mirror of
https://github.com/storytold/wordcraft.git
synced 2026-12-03 22:40:27 +00:00
Compare commits
233
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
06b3cf848f | ||
|
|
19f531c23d | ||
|
|
546549a29c | ||
|
|
46db6fe21e | ||
|
|
a43f4c6258 | ||
|
|
30458a8e0b | ||
|
|
49ef461bc3 | ||
|
|
2bfc68964b | ||
|
|
ddb8fa164b | ||
|
|
8d9a614e15 | ||
|
|
0e4d52a5aa | ||
|
|
9abd324244 | ||
|
|
77dc3e75b9 | ||
|
|
8082743bb8 | ||
|
|
4f4827a7c0 | ||
|
|
006189ca48 | ||
|
|
cbf4e580c1 | ||
|
|
4d9b7d39bf | ||
|
|
3db40dabac | ||
|
|
4ea1fe935a | ||
|
|
9a2d6902f4 | ||
|
|
8a2e47f8c3 | ||
|
|
c4cd11c5ff | ||
|
|
3a7a3b4b95 | ||
|
|
72ef3083e7 | ||
|
|
1ec83a1a2f | ||
|
|
27672b2448 | ||
|
|
67d5297c08 | ||
|
|
4c1dfa6367 | ||
|
|
ccf405de52 | ||
|
|
da072c3e74 | ||
|
|
1580f46cee | ||
|
|
c013dff332 | ||
|
|
ab58acfa09 | ||
|
|
f03da28fb5 | ||
|
|
e976e6aa69 | ||
|
|
48f0ad7496 | ||
|
|
d48ca8d3ec | ||
|
|
425f6d990d | ||
|
|
e3878d2b83 | ||
|
|
a1b04eaa52 | ||
|
|
f98d9c2515 | ||
|
|
d8f1a821c7 | ||
|
|
b400a7bbb8 | ||
|
|
c84c1b9e44 | ||
|
|
bee380b2e8 | ||
|
|
dc266c5e55 | ||
|
|
95bfd5af43 | ||
|
|
c7bb1c9636 | ||
|
|
463552ac36 | ||
|
|
870bbffddf | ||
|
|
a2d8bbdb4d | ||
|
|
98e617806b | ||
|
|
4f6dbbb5fd | ||
|
|
882bacb858 | ||
|
|
3487354a1b | ||
|
|
991b590021 | ||
|
|
549748efec | ||
|
|
bf7ce2509c | ||
|
|
f5c9da1b70 | ||
|
|
c8c78e0fab | ||
|
|
dd42e032fc | ||
|
|
438223240c | ||
|
|
6c80ff1de1 | ||
|
|
6585dbbfca | ||
|
|
83a2e63257 | ||
|
|
e3a913a4d3 | ||
|
|
25f126f48b | ||
|
|
ba8bc15d89 | ||
|
|
30792edab8 | ||
|
|
2094505e3a | ||
|
|
7db2784719 | ||
|
|
cbea96e5e9 | ||
|
|
0d04e94422 | ||
|
|
e26c73df7a | ||
|
|
ed33f21784 | ||
|
|
6b021d557d | ||
|
|
5bfdfc3bf6 | ||
|
|
2ed77bdb93 | ||
|
|
d01c843aa2 | ||
|
|
cde21126d2 | ||
|
|
42f157b53f | ||
|
|
34a93e9123 | ||
|
|
9f7fcb88a7 | ||
|
|
da69216eeb | ||
|
|
a668eba449 | ||
|
|
b7c34c3e1e | ||
|
|
3c9c0219b8 | ||
|
|
b185aaf839 | ||
|
|
03439ff33f | ||
|
|
93573f56e6 | ||
|
|
cb1c530240 | ||
|
|
dc5f5852dd | ||
|
|
b4cb84ea5d | ||
|
|
faebf07b9a | ||
|
|
acc1233da0 | ||
|
|
c1a0484d81 | ||
|
|
f6f7e9414e | ||
|
|
1de5a93974 | ||
|
|
9f43aa6ec1 | ||
|
|
f2e2c78c4b | ||
|
|
fe22b29c5f | ||
|
|
7f86031339 | ||
|
|
10fcb05b15 | ||
|
|
1a05479d99 | ||
|
|
fc0acd93b9 | ||
|
|
5c2e7eb296 | ||
|
|
cc7f9e2688 | ||
|
|
a67df42aa8 | ||
|
|
27dea96335 | ||
|
|
3c5aeef936 | ||
|
|
bcf2aa3b03 | ||
|
|
87d5e537e2 | ||
|
|
175d2eabe6 | ||
|
|
1405e7e8cb | ||
|
|
f1e8793b7a | ||
|
|
951e6b230d | ||
|
|
f55fabaac6 | ||
|
|
faa032ec12 | ||
|
|
989a377de9 | ||
|
|
78b0a6929c | ||
|
|
870bec1839 | ||
|
|
e819a03435 | ||
|
|
77c0a29922 | ||
|
|
d66a7d3bf9 | ||
|
|
5efc89e5ea | ||
|
|
010134fb8e | ||
|
|
08b8d71ece | ||
|
|
d05c629fc0 | ||
|
|
f33b5f8551 | ||
|
|
4bac1b4da0 | ||
|
|
17a13fd901 | ||
|
|
aeba356814 | ||
|
|
0c7ad0e0f0 | ||
|
|
91cb502355 | ||
|
|
d46ecf3ab1 | ||
|
|
8286638f79 | ||
|
|
dd2d40a5f5 | ||
|
|
ee05e88fa0 | ||
|
|
81aae389b3 | ||
|
|
8803a95a2d | ||
|
|
adef1253bb | ||
|
|
ff271a34e8 | ||
|
|
52d50bd830 | ||
|
|
6ebd483b14 | ||
|
|
be2d9021bf | ||
|
|
3f9fc816bf | ||
|
|
8654ed1319 | ||
|
|
7777eba6e4 | ||
|
|
4722d7d2fe | ||
|
|
81a367be13 | ||
|
|
989fa17544 | ||
|
|
eccf146bca | ||
|
|
1a0b33f671 | ||
|
|
523c905c6d | ||
|
|
ce2f7789f4 | ||
|
|
539d9ce9d6 | ||
|
|
ccf6340262 | ||
|
|
41e2164cd0 | ||
|
|
861bed3fdd | ||
|
|
6010893891 | ||
|
|
8427de0edb | ||
|
|
1789fd7b4d | ||
|
|
83676d584a | ||
|
|
ec29711caf | ||
|
|
2bce6ed613 | ||
|
|
f674177095 | ||
|
|
03b20a6ca9 | ||
|
|
e27a3bbdfc | ||
|
|
c93359d997 | ||
|
|
cb0aeadd2f | ||
|
|
2e9699c519 | ||
|
|
4afcb2812f | ||
|
|
834c8054cf | ||
|
|
d789f82465 | ||
|
|
540bd57931 | ||
|
|
6da8a86a41 | ||
|
|
11790205d1 | ||
|
|
b73210feeb | ||
|
|
af9dca95de | ||
|
|
6eb03bf4ea | ||
|
|
9d005a6a40 | ||
|
|
0bef53685f | ||
|
|
f0b5298dc4 | ||
|
|
95d1c1b4be | ||
|
|
b664721fb1 | ||
|
|
1abb47e788 | ||
|
|
2c7df2fb96 | ||
|
|
f2c9880298 | ||
|
|
1392290eec | ||
|
|
afaea9484c | ||
|
|
609aa80e5e | ||
|
|
cdec6b459f | ||
|
|
3310e9f5ee | ||
|
|
554a7d689e | ||
|
|
2c32076416 | ||
|
|
19b8dfece6 | ||
|
|
82567c2c61 | ||
|
|
376a714e73 | ||
|
|
9a81b9a88d | ||
|
|
100dfb3c42 | ||
|
|
e88b44df12 | ||
|
|
bc0c9e4da5 | ||
|
|
104fa6133d | ||
|
|
7f8283a77f | ||
|
|
833082618a | ||
|
|
b687f1cd6f | ||
|
|
c7b4310dc1 | ||
|
|
778ccf6db3 | ||
|
|
8f8bec4ad7 | ||
|
|
da295eb0c5 | ||
|
|
022be202c1 | ||
|
|
824a5e2c1d | ||
|
|
a620ad3587 | ||
|
|
7612fe17db | ||
|
|
f4862c6b0e | ||
|
|
7fd2dc9127 | ||
|
|
f420ef4d6a | ||
|
|
6a35fc23a7 | ||
|
|
cf0f6876b9 | ||
|
|
979077101f | ||
|
|
c120c09423 | ||
|
|
61ef4aab3c | ||
|
|
1336bc27cb | ||
|
|
a525210f48 | ||
|
|
892235af06 | ||
|
|
e14f85661b | ||
|
|
6997afcc34 | ||
|
|
d3096ed0fb | ||
|
|
0074cb6ac6 | ||
|
|
3c44fc6443 | ||
|
|
dc515b6128 | ||
|
|
ab35bfa946 |
Generated
+112
-126
@@ -1173,7 +1173,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"craft-automation",
|
||||
"craft-behavior",
|
||||
@@ -1214,7 +1214,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-appkit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"objc2 0.6.5",
|
||||
@@ -1226,7 +1226,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-atomic"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"rustix 1.1.6",
|
||||
]
|
||||
@@ -1234,7 +1234,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-automation"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-behavior",
|
||||
@@ -1259,7 +1259,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-behavior"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"bitflags 2.13.2",
|
||||
@@ -1277,7 +1277,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-browse"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-docpath",
|
||||
@@ -1295,12 +1295,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cfb"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
|
||||
[[package]]
|
||||
name = "craft-cloud-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"egui",
|
||||
]
|
||||
@@ -1308,7 +1308,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cms"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"md-5",
|
||||
"rayon",
|
||||
@@ -1317,12 +1317,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
|
||||
[[package]]
|
||||
name = "craft-color"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
@@ -1330,7 +1330,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-color-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-cms",
|
||||
@@ -1350,7 +1350,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-control"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"craft-control-protocol",
|
||||
"craft-platform",
|
||||
@@ -1361,7 +1361,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-control-protocol"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
"serde_json",
|
||||
@@ -1371,7 +1371,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dds"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
]
|
||||
@@ -1379,7 +1379,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dialogs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"craft-appkit",
|
||||
@@ -1405,24 +1405,24 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-doc-binary"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-cfb",
|
||||
"craft-codepage",
|
||||
"craft-offcrypto",
|
||||
"craft-wordmodel",
|
||||
"image",
|
||||
"log",
|
||||
"md4",
|
||||
"miniz_oxide 0.9.1",
|
||||
"sha1 0.11.0",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-docpath"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
@@ -1430,7 +1430,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-docx"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"chrono",
|
||||
@@ -1450,7 +1450,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-draw"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-color-ui",
|
||||
@@ -1469,7 +1469,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-drawingml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-xml",
|
||||
@@ -1481,7 +1481,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-flow"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"craft-wordmodel",
|
||||
"image",
|
||||
@@ -1491,7 +1491,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-catalog"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"fontique",
|
||||
"harfrust 0.13.3",
|
||||
@@ -1506,7 +1506,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-manager"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-font-catalog",
|
||||
@@ -1525,7 +1525,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-os-windows"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"windows-registry",
|
||||
"windows-sys 0.61.2",
|
||||
@@ -1534,7 +1534,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-store"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"cap-primitives",
|
||||
"craft-atomic",
|
||||
@@ -1557,7 +1557,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-subset"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"brotli 9.1.3",
|
||||
"harfbuzz-subset-sys",
|
||||
@@ -1570,7 +1570,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"craft-font-subset",
|
||||
]
|
||||
@@ -1578,7 +1578,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-gpu"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"egui-wgpu",
|
||||
"log",
|
||||
@@ -1590,7 +1590,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-host"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"craft-i18n",
|
||||
@@ -1603,7 +1603,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-html"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"craft-codepage",
|
||||
"craft-flow",
|
||||
@@ -1616,7 +1616,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-i18n"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"brotli 9.1.3",
|
||||
"brotli-decompressor 6.3.1",
|
||||
@@ -1646,7 +1646,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-image-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"craft-dds",
|
||||
"craft-jpeg",
|
||||
@@ -1673,7 +1673,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-imaging"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-color-ui",
|
||||
@@ -1691,7 +1691,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -1699,7 +1699,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-keymap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"craft-host",
|
||||
"craft-i18n",
|
||||
@@ -1714,7 +1714,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-latex"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"craft-flow",
|
||||
"craft-math",
|
||||
@@ -1725,7 +1725,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-markdown"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"craft-flow",
|
||||
"craft-html",
|
||||
@@ -1735,7 +1735,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-math"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"craft-xml",
|
||||
"roxmltree",
|
||||
@@ -1745,7 +1745,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-mcp-server"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
@@ -1753,7 +1753,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-menu"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -1771,7 +1771,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metadata"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"brotli-decompressor 6.3.1",
|
||||
"chrono",
|
||||
@@ -1783,7 +1783,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metafile"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"image",
|
||||
@@ -1794,7 +1794,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-mime"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"chrono",
|
||||
@@ -1805,7 +1805,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-nightly"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"uds_windows",
|
||||
"winsafe",
|
||||
@@ -1814,7 +1814,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-odf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"base64 0.23.1",
|
||||
@@ -1840,7 +1840,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ods"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"craft-odf",
|
||||
"craft-sheet",
|
||||
@@ -1851,7 +1851,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-offcrypto"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"base64 0.23.1",
|
||||
@@ -1868,7 +1868,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-opc"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"craft-xml",
|
||||
"craft-zip",
|
||||
@@ -1879,7 +1879,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pages"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -1895,7 +1895,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"krilla",
|
||||
"serde",
|
||||
@@ -1905,7 +1905,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-platform"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"arboard",
|
||||
"async-channel",
|
||||
@@ -1943,7 +1943,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-print"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -1967,7 +1967,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-proof"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"log",
|
||||
"miniz_oxide 0.9.1",
|
||||
@@ -1978,7 +1978,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-quit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"dispatch2",
|
||||
"egui",
|
||||
@@ -1991,7 +1991,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-review"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-behavior",
|
||||
@@ -2010,7 +2010,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-rtf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"craft-codepage",
|
||||
"craft-flow",
|
||||
@@ -2023,7 +2023,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-settings"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"craft-host",
|
||||
@@ -2040,17 +2040,17 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-sheet"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
|
||||
[[package]]
|
||||
name = "craft-ssip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
|
||||
[[package]]
|
||||
name = "craft-svg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"craft-xml",
|
||||
"flate2",
|
||||
@@ -2067,7 +2067,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-table"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -2079,7 +2079,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-text"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2103,7 +2103,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-theme"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"craft-tracked",
|
||||
@@ -2118,7 +2118,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-theme-store"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"craft-behavior",
|
||||
@@ -2133,7 +2133,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2143,7 +2143,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-time"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2152,7 +2152,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-timeline"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -2167,12 +2167,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-tracked"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"craft-cloud-ui",
|
||||
"craft-ui-canvas",
|
||||
@@ -2186,7 +2186,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-canvas"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-font-catalog",
|
||||
@@ -2203,7 +2203,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-contract"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"craft-behavior",
|
||||
@@ -2241,7 +2241,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-macros"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"proc-macro-crate",
|
||||
"proc-macro2",
|
||||
@@ -2252,7 +2252,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-panels"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2270,7 +2270,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-patterns"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2291,7 +2291,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-shell"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2312,7 +2312,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-test-kit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2323,7 +2323,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-widgets"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2342,7 +2342,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
@@ -2374,7 +2374,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-web-api"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"serde_json",
|
||||
@@ -2385,7 +2385,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-web-host"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"craft-host",
|
||||
"craft-platform",
|
||||
@@ -2397,7 +2397,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-win32"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"winsafe",
|
||||
]
|
||||
@@ -2405,7 +2405,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-window"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"craft-appkit",
|
||||
"craft-atomic",
|
||||
@@ -2437,7 +2437,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-wordmodel"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-math",
|
||||
@@ -2451,7 +2451,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xls"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"craft-cfb",
|
||||
"craft-sheet",
|
||||
@@ -2464,7 +2464,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xlsx"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"craft-drawingml",
|
||||
"craft-opc",
|
||||
@@ -2476,7 +2476,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
@@ -2486,7 +2486,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-zip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2842,7 +2842,7 @@ checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
|
||||
[[package]]
|
||||
name = "ecolor"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"emath",
|
||||
@@ -2875,7 +2875,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "eframe"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -2910,7 +2910,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"ahash",
|
||||
@@ -2929,7 +2929,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui-wgpu"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -2948,7 +2948,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui-winit"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff"
|
||||
dependencies = [
|
||||
"accesskit_winit",
|
||||
"arboard",
|
||||
@@ -2974,7 +2974,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui_extras"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"egui",
|
||||
@@ -2987,7 +2987,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui_glow"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"egui",
|
||||
@@ -3000,7 +3000,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui_kittest"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff"
|
||||
dependencies = [
|
||||
"dify",
|
||||
"eframe",
|
||||
@@ -3026,7 +3026,7 @@ checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
|
||||
[[package]]
|
||||
name = "emath"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
@@ -3107,7 +3107,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "epaint"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -3133,7 +3133,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "epaint_default_fonts"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff"
|
||||
dependencies = [
|
||||
"brotli 9.1.3",
|
||||
"brotli-decompressor 6.3.1",
|
||||
@@ -3866,7 +3866,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
|
||||
[[package]]
|
||||
name = "hayro-cmap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"brotli 8.0.4",
|
||||
"hayro-postscript",
|
||||
@@ -3875,7 +3875,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-interpret"
|
||||
version = "0.7.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"hayro-cmap",
|
||||
@@ -3893,7 +3893,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-jbig2"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"fearless_simd",
|
||||
"hayro-ccitt",
|
||||
@@ -3911,12 +3911,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-postscript"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
|
||||
[[package]]
|
||||
name = "hayro-syntax"
|
||||
version = "0.7.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hayro-ccitt",
|
||||
@@ -4645,7 +4645,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "krilla"
|
||||
version = "0.8.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bumpalo",
|
||||
@@ -4784,7 +4784,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
|
||||
[[package]]
|
||||
name = "linesweeper"
|
||||
version = "0.5.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
dependencies = [
|
||||
"arrayvec",
|
||||
"kurbo",
|
||||
@@ -8454,19 +8454,6 @@ dependencies = [
|
||||
"wayland-scanner",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wayland-protocols-plasma"
|
||||
version = "0.3.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2b6d8cf1eb2c1c31ed1f5643c88a6e53538129d4af80030c8cabd1f9fa884d91"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"wayland-backend",
|
||||
"wayland-client",
|
||||
"wayland-protocols",
|
||||
"wayland-scanner",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wayland-protocols-wlr"
|
||||
version = "0.3.12"
|
||||
@@ -8991,7 +8978,7 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
|
||||
[[package]]
|
||||
name = "winit"
|
||||
version = "0.30.13"
|
||||
source = "git+https://github.com/storytold/winit.git?rev=0dfcec0eb62fda5904137a63a6dd0c3d83295f45#0dfcec0eb62fda5904137a63a6dd0c3d83295f45"
|
||||
source = "git+https://github.com/storytold/winit.git?rev=3fd7ae64762f82a73b78bd24f453f82c4291067d#3fd7ae64762f82a73b78bd24f453f82c4291067d"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"android-activity",
|
||||
@@ -9030,7 +9017,6 @@ dependencies = [
|
||||
"wayland-backend",
|
||||
"wayland-client",
|
||||
"wayland-protocols",
|
||||
"wayland-protocols-plasma",
|
||||
"web-sys",
|
||||
"web-time",
|
||||
"windows-sys 0.52.0",
|
||||
@@ -10051,19 +10037,19 @@ dependencies = [
|
||||
[[patch.unused]]
|
||||
name = "egui_demo_lib"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff"
|
||||
|
||||
[[patch.unused]]
|
||||
name = "egui_inspection"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff"
|
||||
|
||||
[[patch.unused]]
|
||||
name = "egui_system_font_provider"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f11ebbd177bf7d4ff#399fc6e0ea65059e37de680f11ebbd177bf7d4ff"
|
||||
|
||||
[[patch.unused]]
|
||||
name = "hayro"
|
||||
version = "0.7.1"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
|
||||
|
||||
+54
-54
@@ -37,22 +37,22 @@ wordcraft-pdf = { path = "crates/pdf" }
|
||||
# reads the ca-valencia pack), #589 (French elision suggestions first), #497 (flag-based
|
||||
# compounding), #496 (review follow-ups, en-AU) and the merged #482–#490/#495 stack; the font
|
||||
# store's `language-pack` kind is #486 (CP4.1).
|
||||
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
|
||||
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
|
||||
wordcraft-engine = { path = "crates/engine" }
|
||||
wordcraft-mcp = { path = "crates/mcp" }
|
||||
wordcraft-zotero = { path = "crates/zotero" }
|
||||
wordcraft-control-key = { path = "crates/control-key" }
|
||||
wordcraft-ui-egui = { path = "crates/ui-egui" }
|
||||
wordcraft-validate = { path = "crates/validate" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", default-features = false }
|
||||
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0", default-features = false }
|
||||
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35" }
|
||||
|
||||
# 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 = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", default-features = false, features = ["write"] }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0", default-features = false, features = ["write"] }
|
||||
|
||||
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", features = ["doc"] }
|
||||
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", features = ["text"] }
|
||||
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", features = ["flow"] }
|
||||
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", features = ["detect"] }
|
||||
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
|
||||
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
|
||||
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0", features = ["doc"] }
|
||||
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
|
||||
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
|
||||
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0", features = ["text"] }
|
||||
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
|
||||
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0", features = ["flow"] }
|
||||
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
|
||||
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0", features = ["detect"] }
|
||||
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
|
||||
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
|
||||
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
|
||||
# zlib streams (compressed metafile pictures in `.doc` drawings); already in the lock as a dependency of other crates.
|
||||
miniz_oxide = "0.9"
|
||||
cfb = "0.15"
|
||||
@@ -174,27 +174,27 @@ debug = 0
|
||||
# The framework's patches, which Cargo does not carry over to dependents: its vendored crates from craft-libs,
|
||||
# and the egui and winit forks it builds with.
|
||||
[patch.crates-io]
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
|
||||
hayro = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "0dfcec0eb62fda5904137a63a6dd0c3d83295f45" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35" }
|
||||
hayro = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "3fd7ae64762f82a73b78bd24f453f82c4291067d" }
|
||||
|
||||
|
||||
+179
-134
@@ -463,6 +463,46 @@ fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
|
||||
Some(launch_profile::passthrough_args(early.passthrough_args, had_separator))
|
||||
}
|
||||
|
||||
/// Runs the app with the windowless root when `windowless` is set, and with the visible root when it is not. eframe
|
||||
/// refuses a windowless root on a session that cannot run it before it calls the creator, which then stays in its
|
||||
/// cell for a retry with the visible root: the app always starts.
|
||||
fn run_with_visible_root_fallback(
|
||||
creator: eframe::AppCreator<'static>,
|
||||
windowless: Arc<std::sync::atomic::AtomicBool>,
|
||||
mut options: eframe::NativeOptions,
|
||||
) -> eframe::Result {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
let creator = std::rc::Rc::new(std::cell::RefCell::new(Some(creator)));
|
||||
let name = wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity());
|
||||
let run = |options: eframe::NativeOptions| {
|
||||
let creator = creator.clone();
|
||||
eframe::run_native(
|
||||
name,
|
||||
options,
|
||||
Box::new(move |cc| match creator.borrow_mut().take() {
|
||||
Some(create) => create(cc),
|
||||
None => Err("the app was already created".into()),
|
||||
}),
|
||||
)
|
||||
};
|
||||
let on = windowless.load(Relaxed);
|
||||
// The clone keeps no event-loop hook, which only the X11 start sets and that start is windowed.
|
||||
let mut visible_root = on.then(|| options.clone());
|
||||
if on {
|
||||
options.root_viewport_mode = eframe::RootViewportMode::Windowless;
|
||||
}
|
||||
let result = run(options);
|
||||
if let Err(eframe::Error::UnsupportedConfiguration(reason)) = &result
|
||||
&& let Some(options) = visible_root.take()
|
||||
&& creator.borrow().is_some()
|
||||
{
|
||||
log::warn!("windowless root unavailable ({reason}); starting with a visible root window");
|
||||
windowless.store(false, Relaxed);
|
||||
return run(options);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Parses the command line, installs logging and the panic hook, restores preferences and window
|
||||
/// geometry, opens requested documents or the Start screen, starts the control server when
|
||||
/// asked, and runs the eframe event loop.
|
||||
@@ -705,147 +745,152 @@ fn main() -> eframe::Result {
|
||||
let noticed_for_exit = unclean_notice_shown.clone();
|
||||
let noticed_in_window = unclean_notice_shown.clone();
|
||||
let exit_settings = settings.clone();
|
||||
let result = eframe::run_native(
|
||||
wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity()),
|
||||
options,
|
||||
Box::new(move |cc| {
|
||||
let ctx = cc.egui_ctx.clone();
|
||||
let _ = repaint.set(ctx.clone());
|
||||
let wake = {
|
||||
let ctx = ctx.clone();
|
||||
move || ctx.request_repaint()
|
||||
};
|
||||
// The interface language: the saved choice, else the system's.
|
||||
let lang = wordcraft_ui_egui::i18n::Lang::from_pref(&settings.lock().get().language);
|
||||
let (file_service, panels) = FileService::new(Wake::new(wake.clone()));
|
||||
let host = Arc::new(
|
||||
Host::builder(wordcraft_ui_egui::APP)
|
||||
.i18n(wordcraft_ui_egui::i18n::catalogs())
|
||||
.files(Arc::new(file_service))
|
||||
.settings(Arc::new(settings.clone()))
|
||||
.lang(lang.craft_lang())
|
||||
.build(),
|
||||
);
|
||||
let shell = ShellInfo::current().backend(if x11 { Backend::X11 } else { Backend::from_env() });
|
||||
let spec = InstallSpec::new(shell, Arc::new(SystemWindows))
|
||||
.app_id(wordcraft_ui_egui::os_window::app_id())
|
||||
.system(SystemReader::start(wake))
|
||||
.clipboard(Clipboard::new(SystemClipboard::new().decoder(decode_png)))
|
||||
.placement(placement);
|
||||
// PLAN: assumed `wordcraft_ui_egui::ui_fonts` re-exports sh.A10's `app::fonts::ui_fonts` (`mod app` is private; app-hub/shell-w11).
|
||||
embed::install(&ctx, spec, &wordcraft_ui_egui::ui_fonts(lang)).map_err(|e| format!("the runtime could not be installed: {e}"))?;
|
||||
// The system region picks the new document's paper, the units and the decimal
|
||||
// separator (#838).
|
||||
let region = region::system();
|
||||
let doc = if sample { wordcraft_engine::sample::sample_document() } else { wordcraft_engine::blank_document(®ion) };
|
||||
let mut session = Session::new(doc);
|
||||
session.system_region = region;
|
||||
// The custom dictionary's words (#40) count as loaded settings.
|
||||
if prefs::enabled()
|
||||
&& let Some(path) = prefs::user_dict_path()
|
||||
{
|
||||
prefs::load_user_dictionary(&mut session, &settings, path);
|
||||
// The root window is never shown (ADR 0001): eframe runs a windowless root and every document is a child
|
||||
// window. X11, XWayland and BSD on X11 cannot, so they keep the visible root (the ADR's amendment). The mode
|
||||
// is read by the app creator, which runs once the mode is settled.
|
||||
let windowless = Arc::new(std::sync::atomic::AtomicBool::new(!x11));
|
||||
let windowless_in_app = windowless.clone();
|
||||
let creator: eframe::AppCreator<'static> = Box::new(move |cc| {
|
||||
let ctx = cc.egui_ctx.clone();
|
||||
let _ = repaint.set(ctx.clone());
|
||||
let wake = {
|
||||
let ctx = ctx.clone();
|
||||
move || ctx.request_repaint()
|
||||
};
|
||||
// The interface language: the saved choice, else the system's.
|
||||
let lang = wordcraft_ui_egui::i18n::Lang::from_pref(&settings.lock().get().language);
|
||||
let (file_service, panels) = FileService::new(Wake::new(wake.clone()));
|
||||
let host = Arc::new(
|
||||
Host::builder(wordcraft_ui_egui::APP)
|
||||
.i18n(wordcraft_ui_egui::i18n::catalogs())
|
||||
.files(Arc::new(file_service))
|
||||
.settings(Arc::new(settings.clone()))
|
||||
.lang(lang.craft_lang())
|
||||
.build(),
|
||||
);
|
||||
let shell = ShellInfo::current().backend(if x11 { Backend::X11 } else { Backend::from_env() });
|
||||
let mut spec = InstallSpec::new(shell, Arc::new(SystemWindows))
|
||||
.app_id(wordcraft_ui_egui::os_window::app_id())
|
||||
.system(SystemReader::start(wake))
|
||||
.clipboard(Clipboard::new(SystemClipboard::new().decoder(decode_png)))
|
||||
.placement(placement);
|
||||
// The runtime and eframe must agree on the root.
|
||||
if windowless_in_app.load(std::sync::atomic::Ordering::Relaxed) {
|
||||
spec = spec.windowless_root();
|
||||
}
|
||||
// PLAN: assumed `wordcraft_ui_egui::ui_fonts` re-exports sh.A10's `app::fonts::ui_fonts` (`mod app` is private; app-hub/shell-w11).
|
||||
embed::install(&ctx, spec, &wordcraft_ui_egui::ui_fonts(lang)).map_err(|e| format!("the runtime could not be installed: {e}"))?;
|
||||
// The system region picks the new document's paper, the units and the decimal
|
||||
// separator (#838).
|
||||
let region = region::system();
|
||||
let doc = if sample { wordcraft_engine::sample::sample_document() } else { wordcraft_engine::blank_document(®ion) };
|
||||
let mut session = Session::new(doc);
|
||||
session.system_region = region;
|
||||
// The custom dictionary's words (#40) count as loaded settings.
|
||||
if prefs::enabled()
|
||||
&& let Some(path) = prefs::user_dict_path()
|
||||
{
|
||||
prefs::load_user_dictionary(&mut session, &settings, path);
|
||||
}
|
||||
let spool = Spool::new(host.jobs_shared().clone());
|
||||
let mut app = WordApp::new(session, services(spool.clone(), intake, nightly)).with_host(host).with_settings(settings.clone());
|
||||
// Drawn by the processor (WARP, llvmpipe; #2221), animations that follow the system stop.
|
||||
if let Some(state) = &cc.wgpu_render_state {
|
||||
let info = state.adapter.get_info();
|
||||
let software = info.device_type == eframe::wgpu::DeviceType::Cpu;
|
||||
if software {
|
||||
log::warn!("graphics: drawing in software on {} ({:?}): animations that follow the system are off", info.name, info.backend);
|
||||
}
|
||||
let spool = Spool::new(host.jobs_shared().clone());
|
||||
let mut app = WordApp::new(session, services(spool.clone(), intake, nightly)).with_host(host).with_settings(settings.clone());
|
||||
// Drawn by the processor (WARP, llvmpipe; #2221), animations that follow the system stop.
|
||||
if let Some(state) = &cc.wgpu_render_state {
|
||||
let info = state.adapter.get_info();
|
||||
let software = info.device_type == eframe::wgpu::DeviceType::Cpu;
|
||||
if software {
|
||||
log::warn!("graphics: drawing in software on {} ({:?}): animations that follow the system are off", info.name, info.backend);
|
||||
}
|
||||
app.set_software_drawing(software);
|
||||
app.set_software_drawing(software);
|
||||
}
|
||||
// PLAN: writer note 9 puts `with_settings` after `with_control`; it comes first here because
|
||||
// the region check below reads the saved region the settings apply.
|
||||
if std::env::var("WORDCRAFT_FILE_DIALOG").is_ok_and(|v| v.trim().eq_ignore_ascii_case("builtin")) {
|
||||
app = app.with_fallback_chooser(true);
|
||||
}
|
||||
if nightly {
|
||||
// The Launcher installs Nightly; Help › Check for Updates says so instead.
|
||||
app.use_launcher_updates();
|
||||
} else {
|
||||
app.set_startup_update_check(true);
|
||||
// After the preferences, so the reason it gives is in the interface language.
|
||||
if updates_unsafe {
|
||||
app.disable_self_update();
|
||||
}
|
||||
// PLAN: writer note 9 puts `with_settings` after `with_control`; it comes first here because
|
||||
// the region check below reads the saved region the settings apply.
|
||||
if std::env::var("WORDCRAFT_FILE_DIALOG").is_ok_and(|v| v.trim().eq_ignore_ascii_case("builtin")) {
|
||||
app = app.with_fallback_chooser(true);
|
||||
}
|
||||
// Language packs from the suite's font store; an Install click is the person's own.
|
||||
// Nightly keeps its own store in the profile, so a pack installed there is not a
|
||||
// change to the stable apps' shared fonts.
|
||||
match launch_profile::current().root() {
|
||||
Some(root) => wordcraft_engine::packs::use_font_store_in(root.join("FontStore"), true),
|
||||
None => {
|
||||
wordcraft_engine::packs::use_font_store(true);
|
||||
}
|
||||
if nightly {
|
||||
// The Launcher installs Nightly; Help › Check for Updates says so instead.
|
||||
app.use_launcher_updates();
|
||||
} else {
|
||||
app.set_startup_update_check(true);
|
||||
// After the preferences, so the reason it gives is in the interface language.
|
||||
if updates_unsafe {
|
||||
app.disable_self_update();
|
||||
}
|
||||
}
|
||||
// A region chosen in File › Options replaces the system's for the first blank
|
||||
// document too (#838).
|
||||
if !sample && app.session.prefs.region.is_some() {
|
||||
let doc = app.session.blank_document();
|
||||
app.replace_startup_document(doc);
|
||||
}
|
||||
app.tell_about_font_downloads();
|
||||
if prefs::enabled()
|
||||
&& let Some(dir) = wordcraft_control_key::settings_dir()
|
||||
{
|
||||
let ctx = ctx.clone();
|
||||
if let Err(e) = app.session.enable_recovery(dir.join("recovery"), Arc::new(move || ctx.request_repaint())) {
|
||||
log::warn!("local recovery unavailable: {e}");
|
||||
}
|
||||
// Language packs from the suite's font store; an Install click is the person's own.
|
||||
// Nightly keeps its own store in the profile, so a pack installed there is not a
|
||||
// change to the stable apps' shared fonts.
|
||||
match launch_profile::current().root() {
|
||||
Some(root) => wordcraft_engine::packs::use_font_store_in(root.join("FontStore"), true),
|
||||
None => {
|
||||
wordcraft_engine::packs::use_font_store(true);
|
||||
}
|
||||
}
|
||||
let mut control_server = None;
|
||||
if !nightly
|
||||
&& let Some(port) = control.port
|
||||
&& let Some((rx, started)) = control_server::start(&control, port, WindowHost::of(&ctx), wordcraft_control_key::settings_dir().as_deref())
|
||||
{
|
||||
app = app.with_control(ControlChannel::new(rx));
|
||||
control_server = Some(started);
|
||||
}
|
||||
// Nothing to open (no files, no sample, no control channel driving the editor): start
|
||||
// on File › Home, as Word does (#766), unless the Start screen option is off. Files
|
||||
// the OS hands over later open on top of it and close it.
|
||||
if files.is_empty() && other_files.is_empty() && !sample && control.port.is_none() {
|
||||
app.start_screen();
|
||||
}
|
||||
// A Word template named here starts a new document based on it (#3433).
|
||||
for f in files {
|
||||
if let Err(e) = app.open_from_platform(&f, None) {
|
||||
app.report_open_failure(&f, &e);
|
||||
}
|
||||
// A region chosen in File › Options replaces the system's for the first blank
|
||||
// document too (#838).
|
||||
if !sample && app.session.prefs.region.is_some() {
|
||||
let doc = app.session.blank_document();
|
||||
app.replace_startup_document(doc);
|
||||
}
|
||||
app.tell_about_font_downloads();
|
||||
if prefs::enabled()
|
||||
&& let Some(dir) = wordcraft_control_key::settings_dir()
|
||||
{
|
||||
let ctx = ctx.clone();
|
||||
if let Err(e) = app.session.enable_recovery(dir.join("recovery"), Arc::new(move || ctx.request_repaint())) {
|
||||
log::warn!("local recovery unavailable: {e}");
|
||||
}
|
||||
}
|
||||
let mut control_server = None;
|
||||
if !nightly
|
||||
&& let Some(port) = control.port
|
||||
&& let Some((rx, started)) =
|
||||
control_server::start(&control, port, WindowHost::of(&ctx), wordcraft_control_key::settings_dir().as_deref())
|
||||
{
|
||||
app = app.with_control(ControlChannel::new(rx));
|
||||
control_server = Some(started);
|
||||
}
|
||||
// Nothing to open (no files, no sample, no control channel driving the editor): start
|
||||
// on File › Home, as Word does (#766), unless the Start screen option is off. Files
|
||||
// the OS hands over later open on top of it and close it.
|
||||
if files.is_empty() && other_files.is_empty() && !sample && control.port.is_none() {
|
||||
app.start_screen();
|
||||
}
|
||||
// A Word template named here starts a new document based on it (#3433).
|
||||
for f in files {
|
||||
if let Err(e) = app.open_from_platform(&f, None) {
|
||||
app.report_open_failure(&f, &e);
|
||||
}
|
||||
}
|
||||
for f in other_files {
|
||||
open_non_unicode(&mut app, &f);
|
||||
}
|
||||
// The personal agent files, the session record and the control token all live in the
|
||||
// profile; the app's own services are built with the nightly rule in mind.
|
||||
if let Some(warning) = &session_health_warning {
|
||||
app.status_long(warning.clone());
|
||||
}
|
||||
if previous_nightly_unclean {
|
||||
app.status_long(
|
||||
}
|
||||
for f in other_files {
|
||||
open_non_unicode(&mut app, &f);
|
||||
}
|
||||
// The personal agent files, the session record and the control token all live in the
|
||||
// profile; the app's own services are built with the nightly rule in mind.
|
||||
if let Some(warning) = &session_health_warning {
|
||||
app.status_long(warning.clone());
|
||||
}
|
||||
if previous_nightly_unclean {
|
||||
app.status_long(
|
||||
"The previous WordCraft Nightly session did not finish normally. You can report a problem from Help › About. No diagnostics have been sent.",
|
||||
);
|
||||
noticed_in_window.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
Ok(Box::new(App {
|
||||
#[cfg(target_os = "macos")]
|
||||
native_menu: native_menu::install(&ctx, &app),
|
||||
app,
|
||||
panels,
|
||||
drops,
|
||||
settings,
|
||||
spool,
|
||||
control: control_server,
|
||||
exit: Some(Box::new(move || {
|
||||
nightly_session::finish_once(&session_for_exit, noticed_for_exit.load(std::sync::atomic::Ordering::Relaxed));
|
||||
})),
|
||||
}))
|
||||
}),
|
||||
);
|
||||
noticed_in_window.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
Ok(Box::new(App {
|
||||
#[cfg(target_os = "macos")]
|
||||
native_menu: native_menu::install(&ctx, &app),
|
||||
app,
|
||||
panels,
|
||||
drops,
|
||||
settings,
|
||||
spool,
|
||||
control: control_server,
|
||||
exit: Some(Box::new(move || {
|
||||
nightly_session::finish_once(&session_for_exit, noticed_for_exit.load(std::sync::atomic::Ordering::Relaxed));
|
||||
})),
|
||||
}))
|
||||
});
|
||||
let result = run_with_visible_root_fallback(creator, windowless, options);
|
||||
// The exit hook has run; this is the no-op fallback for a start that created no window.
|
||||
nightly_session::finish_once(&nightly_watch, unclean_notice_shown.load(std::sync::atomic::Ordering::Relaxed));
|
||||
// The app is dropped by now: whatever it saved on the way out is in the store.
|
||||
|
||||
+17
-1
@@ -619,7 +619,8 @@ impl Paragraph {
|
||||
/// The word around `off` (double-click): (start, end) without trailing space.
|
||||
pub fn word_at(&self, off: usize) -> (usize, usize) {
|
||||
let off = self.clamp(off);
|
||||
let is_w = |c: char| crate::bidi::is_word_char(c);
|
||||
// Word's word unit takes a typographic apostrophe (’) like `'`, at either end too (#6517).
|
||||
let is_w = |c: char| crate::bidi::is_word_char(c) || c == '’';
|
||||
let mut a = off;
|
||||
for (i, c) in self.text.get(..off).unwrap_or("").char_indices().rev() {
|
||||
if !is_w(c) {
|
||||
@@ -852,6 +853,21 @@ mod tests {
|
||||
assert_eq!(p.prev_boundary(0), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn word_at_takes_a_typographic_apostrophe_like_a_straight_one() {
|
||||
// Byte offsets: `’` is three bytes. Word: `don’t ` (#6517).
|
||||
let p = Paragraph::with_text("don’t stop", CharProps::default());
|
||||
assert_eq!(p.word_at(1), (0, 8));
|
||||
assert_eq!(p.word_at(2), (0, 8));
|
||||
let p = Paragraph::with_text("the dogs’ bone", CharProps::default());
|
||||
assert_eq!(p.word_at(5), (4, 12));
|
||||
let p = Paragraph::with_text("’tis here", CharProps::default());
|
||||
assert_eq!(p.word_at(3), (0, 7));
|
||||
assert_eq!(p.word_at(4), (0, 7));
|
||||
let p = Paragraph::with_text("well-known", CharProps::default());
|
||||
assert_eq!(p.word_at(1), (0, 4));
|
||||
}
|
||||
|
||||
proptest::proptest! {
|
||||
#[test]
|
||||
fn edits_keep_runs_consistent(ops in proptest::collection::vec((0u8..4, 0usize..40, 0usize..40, "[a-zé ]{0,5}"), 0..40)) {
|
||||
|
||||
@@ -296,6 +296,7 @@ impl NumFormat {
|
||||
use crate::cjk_numbers as cjk;
|
||||
match self {
|
||||
NumFormat::DecimalZero => format!("{n:02}"),
|
||||
NumFormat::Hex => format!("{n:X}"),
|
||||
NumFormat::ThaiNumbers => thai_digits(n),
|
||||
NumFormat::UpperRoman => roman(n).to_uppercase(),
|
||||
NumFormat::LowerRoman => roman(n),
|
||||
@@ -341,7 +342,6 @@ impl NumFormat {
|
||||
NumFormat::Chosung => cjk::chosung(n),
|
||||
NumFormat::Decimal
|
||||
| NumFormat::DecimalHalfWidth
|
||||
| NumFormat::Hex
|
||||
| NumFormat::VietnameseCounting
|
||||
| NumFormat::Hebrew1
|
||||
| NumFormat::Hebrew2
|
||||
@@ -496,13 +496,21 @@ pub fn cardinal_text(n: u32) -> String {
|
||||
let h = format!("{} hundred", words(n / 100));
|
||||
if n.is_multiple_of(100) { h } else { format!("{h} {}", words(n % 100)) }
|
||||
}
|
||||
_ => {
|
||||
1_000..=999_999 => {
|
||||
let th = format!("{} thousand", words(n / 1000));
|
||||
if n.is_multiple_of(1000) { th } else { format!("{th} {}", words(n % 1000)) }
|
||||
}
|
||||
1_000_000..=999_999_999 => {
|
||||
let m = format!("{} million", words(n / 1_000_000));
|
||||
if n.is_multiple_of(1_000_000) { m } else { format!("{m} {}", words(n % 1_000_000)) }
|
||||
}
|
||||
_ => {
|
||||
let b = format!("{} billion", words(n / 1_000_000_000));
|
||||
if n.is_multiple_of(1_000_000_000) { b } else { format!("{b} {}", words(n % 1_000_000_000)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
capitalize(&words(n.min(999_999)))
|
||||
capitalize(&words(n))
|
||||
}
|
||||
|
||||
/// English ordinal words (`Twenty-First`).
|
||||
@@ -1004,6 +1012,17 @@ mod tests {
|
||||
assert_eq!(NumFormat::from_ooxml("klingon"), NumFormat::Decimal, "unknown formats are decimal");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_and_large_number_text() {
|
||||
assert_eq!(NumFormat::Hex.format(10), "A");
|
||||
assert_eq!(NumFormat::Hex.format(15), "F");
|
||||
assert_eq!(NumFormat::Hex.format(16), "10");
|
||||
assert_eq!(NumFormat::Hex.format(255), "FF");
|
||||
assert_eq!(NumFormat::CardinalText.format(1_000_000), "One Million");
|
||||
assert_eq!(NumFormat::OrdinalText.format(1_000_000), "One Millionth");
|
||||
assert_eq!(NumFormat::CardinalText.format(2_000_000_000), "Two Billion");
|
||||
}
|
||||
|
||||
/// #5757: Thai numbers are the decimal number in Thai digits, every digit, at any length.
|
||||
#[test]
|
||||
fn thai_numbers_use_thai_digits() {
|
||||
|
||||
@@ -177,6 +177,19 @@ fn glossary_value_from_shared(
|
||||
})
|
||||
}
|
||||
|
||||
fn note_separators_from_shared(
|
||||
source: craft_wordmodel::NoteSeparators,
|
||||
graphics: &mut GraphicCache,
|
||||
) -> Result<wordcraft_doc::NoteSeparators, DocxError> {
|
||||
let craft_wordmodel::NoteSeparators { separator, continuation_separator, continuation_notice } = source;
|
||||
let mut blocks = |b: Option<craft_wordmodel::Blocks>| b.map(|b| blocks_from_shared(b, graphics)).transpose();
|
||||
Ok(wordcraft_doc::NoteSeparators {
|
||||
separator: blocks(separator)?,
|
||||
continuation_separator: blocks(continuation_separator)?,
|
||||
continuation_notice: blocks(continuation_notice)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn missing_pictures_from_shared(source: craft_wordmodel::MissingPictures) -> Result<wordcraft_doc::MissingPictures, DocxError> {
|
||||
let mut target = wordcraft_doc::MissingPictures::default();
|
||||
target.truncated = source.truncated;
|
||||
@@ -239,8 +252,8 @@ pub fn from_shared_model(mut source: craft_wordmodel::Document) -> Result<wordcr
|
||||
document.core = convert(core)?;
|
||||
document.sources = convert(sources)?;
|
||||
document.custom_props = convert(custom_props)?;
|
||||
document.footnote_separators = convert(footnote_separators)?;
|
||||
document.endnote_separators = convert(endnote_separators)?;
|
||||
document.footnote_separators = note_separators_from_shared(footnote_separators, &mut graphics)?;
|
||||
document.endnote_separators = note_separators_from_shared(endnote_separators, &mut graphics)?;
|
||||
document.media = media;
|
||||
document.passthrough = passthrough;
|
||||
document.glossary = glossary.into_iter().map(|g| glossary_value_from_shared(g, &mut graphics)).collect::<Result<_, _>>()?;
|
||||
|
||||
@@ -2444,6 +2444,36 @@ fn note_separators_and_continuation_notice_round_trip() {
|
||||
check(&wordcraft_docx::read(&out).unwrap());
|
||||
}
|
||||
|
||||
/// A picture frame shape in a footnote or endnote separator opens as the same shape kind as it does
|
||||
/// in the body, instead of failing the whole document. (The test name dates from when the body
|
||||
/// opened this shape as a rectangle.)
|
||||
#[test]
|
||||
fn a_frame_shape_in_a_note_separator_reads_as_a_rectangle() {
|
||||
let frame = r#"<w:r><w:drawing><wp:inline><wp:extent cx="508000" cy="381000"/><wp:docPr id="1" name="F"/><a:graphic><a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"><wps:wsp><wps:spPr><a:prstGeom prst="frame"/></wps:spPr><wps:bodyPr/></wps:wsp></a:graphicData></a:graphic></wp:inline></w:drawing></w:r>"#;
|
||||
let notes = |root: &str, item: &str| {
|
||||
format!(r#"<w:{root} {W_NS}><w:{item} w:type="separator" w:id="-1"><w:p>{frame}<w:r><w:separator/></w:r></w:p></w:{item}></w:{root}>"#)
|
||||
};
|
||||
let footnotes = notes("footnotes", "footnote");
|
||||
let endnotes = notes("endnotes", "endnote");
|
||||
let bytes = docx(
|
||||
&format!("<w:p>{frame}</w:p>"),
|
||||
&[("rId1", "footnotes", "footnotes.xml"), ("rId2", "endnotes", "endnotes.xml")],
|
||||
&[("word/footnotes.xml", &footnotes), ("word/endnotes.xml", &endnotes)],
|
||||
);
|
||||
let d = wordcraft_docx::read(&bytes).unwrap();
|
||||
let shapes = |p: &Paragraph| -> Vec<(ShapeKind, f32)> {
|
||||
p.objects.iter().filter_map(|o| if let InlineObject::Shape { kind, w, .. } = o { Some((*kind, *w)) } else { None }).collect()
|
||||
};
|
||||
let in_body = shapes(d.body[0].as_para().unwrap());
|
||||
assert_eq!(in_body.len(), 1, "{in_body:?}");
|
||||
assert_eq!(in_body[0].1, 40.0);
|
||||
assert_eq!(in_body[0].0, ShapeKind::Frame);
|
||||
for separators in [&d.footnote_separators, &d.endnote_separators] {
|
||||
let sep = separators.separator.as_ref().unwrap()[0].as_para().unwrap();
|
||||
assert_eq!(shapes(sep), in_body);
|
||||
}
|
||||
}
|
||||
|
||||
/// Issue #534: East Asian number formats are read, labelled and written back as they were; a
|
||||
/// value the format doesn't define is decimal, and a level without `w:ind` has no indent.
|
||||
#[test]
|
||||
|
||||
@@ -703,3 +703,24 @@ fn a_math_name_is_corrected_by_any_character_that_cannot_continue_it() {
|
||||
s.run("equation.type", &json!({"text": r"\alpha+"})).unwrap();
|
||||
assert_eq!(linear(&s), r"\alpha+");
|
||||
}
|
||||
|
||||
/// Paste Formatting keeps an open equation open (matching other formatting commands and
|
||||
/// `cmd::column`), whereas content-pasting commands leave the equation first.
|
||||
#[test]
|
||||
fn paste_formatting_keeps_an_open_equation_open() {
|
||||
let mut s = session();
|
||||
s.run("text.insert", &json!({"text": "source "})).unwrap();
|
||||
s.run("select.text", &json!({"text": "source"})).unwrap();
|
||||
s.run("format.bold", &json!({})).unwrap();
|
||||
s.run("edit.copyFormat", &json!({})).unwrap();
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("insert.equation", &json!({"linear": "x"})).unwrap();
|
||||
let before = s.math.clone();
|
||||
assert!(before.is_some());
|
||||
|
||||
s.run("edit.pasteFormat", &json!({})).unwrap();
|
||||
assert_eq!(s.math, before, "edit.pasteFormat keeps the open equation open");
|
||||
|
||||
s.run("edit.pasteText", &json!({"text": "y"})).unwrap();
|
||||
assert!(s.math.is_none(), "edit.pasteText closes the open equation");
|
||||
}
|
||||
|
||||
@@ -94,9 +94,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.pure(),
|
||||
CommandSpec::new("file.save", "Save", "File", save)
|
||||
.key("Mod+S / Shift+F12 / Alt+Shift+F2")
|
||||
.params(r#"{"path"?: string, "password"?: string (encrypt this and later saves with it, as file.encrypt does), "markup"?: bool (Print Markup for a PDF, PNG, HTML, Markdown or text copy: comments shown; default file.printMarkup), "format"?: "wordml2003" (an .xml file as a Word 2003 XML Document) | "flatopc" (as a Word XML Document, the default; saving over a Word 2003 XML file keeps that format), "strict"?: bool (a .pdf or .png only: refuse, writing nothing, if a character can't be drawn or a picture is missing; see file.strictReport)}"#)
|
||||
.params(r#"{"path"?: string (required with `copy`), "password"?: string (encrypt this and later saves with it, as file.encrypt does), "markup"?: bool (Print Markup for a PDF, PNG, HTML, Markdown or text copy: comments shown; default file.printMarkup), "format"?: "wordml2003" (an .xml file as a Word 2003 XML Document) | "flatopc" (as a Word XML Document, the default; saving over a Word 2003 XML file keeps that format), "strict"?: bool (a .pdf or .png only: refuse, writing nothing, if a character can't be drawn or a picture is missing; see file.strictReport), "copy"?: bool (write a copy at `path`, as File › Export does: the document keeps its own file, unsaved changes and save stamps; not with `password`)}"#)
|
||||
.pure(),
|
||||
CommandSpec::new("file.saveAs", "Save As", "File", save_as).key(super::mac_or("F12 / Mod+Shift+S", "F12 / Alt+F2")).params(r#"{"path": string, "password"?: string, "markup"?: bool, "format"?: string (as file.save), "strict"?: bool (as file.save)}"#).pure(),
|
||||
CommandSpec::new("file.saveAs", "Save As", "File", save_as).key(super::mac_or("F12 / Mod+Shift+S", "F12 / Alt+F2")).params(r#"{"path": string, "password"?: string, "markup"?: bool, "format"?: string (as file.save), "strict"?: bool (as file.save), "copy"?: bool (as file.save)}"#).pure(),
|
||||
// Pure: the password must not land in Repeat or a recorded macro, and it isn't an edit
|
||||
// to undo; it marks the document as changed itself.
|
||||
CommandSpec::new("file.encrypt", "Encrypt with Password", "File › Info › Protect Document", encrypt)
|
||||
@@ -145,7 +145,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
sel_result(s)
|
||||
})
|
||||
.key("Mod+W / Mod+F4")
|
||||
.params(r#"{"force"?: bool (desktop app's control channel and MCP bridge only: without it a document with unsaved changes is an error and stays open; with it the changes are discarded. Headless sessions never ask; file.closeDocument closes a document there)}"#)
|
||||
.params(r#"{"save"?: bool (desktop app's control channel and MCP bridge only: save the document, then close it), "force"?: bool (desktop app's control channel and MCP bridge only: without save or force a document with unsaved changes is an error and stays open; with force the changes are discarded. Headless sessions never ask; file.closeDocument closes a document there)}"#)
|
||||
.pure(),
|
||||
CommandSpec::new("file.closeDocument", "Close Document", "Agents", close_document)
|
||||
.params(r#"{"id"?: n (an open document, see view.switchWindows; default the active one), "force"?: bool (discard unsaved changes; without it a document with unsaved changes is an error and stays open)} → {"closed": id, "active": id, "documents": [{"id", "title", "path", "dirty", "active"}]}; closing the last document leaves a new blank one"#)
|
||||
@@ -342,6 +342,8 @@ pub(crate) fn new_from_template(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let path = p::req_str(v, "path")?;
|
||||
let (mut doc, _) = read_document(s, path, v)?;
|
||||
doc.settings.attached_template = Some(path.to_string());
|
||||
// A new document: not created when the template was. Saving stamps its creation date.
|
||||
doc.core.created.clear();
|
||||
if p::bool(v, "replaceBlank") == Some(true) && s.used_because().is_none() {
|
||||
s.set_document(doc);
|
||||
} else {
|
||||
@@ -393,6 +395,14 @@ fn encrypt(s: &mut Session, v: &Value) -> CmdResult {
|
||||
/// Executes `file.save`: writes the document or text to disk, preserving exact file text for
|
||||
/// unedited Markdown files, and updating session path and dirty state.
|
||||
fn save(s: &mut Session, v: &Value) -> CmdResult {
|
||||
// A copy (File › Export, #6131) is written and nothing else: the document keeps its own file,
|
||||
// its unsaved changes and its save stamps, so the next Save still goes to the original.
|
||||
// It never falls back to the document's own file or opens the Save As picker (whose answer is
|
||||
// an ordinary save that adopts the file).
|
||||
let as_copy = p::bool(v, "copy") == Some(true);
|
||||
if as_copy && p::str(v, "path").is_none() {
|
||||
return Err(CmdError::Params("`copy` needs a `path`: the copy has to go somewhere".into()));
|
||||
}
|
||||
let path = match p::str(v, "path").map(std::path::PathBuf::from).or_else(|| s.path.clone()) {
|
||||
Some(p) => p,
|
||||
None => {
|
||||
@@ -401,6 +411,9 @@ fn save(s: &mut Session, v: &Value) -> CmdResult {
|
||||
}
|
||||
};
|
||||
check_strict_output(p::bool(v, "strict").unwrap_or(false), &path.to_string_lossy())?;
|
||||
if as_copy && v.get("password").is_some_and(|pw| !pw.is_null()) {
|
||||
return Err(CmdError::Params("`password` changes the document's own saves, so it can't come with `copy` (use file.encrypt)".into()));
|
||||
}
|
||||
if let Some(pw) = v.get("password").filter(|pw| !pw.is_null()) {
|
||||
let Some(pw) = pw.as_str().filter(|pw| !pw.is_empty()) else {
|
||||
return Err(CmdError::Params("`password` must be a non-empty string (file.encrypt removes a password)".into()));
|
||||
@@ -443,11 +456,14 @@ fn save(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Some(text) => crate::io::save_text_path(&path, text),
|
||||
None => crate::io::save_path_with(&path, copy.as_ref().unwrap_or(&s.doc), password, &opts),
|
||||
};
|
||||
if let Err(e) = written {
|
||||
(s.doc.settings.zoom, s.doc.core.last_modified_by, s.doc.core.created, s.doc.core.modified, s.doc.core.revision) = before_stamp;
|
||||
return Err(CmdError::Failed(e));
|
||||
}
|
||||
let encrypted = password.is_some() && crate::io::can_encrypt(&path.to_string_lossy());
|
||||
if written.is_err() || as_copy {
|
||||
(s.doc.settings.zoom, s.doc.core.last_modified_by, s.doc.core.created, s.doc.core.modified, s.doc.core.revision) = before_stamp;
|
||||
}
|
||||
written.map_err(CmdError::Failed)?;
|
||||
if as_copy {
|
||||
return Ok(json!({"saved": true, "path": path.to_string_lossy(), "encrypted": encrypted, "copy": true}));
|
||||
}
|
||||
// A save in a format that doesn't keep everything (plain text, Markdown, a page image) is a
|
||||
// copy, except over the document's own file: a note.txt opened and saved is saved (#2376).
|
||||
// A Markdown file saved as another one loses nothing its own save wouldn't: it moves there.
|
||||
|
||||
@@ -209,7 +209,8 @@ fn target(s: &Session) -> Option<(Pos, Pos)> {
|
||||
return Some((a, b));
|
||||
}
|
||||
let p = s.doc.para_at(&a)?;
|
||||
let is_w = |c: char| c.is_alphanumeric() || c == '\'' || c == '_';
|
||||
// Word takes a typographic apostrophe (’) like `'` here (#6517).
|
||||
let is_w = |c: char| c.is_alphanumeric() || matches!(c, '\'' | '’' | '_');
|
||||
let before = p.text.get(..a.off)?.chars().next_back();
|
||||
let after = p.text.get(a.off..)?.chars().next();
|
||||
if before.is_some_and(is_w) && after.is_some_and(is_w) {
|
||||
@@ -351,6 +352,16 @@ fn resolved(s: &Session) -> Vec<ResolvedChar> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether a toggle without a `value` turns its format on. A selection follows its first character
|
||||
/// in document order, as Word does: one that starts formatted loses the format, all of it (#6516).
|
||||
fn turns_on(s: &Session, has: impl Fn(&ResolvedChar) -> bool) -> bool {
|
||||
let chars = resolved(s);
|
||||
if !s.sel.is_collapsed() || selected_text_box(s).is_some() || column_rows(s).is_some() {
|
||||
return !chars.first().is_some_and(has);
|
||||
}
|
||||
!chars.iter().all(has)
|
||||
}
|
||||
|
||||
/// Bold as drawn: a run marked complex script (`w:cs`) or right to left (`w:rtl`) shows its
|
||||
/// complex-script bold.
|
||||
fn shown_bold(r: &ResolvedChar) -> bool {
|
||||
@@ -366,7 +377,7 @@ fn shown_italic(r: &ResolvedChar) -> bool {
|
||||
fn toggle(s: &mut Session, v: &Value, get: fn(&ResolvedChar) -> bool, set: fn(&mut CharProps, bool)) -> CmdResult {
|
||||
let on = match p::bool(v, "value") {
|
||||
Some(b) => b,
|
||||
None => !resolved(s).iter().all(get),
|
||||
None => turns_on(s, get),
|
||||
};
|
||||
apply(s, &|c| set(c, on))
|
||||
}
|
||||
@@ -376,7 +387,7 @@ fn underline(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let on = match (p::bool(v, "value"), style) {
|
||||
(Some(b), _) => b,
|
||||
(None, Some(_)) => true,
|
||||
(None, None) => !resolved(s).iter().all(|r| r.underline != Underline::None),
|
||||
(None, None) => turns_on(s, |r| r.underline != Underline::None),
|
||||
};
|
||||
let u = if on { style.unwrap_or(Underline::Single) } else { Underline::None };
|
||||
apply(s, &|c| c.underline = Some(u))
|
||||
|
||||
@@ -21,7 +21,7 @@ pub use items::{
|
||||
};
|
||||
use items::{cover_page, date_time, drop_cap, drop_cap_off, field, page_number, symbol};
|
||||
use links::{bookmark, delete_bookmark, link, link_targets};
|
||||
pub use links::{bookmark_name_ok, bookmark_range, bookmark_span};
|
||||
pub use links::{bookmark_name_ok, bookmark_range, bookmark_span, selection_is_one_line};
|
||||
pub use objects::{MAX_TABLE_ROWS, base64_decode, base64_encode};
|
||||
use objects::{icon, shape, table, text_box};
|
||||
pub(crate) use objects::{image_ext, picture};
|
||||
|
||||
@@ -205,21 +205,26 @@ pub fn format_date_at_in(fmt: &str, lang: Option<&str>, unix: u64, offset_secs:
|
||||
format_date_parts_in(fmt, lang, y, m as usize, d, hms, days)
|
||||
}
|
||||
|
||||
/// Month and weekday names of a language, as Word writes them in date fields: full names, the
|
||||
/// three-letter forms (`MMM`, `ddd`) being their first three letters, without a full stop.
|
||||
/// Weekdays start on Thursday (1970-01-01).
|
||||
/// Month and weekday names of a language, as Word writes them in date fields: full names and the
|
||||
/// abbreviations used by `MMM` and `ddd`. Weekdays start on Thursday (1970-01-01).
|
||||
struct DateNames {
|
||||
/// Full month names (January through December).
|
||||
months: [&'static str; 12],
|
||||
/// Abbreviated month names for `MMM` (January through December).
|
||||
months_short: [&'static str; 12],
|
||||
/// Weekday names starting on Thursday (1970-01-01).
|
||||
days: [&'static str; 7],
|
||||
/// Abbreviated weekday names for `ddd`, starting on Thursday (1970-01-01).
|
||||
days_short: [&'static str; 7],
|
||||
/// The picture of a `DATE` field without `\@`.
|
||||
default: &'static str,
|
||||
}
|
||||
|
||||
const ENGLISH: DateNames = DateNames {
|
||||
months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
|
||||
months_short: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
|
||||
days: ["Thursday", "Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday"],
|
||||
days_short: ["Thu", "Fri", "Sat", "Sun", "Mon", "Tue", "Wed"],
|
||||
default: "M/d/yyyy",
|
||||
};
|
||||
|
||||
@@ -227,14 +232,46 @@ const ENGLISH: DateNames = DateNames {
|
||||
/// `ddd` = `qui`, and `dd/MM/yyyy` for a field without a picture.
|
||||
const PORTUGUESE: DateNames = DateNames {
|
||||
months: ["janeiro", "fevereiro", "março", "abril", "maio", "junho", "julho", "agosto", "setembro", "outubro", "novembro", "dezembro"],
|
||||
months_short: ["jan", "fev", "mar", "abr", "mai", "jun", "jul", "ago", "set", "out", "nov", "dez"],
|
||||
days: ["quinta-feira", "sexta-feira", "sábado", "domingo", "segunda-feira", "terça-feira", "quarta-feira"],
|
||||
days_short: ["qui", "sex", "sáb", "dom", "seg", "ter", "qua"],
|
||||
default: "dd/MM/yyyy",
|
||||
};
|
||||
|
||||
/// Choose month and weekday names according to the primary language subtag.
|
||||
/// German (Word's Windows NLS forms): `MMMM` = `März`, `MMM` = `Mrz`, `ddd` = `Fr` (two
|
||||
/// letters), and `dd.MM.yyyy` for a field without a picture. Covers de-DE, de-CH and bare `de`.
|
||||
const GERMAN: DateNames = DateNames {
|
||||
months: ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
|
||||
months_short: ["Jan", "Feb", "Mrz", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"],
|
||||
days: ["Donnerstag", "Freitag", "Samstag", "Sonntag", "Montag", "Dienstag", "Mittwoch"],
|
||||
days_short: ["Do", "Fr", "Sa", "So", "Mo", "Di", "Mi"],
|
||||
default: "dd.MM.yyyy",
|
||||
};
|
||||
|
||||
/// Austrian Standard German: January is `Jänner`, abbreviated `Jän` (Österreichisches
|
||||
/// Wörterbuch; Windows NLS `de-AT`). Every other month and weekday matches [`GERMAN`].
|
||||
const GERMAN_AUSTRIA: DateNames = DateNames {
|
||||
months: ["Jänner", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
|
||||
months_short: ["Jän", "Feb", "Mrz", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"],
|
||||
days: ["Donnerstag", "Freitag", "Samstag", "Sonntag", "Montag", "Dienstag", "Mittwoch"],
|
||||
days_short: ["Do", "Fr", "Sa", "So", "Mo", "Di", "Mi"],
|
||||
default: "dd.MM.yyyy",
|
||||
};
|
||||
|
||||
/// Choose month and weekday names from the language tag: the primary subtag picks the language,
|
||||
/// and a region subtag refines it (`de-AT` writes `Jänner`). Tags compare case-insensitively, as
|
||||
/// `w:lang` values do.
|
||||
fn date_names(lang: Option<&str>) -> &'static DateNames {
|
||||
let primary = lang.and_then(|l| l.trim().split(['-', '_']).next()).unwrap_or("");
|
||||
if primary.eq_ignore_ascii_case("pt") { &PORTUGUESE } else { &ENGLISH }
|
||||
let mut subtags = lang.unwrap_or("").trim().split(['-', '_']);
|
||||
let primary = subtags.next().unwrap_or("");
|
||||
if primary.eq_ignore_ascii_case("pt") {
|
||||
&PORTUGUESE
|
||||
} else if primary.eq_ignore_ascii_case("de") {
|
||||
// Austria keeps `Jänner` / `Jän`; Germany and Switzerland keep `Januar` / `Jan`.
|
||||
if subtags.any(|region| region.eq_ignore_ascii_case("AT")) { &GERMAN_AUSTRIA } else { &GERMAN }
|
||||
} else {
|
||||
&ENGLISH
|
||||
}
|
||||
}
|
||||
|
||||
/// The picture Word gives a `DATE` field that has no `\@` switch, in the field's language.
|
||||
@@ -252,9 +289,12 @@ pub fn format_date_parts(fmt: &str, y: i64, m: usize, d: u32, hms: (u32, u32, u3
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn format_date_parts_in(fmt: &str, lang: Option<&str>, y: i64, m: usize, d: u32, (hh, mm, ss): (u32, u32, u32), days_since: i64) -> String {
|
||||
let names = date_names(lang);
|
||||
let month = names.months.get(m.saturating_sub(1)).copied().unwrap_or(names.months[0]);
|
||||
let day = names.days.get(days_since.rem_euclid(7) as usize).copied().unwrap_or(names.days[0]);
|
||||
let three = |s: &str| -> String { s.chars().take(3).collect() };
|
||||
let mi = m.saturating_sub(1);
|
||||
let di = days_since.rem_euclid(7) as usize;
|
||||
let month = names.months.get(mi).copied().unwrap_or(names.months[0]);
|
||||
let month_short = names.months_short.get(mi).copied().unwrap_or(names.months_short[0]);
|
||||
let day = names.days.get(di).copied().unwrap_or(names.days[0]);
|
||||
let day_short = names.days_short.get(di).copied().unwrap_or(names.days_short[0]);
|
||||
let mut out = String::new();
|
||||
let chars: Vec<char> = fmt.chars().collect();
|
||||
let mut i = 0;
|
||||
@@ -296,11 +336,11 @@ pub fn format_date_parts_in(fmt: &str, lang: Option<&str>, y: i64, m: usize, d:
|
||||
('y' | 'Y', 4..) => out.push_str(&format!("{y:04}")),
|
||||
('y' | 'Y', _) => out.push_str(&format!("{:02}", y % 100)),
|
||||
('M', 4..) => out.push_str(month),
|
||||
('M', 3) => out.push_str(&three(month)),
|
||||
('M', 3) => out.push_str(month_short),
|
||||
('M', 2) => out.push_str(&format!("{m:02}")),
|
||||
('M', 1) => out.push_str(&m.to_string()),
|
||||
('d' | 'D', 4..) => out.push_str(day),
|
||||
('d' | 'D', 3) => out.push_str(&three(day)),
|
||||
('d' | 'D', 3) => out.push_str(day_short),
|
||||
('d' | 'D', 2) => out.push_str(&format!("{d:02}")),
|
||||
('d' | 'D', 1) => out.push_str(&d.to_string()),
|
||||
('H', 2..) => out.push_str(&format!("{hh:02}")),
|
||||
@@ -574,6 +614,43 @@ mod date_time_locale_tests {
|
||||
assert_eq!(format("MMMM", 20), "outubro");
|
||||
}
|
||||
|
||||
/// German month and weekday names, and the default picture, are chosen by the language tag
|
||||
/// (de-DE, de-AT, de-CH), as in Word (#7146).
|
||||
#[test]
|
||||
fn german_date_names_render_for_de() {
|
||||
assert_eq!(format_date_parts_in("dddd, d. MMMM yyyy", Some("de-DE"), 2026, 11, 21, (12, 0, 0), 2), "Samstag, 21. November 2026");
|
||||
assert_eq!(default_date_picture(Some("de-CH")), "dd.MM.yyyy");
|
||||
}
|
||||
|
||||
/// Windows NLS short forms: two-letter weekdays (`Mo`, `Di`…) and `Mrz` for March, with no
|
||||
/// trailing full stop (#7146).
|
||||
#[test]
|
||||
fn german_short_names_match_windows_nls() {
|
||||
let format = |pic| format_date_parts_in(pic, Some("de-DE"), 2026, 3, 15, (12, 0, 0), 3);
|
||||
assert_eq!(format("ddd, d. MMM yyyy"), "So, 15. Mrz 2026");
|
||||
assert_eq!(format("dddd"), "Sonntag");
|
||||
assert_eq!(format("MMM"), "Mrz");
|
||||
}
|
||||
|
||||
/// Austrian Standard German writes January as `Jänner` (`Jän`), while Germany, Switzerland
|
||||
/// and bare `de` keep `Januar` (`Jan`); every other name is shared (#7146).
|
||||
#[test]
|
||||
fn austrian_german_january_is_jaenner() {
|
||||
let january = |lang, pic| format_date_parts_in(pic, Some(lang), 2026, 1, 15, (12, 0, 0), 0);
|
||||
assert_eq!(january("de-AT", "MMMM"), "Jänner");
|
||||
assert_eq!(january("de-AT", "MMM"), "Jän");
|
||||
assert_eq!(january("de_at", "MMMM"), "Jänner", "region subtags compare case-insensitively");
|
||||
for lang in ["de-DE", "de-CH", "de"] {
|
||||
assert_eq!(january(lang, "MMMM"), "Januar", "{lang}");
|
||||
assert_eq!(january(lang, "MMM"), "Jan", "{lang}");
|
||||
}
|
||||
// Only January differs: February and March read the same in Austria and Germany.
|
||||
for month in [2, 3] {
|
||||
let names = |lang| format_date_parts_in("MMMM MMM", Some(lang), 2026, month, 1, (12, 0, 0), 0);
|
||||
assert_eq!(names("de-AT"), names("de-DE"));
|
||||
}
|
||||
}
|
||||
|
||||
/// A pt-BR dynamic field keeps its result after DOCX round-trip and refresh.
|
||||
#[test]
|
||||
fn pt_br_date_time_dialog_inserts_dynamic_field() {
|
||||
|
||||
@@ -84,25 +84,45 @@ pub(super) fn link(s: &mut Session, v: &Value) -> CmdResult {
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
/// The `text` to retype a selection with before linking it: only when it differs from the selected
|
||||
/// text and both fit in one line of one paragraph without pictures or fields, outside any field's
|
||||
/// result. Otherwise (as Word shows `<<Selection in Document>>`) the selection keeps its text.
|
||||
fn retyped_text(s: &Session, v: &Value) -> Option<String> {
|
||||
/// What can't stand in one line of text: breaks, and pictures or fields.
|
||||
const NOT_ONE_LINE: [char; 7] = {
|
||||
use wordcraft_doc::para::{COLUMN_BREAK, LINE_BREAK, OBJ, PAGE_BREAK};
|
||||
/// What can't stand in one line of text: breaks, and pictures or fields.
|
||||
const NOT_ONE_LINE: [char; 7] = [LINE_BREAK, '\r', '\u{2029}', '\u{b}', PAGE_BREAK, COLUMN_BREAK, OBJ];
|
||||
let text = p::str(v, "text").filter(|t| !t.is_empty() && t.len() <= 4096)?;
|
||||
if text.contains(NOT_ONE_LINE) {
|
||||
[LINE_BREAK, '\r', '\u{2029}', '\u{b}', PAGE_BREAK, COLUMN_BREAK, OBJ]
|
||||
};
|
||||
|
||||
/// The raw text of the selection when it is one run of one paragraph without breaks, pictures or fields.
|
||||
fn one_line_selection(s: &Session) -> Option<&str> {
|
||||
// A column (block) selection has both ends in one paragraph but holds a piece of each line it
|
||||
// covers: it isn't one line of text (#8581).
|
||||
if s.column_segments().is_some_and(|segs| !segs.is_empty()) {
|
||||
return None;
|
||||
}
|
||||
let (a, b) = s.sel.ordered();
|
||||
if a.story != b.story || a.path != b.path {
|
||||
return None;
|
||||
}
|
||||
let shown = s.doc.para(a.story, &a.path)?.text.get(a.off..b.off)?;
|
||||
if shown.contains(NOT_ONE_LINE) || shown == text {
|
||||
s.doc.para(a.story, &a.path)?.text.get(a.off..b.off).filter(|t| !t.contains(NOT_ONE_LINE))
|
||||
}
|
||||
|
||||
/// Whether the selection is plain text in one line of one paragraph: otherwise (as Word shows
|
||||
/// `<<Selection in Document>>`) Text to display can't show it and linking keeps its content (#8286).
|
||||
pub fn selection_is_one_line(s: &Session) -> bool {
|
||||
one_line_selection(s).is_some()
|
||||
}
|
||||
|
||||
/// The `text` to retype a selection with before linking it: only when it differs from the selected
|
||||
/// text and both fit in one line of one paragraph without pictures or fields, outside any field's
|
||||
/// result. Otherwise (as Word shows `<<Selection in Document>>`) the selection keeps its text.
|
||||
fn retyped_text(s: &Session, v: &Value) -> Option<String> {
|
||||
let text = p::str(v, "text").filter(|t| !t.is_empty() && t.len() <= 4096)?;
|
||||
if text.contains(NOT_ONE_LINE) {
|
||||
return None;
|
||||
}
|
||||
let shown = one_line_selection(s)?;
|
||||
if shown == text {
|
||||
return None;
|
||||
}
|
||||
let (a, b) = s.sel.ordered();
|
||||
// A selection in a field's result (between its markers, which it doesn't hold) is retyped by
|
||||
// the next update of the field, not here.
|
||||
if s.doc.field_ranges(a.story).iter().any(|r| r.start < b && a <= r.end) {
|
||||
|
||||
@@ -373,21 +373,22 @@ pub fn merge_formatting(s: &Session, frag: &mut Fragment) {
|
||||
p.props = para.clone();
|
||||
for run in &mut p.runs {
|
||||
let src = std::mem::replace(&mut run.props, base.clone());
|
||||
// Emphasis in either script is kept for both, as the Bold and Italic buttons set
|
||||
// it: text pasted into a run marked `w:cs` (Thai from a WPS or Word file) is drawn
|
||||
// with the complex-script bold and italic.
|
||||
if src.bold == Some(true) || src.bold_cs == Some(true) {
|
||||
let e = emphasis_of(s, &src);
|
||||
// Emphasis the source shows in either script is kept for both, as the Bold and
|
||||
// Italic buttons set it: text pasted into a run marked `w:cs` (Thai from a WPS or
|
||||
// Word file) is drawn with the complex-script bold and italic.
|
||||
if shown(e.bold, e.bold_cs, &e) {
|
||||
run.props.bold = Some(true);
|
||||
run.props.bold_cs = Some(true);
|
||||
}
|
||||
if src.italic == Some(true) || src.italic_cs == Some(true) {
|
||||
if shown(e.italic, e.italic_cs, &e) {
|
||||
run.props.italic = Some(true);
|
||||
run.props.italic_cs = Some(true);
|
||||
}
|
||||
if src.underline.is_some_and(|u| u != wordcraft_doc::props::Underline::None) {
|
||||
run.props.underline = src.underline;
|
||||
if e.underline.is_some_and(|u| u != wordcraft_doc::props::Underline::None) {
|
||||
run.props.underline = e.underline;
|
||||
}
|
||||
if src.strike == Some(true) {
|
||||
if e.strike == Some(true) {
|
||||
run.props.strike = Some(true);
|
||||
}
|
||||
run.props.link = src.link;
|
||||
@@ -400,6 +401,34 @@ pub fn merge_formatting(s: &Session, frag: &mut Fragment) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The formatting a pasted run's emphasis is judged by: its own, over its character style
|
||||
/// chain's. Word keeps the bold, italic, underline and strikethrough a character style gives the
|
||||
/// source, as direct formatting, but not a paragraph style's (measured in Word for Windows), so
|
||||
/// the paragraph style isn't consulted.
|
||||
fn emphasis_of(s: &Session, src: &wordcraft_doc::CharProps) -> wordcraft_doc::CharProps {
|
||||
use wordcraft_doc::styles::StyleKind;
|
||||
let mut e = wordcraft_doc::CharProps::default();
|
||||
if let Some(id) = src.style.as_deref() {
|
||||
for st in s.doc.styles.chain(id) {
|
||||
if st.kind == StyleKind::Character || st.kind == StyleKind::Paragraph {
|
||||
e.overlay(&st.chr);
|
||||
}
|
||||
}
|
||||
}
|
||||
e.overlay(&wordcraft_doc::CharProps { style: None, ..src.clone() });
|
||||
e
|
||||
}
|
||||
|
||||
/// Whether a run with these Latin and complex-script values of a toggle (bold or italic) shows
|
||||
/// it anywhere, as the resolved formatting draws it: a run marked `w:cs` or `w:rtl` draws all
|
||||
/// its text with the complex-script value, which borrows the Latin one unless the run is marked
|
||||
/// `w:cs`; other runs draw their Latin text with the Latin value.
|
||||
fn shown(latin: Option<bool>, complex: Option<bool>, run: &wordcraft_doc::CharProps) -> bool {
|
||||
let complex_shown = complex.or(latin.filter(|_| run.cs != Some(true))) == Some(true);
|
||||
let all_complex = run.cs == Some(true) || run.rtl == Some(true);
|
||||
complex_shown || (!all_complex && latin == Some(true))
|
||||
}
|
||||
|
||||
/// Paste `frag` at the selection. A copied table pasted with the caret in a table cell goes the way
|
||||
/// Word's Paste does it (rows inserted or cells overwritten, #6739; see [`super::paste_cells`]);
|
||||
/// anything else is [`insert_as_is`].
|
||||
|
||||
@@ -422,7 +422,19 @@ pub fn update_fields_in(s: &mut Session, all: bool) -> Result<(), CmdError> {
|
||||
"DATE" | "TIME" | "CREATEDATE" | "SAVEDATE" | "PRINTDATE" => {
|
||||
let lang = field_lang(&s.doc, p, k);
|
||||
let pic = date_picture(instr).unwrap_or_else(|| default_picture(&name, lang.as_deref()));
|
||||
updates.push((k, text_result(instr, crate::cmd::insert::format_date_in(&pic, lang.as_deref()))));
|
||||
let created = s.doc.core.created.trim();
|
||||
// CREATEDATE shows when the document was created (ECMA-376 §17.16.5.11). A new
|
||||
// document, never saved, has no creation date yet and saving stamps now. A
|
||||
// file opened without one, or with one that can't be read, keeps the result
|
||||
// it has.
|
||||
let text = if name != "CREATEDATE" || (created.is_empty() && s.path.is_none()) {
|
||||
crate::cmd::insert::format_date_in(&pic, lang.as_deref())
|
||||
} else if let Some((unix, offset)) = created_at(created) {
|
||||
crate::cmd::insert::format_date_at_in(&pic, lang.as_deref(), unix, offset)
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
updates.push((k, text_result(instr, text)));
|
||||
}
|
||||
"REF" | "PAGEREF" => {
|
||||
let f = FieldCode::parse(instr);
|
||||
@@ -572,6 +584,24 @@ fn field_lang(doc: &wordcraft_doc::Document, p: &wordcraft_doc::Paragraph, k: us
|
||||
doc.styles.resolve_char(p.props.style.as_deref(), p.props_of_char(off)).lang
|
||||
}
|
||||
|
||||
/// A core-properties creation date as seconds since the epoch and the UTC offset to show it at:
|
||||
/// an instant (`2019-05-05T12:00:00Z`, any offset or fraction, or without the seconds,
|
||||
/// `2019-05-05T12:00Z`, as W3CDTF allows) at the local offset, or a calendar date (`2019-05-05`)
|
||||
/// at its own midnight, whatever the time zone. `None` for another form or a date before 1970.
|
||||
fn created_at(stamp: &str) -> Option<(u64, i64)> {
|
||||
let instant = chrono::DateTime::parse_from_rfc3339(stamp).ok().or_else(|| {
|
||||
// `%:z` takes `+01:00` but not `Z`.
|
||||
let utc = stamp.strip_suffix(['Z', 'z']).map(|t| format!("{t}+00:00"));
|
||||
chrono::DateTime::parse_from_str(utc.as_deref().unwrap_or(stamp), "%Y-%m-%dT%H:%M%:z").ok()
|
||||
});
|
||||
if let Some(t) = instant {
|
||||
let unix = u64::try_from(t.timestamp()).ok()?;
|
||||
return Some((unix, crate::cmd::local_offset_secs(unix)));
|
||||
}
|
||||
let day = chrono::NaiveDate::parse_from_str(stamp, "%Y-%m-%d").ok()?;
|
||||
Some((u64::try_from(day.and_hms_opt(0, 0, 0)?.and_utc().timestamp()).ok()?, 0))
|
||||
}
|
||||
|
||||
/// Word's default date or time picture when a field instruction carries no `\@` picture switch.
|
||||
fn default_picture(name: &str, lang: Option<&str>) -> String {
|
||||
if name == "TIME" { "h:mm am/pm".into() } else { crate::cmd::insert::default_date_picture(lang).into() }
|
||||
|
||||
@@ -506,6 +506,56 @@ fn update_fields_all_covers_every_story() {
|
||||
s.run("references.updateFields", &json!({"all": "yes"})).unwrap();
|
||||
}
|
||||
|
||||
/// CREATEDATE shows when the document was created (ECMA-376 §17.16.5.11), not today's date.
|
||||
#[test]
|
||||
fn createdate_keeps_the_creation_date_on_update() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.doc.core.created = "2019-05-05T12:00:00Z".into();
|
||||
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#, "result": "2019-05"})).unwrap();
|
||||
s.run("insert.field", &json!({"instr": "CREATEDATE"})).unwrap();
|
||||
s.run("references.updateFields", &json!({})).unwrap();
|
||||
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
|
||||
// 12:00 UTC is 5 May from UTC-12 to UTC+11:59, the next day east of that.
|
||||
let unix = 1_557_057_600;
|
||||
let (_, _, day, _, _) = crate::cmd::local_civil(unix, crate::cmd::local_offset_secs(unix));
|
||||
assert_eq!(results, ["2019-05".to_string(), format!("5/{day}/2019")]);
|
||||
assert!(day == 5 || day == 6, "{day}");
|
||||
// W3CDTF may leave out the seconds; that is the same instant.
|
||||
for minutes in ["2019-05-05T12:00Z", "2019-05-05T14:00+02:00", "2019-05-05T07:00-05:00"] {
|
||||
// From another date first, so an unread stamp, which keeps the result, shows.
|
||||
s.doc.core.created = "2001-02-03".into();
|
||||
s.run("references.updateFields", &json!({})).unwrap();
|
||||
assert_eq!(fields(&s)[1].1, "2/3/2001");
|
||||
s.doc.core.created = minutes.into();
|
||||
s.run("references.updateFields", &json!({})).unwrap();
|
||||
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
|
||||
assert_eq!(results, ["2019-05".to_string(), format!("5/{day}/2019")], "{minutes}");
|
||||
}
|
||||
// A date without a time is that calendar day in every time zone.
|
||||
s.doc.core.created = "2019-06-07".into();
|
||||
s.run("references.updateFields", &json!({})).unwrap();
|
||||
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
|
||||
assert_eq!(results, ["2019-06", "6/7/2019"]);
|
||||
}
|
||||
|
||||
/// A creation date that can't be read leaves the field's result as it was; a document that has
|
||||
/// never been saved is created now (saving stamps that time as its creation date).
|
||||
#[test]
|
||||
fn createdate_without_a_readable_creation_date() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.doc.core.created = "sometime in May".into();
|
||||
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#, "result": "2019-05"})).unwrap();
|
||||
assert_eq!(fields(&s)[0].1, "2019-05");
|
||||
// A file opened without a creation date keeps the result too.
|
||||
s.doc.core.created.clear();
|
||||
s.path = Some(std::env::temp_dir().join("opened.docx"));
|
||||
s.run("references.updateFields", &json!({})).unwrap();
|
||||
assert_eq!(fields(&s)[0].1, "2019-05");
|
||||
s.path = None;
|
||||
s.run("references.updateFields", &json!({})).unwrap();
|
||||
assert_eq!(fields(&s)[0].1, crate::cmd::insert::format_date("yyyy-MM"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toc_tabs_ignore_nonentries() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Before\nContents\nOld\t9\nAfter"));
|
||||
|
||||
@@ -12,6 +12,7 @@ use crate::{CmdError, CmdResult, CommandSpec, Selection, Session, p};
|
||||
mod changes;
|
||||
mod comments;
|
||||
mod proofing;
|
||||
pub use proofing::thesaurus_word;
|
||||
|
||||
pub(crate) use changes::StyleTarget;
|
||||
pub use changes::{
|
||||
|
||||
@@ -53,10 +53,11 @@ fn resolve_para(
|
||||
}
|
||||
// An inserted paragraph mark that is rejected, or a deleted one that is accepted, goes away:
|
||||
// the next paragraph joins this one (the split is undone). A paragraph left empty goes away
|
||||
// whole, so the next one keeps its own style and numbering, as in Word. The mark at the end
|
||||
// of a story or cell can't go, so it just stops being a revision. An empty paragraph whose
|
||||
// mark carries a section break goes whole too: its section joins the following one, as when
|
||||
// the break is deleted (#5667). Joining instead gave the next paragraph its properties.
|
||||
// whole, so the next one keeps its own style and numbering, as in Word. The end mark of a
|
||||
// story or cell has no follower to join here; `resolve_all` removes the whole paragraph
|
||||
// instead when one is left over (see `remove_trailing_para`). An empty paragraph whose mark
|
||||
// carries a section break goes whole too: its section joins the following one, as when the
|
||||
// break is deleted (#5667). Joining instead gave the next paragraph its properties.
|
||||
if (del.is_some() && accept) || (ins.is_some() && !accept) {
|
||||
let sectioned = story == StoryRef::Body
|
||||
&& path.0.len() == 1
|
||||
@@ -76,6 +77,23 @@ fn resolve_para(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Remove the whole paragraph at `path` when a whole-paragraph revision on its mark resolved to
|
||||
/// removal and it is the last paragraph in its container and carries no section break: it goes
|
||||
/// away, as long as the container keeps another paragraph (a story or cell must never end up
|
||||
/// with none). `false`, changing nothing, otherwise.
|
||||
fn remove_trailing_para(s: &mut Session, story: StoryRef, path: &wordcraft_doc::Path) -> Result<bool, CmdError> {
|
||||
let Some(p) = s.doc.para(story, path) else { return Ok(false) };
|
||||
if !p.is_empty() || p.section.is_some() {
|
||||
return Ok(false);
|
||||
}
|
||||
let Some(container) = s.doc.container(story, path) else { return Ok(false) };
|
||||
if container.iter().filter(|b| b.as_para().is_some()).count() <= 1 {
|
||||
return Ok(false);
|
||||
}
|
||||
s.doc.remove_block(story, path)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Accept or reject the changes of the table cell `path` is in: the table's, its row's and the
|
||||
/// cell's own. Returns whether there were any.
|
||||
fn resolve_cell(s: &mut Session, story: StoryRef, path: &wordcraft_doc::Path, accept: bool) -> Result<bool, CmdError> {
|
||||
@@ -245,8 +263,16 @@ fn resolve_all(s: &mut Session, accept: bool) -> CmdResult {
|
||||
let stories: Vec<StoryRef> = std::iter::once(StoryRef::Body).chain(s.doc.parts.keys().map(|k| StoryRef::Part(*k))).collect();
|
||||
for st in stories {
|
||||
for path in s.doc.para_paths(st).into_iter().rev() {
|
||||
// A whole-paragraph mark that resolves to removal at the end of its container takes
|
||||
// the paragraph with it (there is no follower for `resolve_para` to join). A paragraph
|
||||
// followed by a table is not the end: removing it could make two tables adjacent.
|
||||
let is_last = s.doc.block(st, &path.with_last(path.last().saturating_add(1))).is_none();
|
||||
let trailing = is_last && s.doc.para(st, &path).is_some_and(|p| (p.mark.del.is_some() && accept) || (p.mark.ins.is_some() && !accept));
|
||||
let len = s.doc.para(st, &path).map(|p| p.len()).unwrap_or(0);
|
||||
resolve_para(s, st, &path, (0, len), (true, true), accept)?;
|
||||
if trailing {
|
||||
remove_trailing_para(s, st, &path)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Tables, rows, cells, sections and style definitions.
|
||||
|
||||
@@ -128,6 +128,20 @@ pub(super) fn suggestions(s: &mut Session, v: &Value) -> CmdResult {
|
||||
}
|
||||
}
|
||||
|
||||
/// The word at the caret that the thesaurus looks up and a chosen synonym replaces: the word unit
|
||||
/// without the spaces after it or the quotes around it, so `‘good’` is `good` and its quotes stay
|
||||
/// when it is replaced; an apostrophe inside a word (`don’t`) is kept (#6517).
|
||||
pub fn thesaurus_word(s: &Session) -> Option<(Pos, Pos)> {
|
||||
let f = &s.sel.focus;
|
||||
let p = s.doc.para_at(f)?;
|
||||
let (a, b) = p.word_at(f.off);
|
||||
let w = p.text.get(a..b)?;
|
||||
let edge = |c: char| c.is_whitespace() || matches!(c, '’' | '‘' | '\'');
|
||||
let start = a + (w.len() - w.trim_start_matches(edge).len());
|
||||
let end = (a + w.trim_end_matches(edge).len()).max(start);
|
||||
Some((Pos { off: start, ..f.clone() }, Pos { off: end, ..f.clone() }))
|
||||
}
|
||||
|
||||
/// A tiny built-in thesaurus of common words (our own list).
|
||||
pub(super) fn thesaurus(s: &mut Session, v: &Value) -> CmdResult {
|
||||
const T: &[(&str, &[&str])] = &[
|
||||
@@ -164,10 +178,8 @@ pub(super) fn thesaurus(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let word = match p::str(v, "word") {
|
||||
Some(w) => w.to_lowercase(),
|
||||
None => {
|
||||
let f = s.sel.focus.clone();
|
||||
let p = s.doc.para_at(&f).ok_or_else(|| CmdError::Failed("no word".into()))?;
|
||||
let (a, b) = p.word_at(f.off);
|
||||
p.text.get(a..b).unwrap_or("").trim().to_lowercase()
|
||||
let (a, b) = thesaurus_word(s).ok_or_else(|| CmdError::Failed("no word".into()))?;
|
||||
s.doc.para_at(&a).and_then(|p| p.text.get(a.off..b.off)).unwrap_or("").to_lowercase()
|
||||
}
|
||||
};
|
||||
let syn = T.iter().find(|(w, _)| *w == word).map(|(_, l)| l.to_vec()).unwrap_or_default();
|
||||
|
||||
@@ -136,6 +136,30 @@ fn a_selected_column_is_edited_cell_by_cell() {
|
||||
assert_eq!(s.cell_range().map(|r| r.cols), Some((1, 1)), "undo brings the column selection back");
|
||||
}
|
||||
|
||||
/// Toggling a format on a selected table column follows the first character in document order (#8589).
|
||||
#[test]
|
||||
fn toggle_on_a_selected_table_column_follows_first_character() {
|
||||
let toggled = |bold_row: usize| -> Vec<bool> {
|
||||
let mut s = table_session(3, 3);
|
||||
fill(&mut s);
|
||||
let p = cell_pos(&s, bold_row, 1);
|
||||
s.sel = Selection { anchor: p.clone(), focus: Pos { off: 4, ..p } };
|
||||
s.run("format.bold", &json!({"value": true})).unwrap();
|
||||
// Start from the bottom row so the caret is not on row 0.
|
||||
s.sel = Selection::caret(cell_pos(&s, 2, 1));
|
||||
s.run("table.selectColumn", &json!({})).unwrap();
|
||||
s.run("format.bold", &json!({})).unwrap();
|
||||
for r in 0..3 {
|
||||
assert!(!bold(&s, r, 0) && !bold(&s, r, 2), "row {r}'s other cells stay plain");
|
||||
}
|
||||
(0..3).map(|r| bold(&s, r, 1)).collect()
|
||||
};
|
||||
// First row bold, later rows plain: Bold turns off across the column.
|
||||
assert_eq!(toggled(0), vec![false, false, false]);
|
||||
// First row plain, middle row bold: Bold turns on across the column.
|
||||
assert_eq!(toggled(1), vec![true, true, true]);
|
||||
}
|
||||
|
||||
/// Numbering a column numbers its cells as one list, like Word.
|
||||
#[test]
|
||||
fn numbering_a_column_makes_one_list() {
|
||||
|
||||
@@ -1622,12 +1622,11 @@ fn block_text(b: &Block, depth: usize) -> String {
|
||||
/// the paragraph is empty (`format` returns early for a length-0 range). Walks nested tables
|
||||
/// iteratively, without recursion or depth truncation.
|
||||
///
|
||||
/// Known limitation: resolving a revision needs a following paragraph, so a paragraph inserted at
|
||||
/// the very end (rejected) or deleted from the very end (accepted) still leaves one empty
|
||||
/// paragraph. That is a separate follow-up, not handled here. A section-carrying inserted
|
||||
/// paragraph is not such a case: `resolve_para` removes the section break first (#5734, issue
|
||||
/// #5667), so rejecting it takes the paragraph out whole and the following paragraph keeps its
|
||||
/// own properties.
|
||||
/// A whole-paragraph revision on the last paragraph of a story or cell is removed together with
|
||||
/// the paragraph on Accept/Reject All (see `remove_trailing_para` in `review::changes`), except
|
||||
/// where the paragraph carries a section break or is the container's only paragraph. A
|
||||
/// non-terminal section-carrying paragraph is removed whole too: `resolve_para` removes the
|
||||
/// section break first (#5734, issue #5667), so the following paragraph keeps its own properties.
|
||||
fn mark_block(b: &Block, f: &dyn Fn(&mut CharProps)) -> Block {
|
||||
let mut out = b.clone();
|
||||
let mut todo = vec![&mut out];
|
||||
|
||||
@@ -105,31 +105,49 @@ fn compare_keeps_another_authors_deletion_stamp() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_pins_the_terminal_inserted_paragraph_limitation() {
|
||||
// Characterizes the limitation documented on `mark_block` (compare.rs): resolving a revision
|
||||
// needs a following paragraph, so a paragraph inserted at the very end is rejected but leaves
|
||||
// one empty paragraph behind. Flip this test when the follow-up fix lands.
|
||||
fn compare_terminal_inserted_paragraph_resolves_fully() {
|
||||
// A paragraph inserted at the very end is removed whole when rejected, leaving no empty
|
||||
// paragraph behind.
|
||||
let mut s = Session::new(Document::from_text("A\nB"));
|
||||
s.run("review.compare", &json!({"text": "A\nB\nC"})).unwrap();
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
s.run("review.rejectAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB\n", "the rejected terminal paragraph still leaves a line");
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
assert_eq!(empty_paras(&s), 1, "the rejected terminal paragraph is left as one empty paragraph");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
|
||||
assert_eq!(s.doc.body.len(), 2);
|
||||
assert_eq!(empty_paras(&s), 0, "rejecting a terminal inserted paragraph left an empty paragraph behind");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_pins_the_terminal_deleted_paragraph_limitation() {
|
||||
// The mirror of `compare_pins_the_terminal_inserted_paragraph_limitation`: a paragraph deleted
|
||||
// from the very end is accepted but still leaves one empty paragraph. Characterizes the
|
||||
// limitation documented on `mark_block` (compare.rs); flip when the follow-up fix lands.
|
||||
fn compare_terminal_deleted_paragraph_resolves_fully() {
|
||||
// The mirror of `compare_terminal_inserted_paragraph_resolves_fully`: a paragraph deleted
|
||||
// from the very end is removed whole when accepted, leaving no empty paragraph behind.
|
||||
let mut s = Session::new(Document::from_text("A\nB\nC"));
|
||||
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
s.run("review.acceptAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB\n", "the accepted terminal deletion still leaves a line");
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
assert_eq!(empty_paras(&s), 1, "the accepted terminal deletion is left as one empty paragraph");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
|
||||
assert_eq!(s.doc.body.len(), 2);
|
||||
assert_eq!(empty_paras(&s), 0, "accepting a terminal deleted paragraph left an empty paragraph behind");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reject_all_keeps_an_empty_inserted_paragraph_between_tables() {
|
||||
// An empty paragraph between two tables is not the container's last block: removing it
|
||||
// would make the tables adjacent, and they would join into one on reopen. Reject All only
|
||||
// clears its mark.
|
||||
use wordcraft_doc::{Block, Paragraph, para_block};
|
||||
let mut doc = Document::from_text("");
|
||||
doc.revisions.push(wordcraft_doc::Revision::new(RevisionKind::Insert, "Alice", ""));
|
||||
let table = || std::sync::Arc::new(Block::Table(wordcraft_doc::table::Table::new(1, 1, 100.0)));
|
||||
let mut between = Paragraph::default();
|
||||
between.mark.ins = Some(0);
|
||||
doc.body = vec![table(), para_block(between), table(), para_block(Paragraph::with_text("end", Default::default()))];
|
||||
let mut s = Session::new(doc);
|
||||
s.run("review.rejectAll", &json!({})).unwrap();
|
||||
let kinds: Vec<bool> = s.doc.body.iter().map(|b| matches!(**b, Block::Table(_))).collect();
|
||||
assert_eq!(kinds, [true, false, true, false]);
|
||||
let kept = s.doc.para(StoryRef::Body, &wordcraft_doc::Path::top(1)).unwrap();
|
||||
assert!(kept.is_empty() && kept.mark.ins.is_none(), "{kept:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -201,6 +219,51 @@ fn compare_pins_accepting_a_deleted_section_keeps_the_next_paragraphs_style() {
|
||||
assert_eq!(body.props.style.as_deref(), Some("Heading1"), "the following paragraph keeps its own properties (fixed on main by #5734)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_marks_the_last_paragraphs_mark() {
|
||||
// Inserted last paragraph: rejecting removes it whole.
|
||||
let mut s = Session::new(Document::from_text("A\nB"));
|
||||
s.run("review.compare", &json!({"text": "A\nB\nNEW"})).unwrap();
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
assert!(s.doc.body[2].as_para().unwrap().mark.ins.is_some());
|
||||
s.run("review.rejectAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
|
||||
assert_eq!(s.doc.body.len(), 2);
|
||||
assert_eq!(empty_paras(&s), 0);
|
||||
let mut s = Session::new(Document::from_text("A\nB"));
|
||||
s.run("review.compare", &json!({"text": "A\nB\nNEW"})).unwrap();
|
||||
s.run("review.acceptAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB\nNEW");
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
assert_eq!(empty_paras(&s), 0);
|
||||
|
||||
// Deleted last paragraph: accepting removes it whole.
|
||||
let mut s = Session::new(Document::from_text("A\nB\nOLD"));
|
||||
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
assert!(s.doc.body[2].as_para().unwrap().mark.del.is_some());
|
||||
s.run("review.acceptAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
|
||||
assert_eq!(s.doc.body.len(), 2);
|
||||
assert_eq!(empty_paras(&s), 0);
|
||||
let mut s = Session::new(Document::from_text("A\nB\nOLD"));
|
||||
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
|
||||
s.run("review.rejectAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB\nOLD");
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
assert_eq!(empty_paras(&s), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_keeps_the_only_paragraphs_mark() {
|
||||
let mut s = Session::new(Document::from_text(""));
|
||||
s.doc.revisions.push(wordcraft_doc::Revision::new(RevisionKind::Insert, s.author.clone(), ""));
|
||||
s.doc.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap().mark.ins = Some(0);
|
||||
s.run("review.rejectAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.body.len(), 1);
|
||||
assert!(s.doc.body[0].as_para().unwrap().mark.ins.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_options_ignore_case_and_white_space() {
|
||||
let original = "The Cat sat.\nTwo spaces here.";
|
||||
|
||||
@@ -337,6 +337,29 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// A document made from a template is created now, not when the template was: it has no
|
||||
/// creation date until it is saved, so CREATEDATE in it shows today.
|
||||
#[test]
|
||||
fn new_from_template_has_no_creation_date_of_its_own_yet() {
|
||||
let d = scratch("created");
|
||||
let path = d.join("Dated.dotx");
|
||||
let mut t = Session::new(wordcraft_doc::Document::new());
|
||||
t.run("document.setText", &json!({"text": "Dated"})).unwrap();
|
||||
t.doc.core.created = "2019-05-05T12:00:00Z".into();
|
||||
crate::io::save_path(&path, &t.doc).unwrap();
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("file.newFromTemplate", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
assert_eq!(s.doc.core.created, "");
|
||||
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy""#, "result": "2019"})).unwrap();
|
||||
s.run("references.updateFields", &json!({})).unwrap();
|
||||
assert!(s.doc.plain_text(wordcraft_doc::StoryRef::Body).contains(&crate::cmd::insert::format_date("yyyy")));
|
||||
// The template itself keeps its date.
|
||||
let mut again = Session::new(wordcraft_doc::Document::new());
|
||||
again.run("file.open", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
assert_eq!(again.doc.core.created, "2019-05-05T12:00:00Z");
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// #3433: a template the platform hands the app takes an untouched blank document's place
|
||||
/// (`replaceBlank`), as a file `file.open` opens does; otherwise, and without the flag, the
|
||||
/// new document opens beside the others, as File › New's does. Either way the template on
|
||||
|
||||
@@ -35,7 +35,10 @@ impl Session {
|
||||
fn leave_math_for_command(&mut self, id: &str) {
|
||||
self.math_left = false;
|
||||
if self.math.is_some()
|
||||
&& (id.starts_with("text.") || id.starts_with("caret.") || id.starts_with("select.") || id.starts_with("edit.paste"))
|
||||
&& (id.starts_with("text.")
|
||||
|| id.starts_with("caret.")
|
||||
|| id.starts_with("select.")
|
||||
|| (id.starts_with("edit.paste") && id != "edit.pasteFormat"))
|
||||
&& let Some(m) = self.math.take()
|
||||
{
|
||||
let off = m.at.off + wordcraft_doc::para::OBJ.len_utf8();
|
||||
|
||||
@@ -293,6 +293,15 @@ fn custom_dictionary_words_persist_through_their_file() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn confined_sessions_test_is_native_only() {
|
||||
let source = include_str!("tests.rs");
|
||||
assert!(source.contains(
|
||||
"#[cfg(not(target_arch = \"wasm32\"))]\n#[test]\nfn confined_sessions_neither_save_the_dictionary_nor_choose_folders_outside_their_roots()"
|
||||
));
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn confined_sessions_neither_save_the_dictionary_nor_choose_folders_outside_their_roots() {
|
||||
let _guard = crate::custom_dict::DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
@@ -1043,6 +1052,180 @@ fn bold_toggles_selection_and_caret_word() {
|
||||
assert_eq!(p.props_of_char(9).italic, None);
|
||||
}
|
||||
|
||||
/// A partly formatted selection toggles by its first character, as Word does (#6516).
|
||||
#[test]
|
||||
fn toggles_on_mixed_selection_follow_first_character() {
|
||||
// `Abc abc` with `fmt` set by `cmd`, then `cmd` with `v` on the selection `from` → `to`.
|
||||
let toggled = |cmd: &str, fmt: (usize, usize), from: usize, to: usize, v: serde_json::Value| -> String {
|
||||
let mut s = s();
|
||||
run(&mut s, "text.insert", json!({"text": "Abc abc"}));
|
||||
let sel = |s: &mut Session, a: usize, b: usize| {
|
||||
run(s, "select.range", json!({"anchor": {"block": 0, "off": a}, "focus": {"block": 0, "off": b}}));
|
||||
};
|
||||
sel(&mut s, fmt.0, fmt.1);
|
||||
run(&mut s, cmd, json!({"value": true}));
|
||||
sel(&mut s, from, to);
|
||||
run(&mut s, cmd, v);
|
||||
let p = s.doc.para_at(&Pos::body(0, 0)).unwrap();
|
||||
(0..7)
|
||||
.map(|i| {
|
||||
let c = p.props_of_char(i);
|
||||
match cmd {
|
||||
"format.italic" => c.italic == Some(true),
|
||||
"format.underline" => c.underline.is_some_and(|u| u != wordcraft_doc::props::Underline::None),
|
||||
_ => c.bold == Some(true),
|
||||
}
|
||||
})
|
||||
.map(|on| if on { 'F' } else { '.' })
|
||||
.collect()
|
||||
};
|
||||
let t = || json!({});
|
||||
for cmd in ["format.bold", "format.italic", "format.underline"] {
|
||||
// `FFF....`: a selection starting on formatted text removes the format from all of it.
|
||||
assert_eq!(toggled(cmd, (0, 3), 2, 5, t()), "FF.....", "{cmd}");
|
||||
assert_eq!(toggled(cmd, (0, 3), 0, 7, t()), ".......", "{cmd}");
|
||||
assert_eq!(toggled(cmd, (0, 3), 1, 7, t()), "F......", "{cmd}");
|
||||
// Made right to left: still the first character in document order.
|
||||
assert_eq!(toggled(cmd, (0, 3), 5, 2, t()), "FF.....", "{cmd}");
|
||||
assert_eq!(toggled(cmd, (0, 3), 7, 0, t()), ".......", "{cmd}");
|
||||
// `....FFF`: a selection starting on plain text applies it to all of it.
|
||||
assert_eq!(toggled(cmd, (4, 7), 0, 7, t()), "FFFFFFF", "{cmd}");
|
||||
// An explicit value still sets.
|
||||
assert_eq!(toggled(cmd, (0, 3), 0, 7, json!({"value": true})), "FFFFFFF", "{cmd}");
|
||||
assert_eq!(toggled(cmd, (4, 7), 0, 7, json!({"value": false})), ".......", "{cmd}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A selection that starts in an empty paragraph: Word decides from the first text character, not
|
||||
/// from the empty paragraph's mark (observed in Word for Windows, #6516 review).
|
||||
#[test]
|
||||
fn toggle_on_a_selection_from_an_empty_paragraph_follows_the_first_text() {
|
||||
let toggled = |mark_bold: bool, text_bold: bool| -> Option<bool> {
|
||||
let mut s = s();
|
||||
run(&mut s, "text.newParagraph", json!({}));
|
||||
run(&mut s, "text.insert", json!({"text": "abc"}));
|
||||
let first = Pos::body(0, 0);
|
||||
s.doc.para_mut(first.story, &first.path).unwrap().mark.bold = Some(mark_bold);
|
||||
run(&mut s, "select.range", json!({"anchor": {"block": 1, "off": 0}, "focus": {"block": 1, "off": 3}}));
|
||||
run(&mut s, "format.bold", json!({"value": text_bold}));
|
||||
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 0}, "focus": {"block": 1, "off": 3}}));
|
||||
run(&mut s, "format.bold", json!({}));
|
||||
s.doc.para_at(&Pos::body(1, 0)).unwrap().props_of_char(0).bold
|
||||
};
|
||||
// A bold empty paragraph before plain text: Bold goes on.
|
||||
assert_eq!(toggled(true, false), Some(true));
|
||||
// A plain empty paragraph before bold text: Bold comes off.
|
||||
assert_eq!(toggled(false, true), Some(false));
|
||||
}
|
||||
|
||||
/// Toggling a format on a selected text box follows the first character of its text (#8589).
|
||||
#[test]
|
||||
fn toggle_on_a_selected_text_box_follows_first_character() {
|
||||
let toggled = |first_bold: bool, second_bold: bool, leading_empty_bold: Option<bool>| -> String {
|
||||
let mut s = s();
|
||||
let id = run(&mut s, "insert.textBox", json!({}))["story"].as_u64().unwrap() as u32;
|
||||
let boxed = StoryRef::Part(id);
|
||||
if let Some(mark_bold) = leading_empty_bold {
|
||||
s.doc.para_mut(boxed, &wordcraft_doc::Path::top(0)).unwrap().mark.bold = Some(mark_bold);
|
||||
run(&mut s, "text.newParagraph", json!({}));
|
||||
}
|
||||
let text_block = usize::from(leading_empty_bold.is_some());
|
||||
run(&mut s, "text.insert", json!({"text": "ab"}));
|
||||
let box_pos = |off| Pos { story: boxed, path: wordcraft_doc::Path::top(text_block), off };
|
||||
run(&mut s, "select.range", json!({"anchor": box_pos(0), "focus": box_pos(1)}));
|
||||
run(&mut s, "format.bold", json!({"value": first_bold}));
|
||||
run(&mut s, "select.range", json!({"anchor": box_pos(1), "focus": box_pos(2)}));
|
||||
run(&mut s, "format.bold", json!({"value": second_bold}));
|
||||
let anchor = s.doc.text_box_anchor(id).unwrap();
|
||||
run(&mut s, "select.range", json!({"anchor": Pos { off: anchor.off - "\u{FFFC}".len(), ..anchor.clone() }, "focus": anchor}));
|
||||
run(&mut s, "format.bold", json!({}));
|
||||
let p = s.doc.para(boxed, &wordcraft_doc::Path::top(text_block)).unwrap();
|
||||
(0..2).map(|i| if p.props_of_char(i).bold == Some(true) { 'B' } else { '.' }).collect()
|
||||
};
|
||||
// First character bold, second plain: Bold turns off across the box.
|
||||
assert_eq!(toggled(true, false, None), "..");
|
||||
// First character plain, second bold: Bold turns on across the box.
|
||||
assert_eq!(toggled(false, true, None), "BB");
|
||||
// A bold empty paragraph at the top of the box does not override plain text after it.
|
||||
assert_eq!(toggled(false, true, Some(true)), "BB");
|
||||
}
|
||||
|
||||
/// Toggling a format on a column block follows the first character in document order (#8589).
|
||||
#[test]
|
||||
fn toggle_on_a_column_block_follows_first_character() {
|
||||
let toggled = |bold_row: usize, top_to_bottom: bool| -> Vec<bool> {
|
||||
let mut s = column_doc();
|
||||
run(&mut s, "select.range", json!({"anchor": {"block": bold_row, "off": 2}, "focus": {"block": bold_row, "off": 4}}));
|
||||
run(&mut s, "format.bold", json!({"value": true}));
|
||||
let (a, f) = if top_to_bottom { (Pos::body(0, 2), Pos::body(2, 4)) } else { (Pos::body(2, 4), Pos::body(0, 2)) };
|
||||
run(&mut s, "select.column", json!({"anchor": a, "focus": f}));
|
||||
run(&mut s, "format.bold", json!({}));
|
||||
(0..3).map(|i| s.doc.para_at(&Pos::body(i, 0)).unwrap().props_of_char(2).bold == Some(true)).collect()
|
||||
};
|
||||
// Row 0 bold, rows 1-2 plain: Bold turns off across the block even when selected bottom-to-top.
|
||||
assert_eq!(toggled(0, true), vec![false, false, false]);
|
||||
assert_eq!(toggled(0, false), vec![false, false, false]);
|
||||
// Row 0 plain, row 1 bold: Bold turns on across the block even when selected bottom-to-top.
|
||||
assert_eq!(toggled(1, true), vec![true, true, true]);
|
||||
assert_eq!(toggled(1, false), vec![true, true, true]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bold_at_a_caret_takes_a_word_with_a_typographic_apostrophe() {
|
||||
// Word bolds `don’t` and `dogs’` whole: `’` is part of the word like `'` (#6517).
|
||||
let bold_word = |text: &str, caret: usize| {
|
||||
let mut s = s();
|
||||
run(&mut s, "text.insert", json!({"text": text}));
|
||||
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": caret}}));
|
||||
run(&mut s, "format.bold", json!({}));
|
||||
let p = s.doc.para_at(&Pos::body(0, 0)).unwrap().clone();
|
||||
p.text.char_indices().filter(|&(i, _)| p.props_of_char(i).bold == Some(true)).map(|(_, c)| c).collect::<String>()
|
||||
};
|
||||
assert_eq!(bold_word("don’t stop", 1), "don’t");
|
||||
assert_eq!(bold_word("the dogs’ bone", 5), "dogs’");
|
||||
assert_eq!(bold_word("’tis here", 3), "’tis");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_word_takes_a_typographic_apostrophe() {
|
||||
let mut s = s();
|
||||
run(&mut s, "text.insert", json!({"text": "don’t stop"}));
|
||||
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": 1}}));
|
||||
run(&mut s, "select.word", json!({}));
|
||||
let (a, b) = s.sel.ordered();
|
||||
assert_eq!((a.off, b.off), (0, 8), "`don’t ` with its trailing space, as Word selects it (#6517)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thesaurus_at_a_caret_looks_up_a_quoted_word_without_its_quotes() {
|
||||
// The word unit now takes `’`, so `‘good’` gives `good’`; the lookup drops enclosing quotes.
|
||||
let mut s = s();
|
||||
run(&mut s, "text.insert", json!({"text": "a ‘good’ day"}));
|
||||
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": 6}}));
|
||||
let r = run(&mut s, "review.thesaurus", json!({}));
|
||||
assert_eq!(r["word"], json!("good"));
|
||||
assert!(r["synonyms"].as_array().is_some_and(|a| !a.is_empty()), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_synonym_replaces_the_word_and_keeps_its_quotes() {
|
||||
// The range a chosen synonym replaces (the context menu's): the word without its quotes or the
|
||||
// space after it, while an apostrophe inside a word stays part of it (#6517).
|
||||
let word = |text: &str, caret: usize| {
|
||||
let mut s = s();
|
||||
run(&mut s, "text.insert", json!({"text": text, "raw": true}));
|
||||
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": caret}}));
|
||||
let (a, b) = crate::cmd::review::thesaurus_word(&s).unwrap();
|
||||
s.set_selection(crate::Selection { anchor: a, focus: b });
|
||||
run(&mut s, "text.insert", json!({"text": "fine", "raw": true}));
|
||||
s.doc.plain_text(StoryRef::Body)
|
||||
};
|
||||
assert_eq!(word("a ‘good’ day", 6), "a ‘fine’ day");
|
||||
assert_eq!(word("a 'good' day", 4), "a 'fine' day");
|
||||
assert_eq!(word("a good day", 3), "a fine day");
|
||||
assert_eq!(word("don’t go", 1), "fine go");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn border_toggles_and_saves() {
|
||||
use wordcraft_doc::props::Border;
|
||||
@@ -2054,6 +2237,88 @@ fn paste_merge_formatting_keeps_bold_and_italic_in_a_complex_script_run() {
|
||||
assert!(r.bold_cs, "drawn bold as complex script");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paste_merge_formatting_leaves_plain_what_the_source_draws_plain() {
|
||||
// #4852 review: a run marked `w:cs` is bold and italic only by `w:bCs` and `w:iCs`, so one
|
||||
// with `w:b` and `w:i` alone is drawn plain and pastes plain; one with `w:bCs` pastes bold.
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "x"}));
|
||||
run(&mut s, "caret.docEnd", json!({}));
|
||||
let pasted = |s: &Session, props: wordcraft_doc::CharProps| {
|
||||
let mut frag = wordcraft_doc::edit::Fragment::from_text("ไทย");
|
||||
for b in &mut frag.blocks {
|
||||
crate::cmd::paste::each_para(b, 0, &mut |p| p.runs.iter_mut().for_each(|r| r.props = props.clone()));
|
||||
}
|
||||
crate::cmd::paste::merge_formatting(s, &mut frag);
|
||||
let mut out = Vec::new();
|
||||
for b in &mut frag.blocks {
|
||||
crate::cmd::paste::each_para(b, 0, &mut |p| out.extend(p.runs.iter().map(|r| s.doc.styles.resolve_char(None, &r.props))));
|
||||
}
|
||||
out
|
||||
};
|
||||
let cs = wordcraft_doc::CharProps { cs: Some(true), bold: Some(true), italic: Some(true), ..Default::default() };
|
||||
for r in pasted(&s, cs.clone()) {
|
||||
assert!(!r.bold && !r.bold_cs && !r.italic && !r.italic_cs, "{r:?}");
|
||||
}
|
||||
for r in pasted(&s, wordcraft_doc::CharProps { bold_cs: Some(true), ..cs }) {
|
||||
assert!(r.bold && r.bold_cs && !r.italic_cs, "{r:?}");
|
||||
}
|
||||
// An unmarked run shows `w:b` in both scripts.
|
||||
for r in pasted(&s, wordcraft_doc::CharProps { bold: Some(true), ..Default::default() }) {
|
||||
assert!(r.bold && r.bold_cs, "{r:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paste_merge_formatting_keeps_a_character_styles_emphasis_not_a_paragraph_styles() {
|
||||
// #7177 review, measured in Word for Windows: Merge Formatting keeps the bold, italic,
|
||||
// underline and strikethrough a character style gives the source, as direct formatting, but
|
||||
// drops a paragraph style's.
|
||||
use wordcraft_doc::props::Underline;
|
||||
use wordcraft_doc::styles::{Style, StyleKind};
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "x"}));
|
||||
run(&mut s, "caret.docEnd", json!({}));
|
||||
let on = wordcraft_doc::CharProps {
|
||||
bold: Some(true),
|
||||
bold_cs: Some(true),
|
||||
italic: Some(true),
|
||||
italic_cs: Some(true),
|
||||
underline: Some(Underline::Single),
|
||||
strike: Some(true),
|
||||
..Default::default()
|
||||
};
|
||||
let sheet = Arc::make_mut(&mut s.doc.styles);
|
||||
sheet.upsert(Style { id: "ChEmph".into(), name: "ChEmph".into(), kind: StyleKind::Character, chr: on.clone(), ..Default::default() });
|
||||
sheet.upsert(Style { id: "PEmph".into(), name: "PEmph".into(), kind: StyleKind::Paragraph, chr: on, ..Default::default() });
|
||||
let pasted = |s: &Session, para_style: Option<&str>, props: wordcraft_doc::CharProps| {
|
||||
let mut frag = wordcraft_doc::edit::Fragment::from_text("ไทย Thai");
|
||||
for b in &mut frag.blocks {
|
||||
crate::cmd::paste::each_para(b, 0, &mut |p| {
|
||||
p.props.style = para_style.map(str::to_string);
|
||||
p.runs.iter_mut().for_each(|r| r.props = props.clone());
|
||||
});
|
||||
}
|
||||
crate::cmd::paste::merge_formatting(s, &mut frag);
|
||||
let mut out = Vec::new();
|
||||
for b in &mut frag.blocks {
|
||||
crate::cmd::paste::each_para(b, 0, &mut |p| {
|
||||
out.extend(p.runs.iter().map(|r| s.doc.styles.resolve_char(p.props.style.as_deref(), &r.props)));
|
||||
});
|
||||
}
|
||||
out
|
||||
};
|
||||
for cs in [None, Some(true)] {
|
||||
for r in pasted(&s, None, wordcraft_doc::CharProps { style: Some("ChEmph".into()), cs, ..Default::default() }) {
|
||||
assert!(r.bold && r.bold_cs && r.italic && r.italic_cs && r.strike, "character style, cs {cs:?}: {r:?}");
|
||||
assert_eq!(r.underline, Underline::Single, "character style, cs {cs:?}");
|
||||
}
|
||||
for r in pasted(&s, Some("PEmph"), wordcraft_doc::CharProps { cs, ..Default::default() }) {
|
||||
assert!(!r.bold && !r.bold_cs && !r.italic && !r.italic_cs && !r.strike, "paragraph style, cs {cs:?}: {r:?}");
|
||||
assert_eq!(r.underline, Underline::None, "paragraph style, cs {cs:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn pasted_rtf_sections_link_their_headers_to_the_previous() {
|
||||
// #1378: the RTF's own header part ids mean nothing in this document; a pasted section
|
||||
@@ -7301,6 +7566,64 @@ fn saving_a_text_file_over_itself_saves_the_document() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// #6131: File › Export to DOCX, ODT or RTF writes a copy (`copy: true`). It made the copy the
|
||||
/// document's file and cleared its unsaved changes, so the next Save went to the copy and the
|
||||
/// original kept its old text. The copy has the edits; the document keeps its file, its changes
|
||||
/// and its save stamps.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn exporting_a_copy_keeps_the_documents_file() {
|
||||
let dir = std::env::temp_dir().join(format!("wordcraft-engine-export-copy-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let body = |p: &std::path::Path| crate::io::open_path(p).unwrap().plain_text(wordcraft_doc::StoryRef::Body);
|
||||
for ext in ["docx", "odt", "rtf"] {
|
||||
let original = dir.join(format!("a-{ext}.docx"));
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
run(&mut s, "text.insert", json!({"text": "first"}));
|
||||
run(&mut s, "file.save", json!({"path": original.to_string_lossy()}));
|
||||
run(&mut s, "text.insert", json!({"text": " edited"}));
|
||||
let stamps = (s.doc.core.revision, s.doc.core.modified.clone());
|
||||
let copy = dir.join(format!("copy.{ext}"));
|
||||
let r = run(&mut s, "file.saveAs", json!({"path": copy.to_string_lossy(), "copy": true}));
|
||||
assert_eq!(r["saved"], true, "{ext}");
|
||||
assert_eq!(body(©), "first edited", "{ext}: the copy has the edits");
|
||||
assert_eq!(s.path.as_deref(), Some(original.as_path()), "{ext}: the document keeps its file");
|
||||
assert!(s.dirty, "{ext}: the document keeps its unsaved changes");
|
||||
assert_eq!((s.doc.core.revision, s.doc.core.modified.clone()), stamps, "{ext}: the document's save stamps are untouched");
|
||||
run(&mut s, "file.save", json!({}));
|
||||
assert_eq!(body(&original), "first edited", "{ext}: Save still writes the original");
|
||||
assert!(!s.dirty);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A copy with no path would open the Save As picker on an untitled document (whose answer is an
|
||||
/// ordinary save that adopts the file) or fall back to the open file's path and overwrite it while
|
||||
/// leaving the document dirty: refused in both cases (#6131 review).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_copy_without_a_path_is_refused() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
run(&mut s, "text.insert", json!({"text": "first"}));
|
||||
let e = s.run("file.save", &json!({"copy": true})).unwrap_err();
|
||||
assert!(e.to_string().contains("copy"), "{e}");
|
||||
assert!(s.ui_requests.is_empty(), "no picker opens");
|
||||
|
||||
let dir = std::env::temp_dir().join(format!("wordcraft-engine-copy-no-path-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let original = dir.join("doc.docx");
|
||||
run(&mut s, "file.save", json!({"path": original.to_string_lossy()}));
|
||||
run(&mut s, "text.insert", json!({"text": " edited"}));
|
||||
let e = s.run("file.save", &json!({"copy": true})).unwrap_err();
|
||||
assert!(e.to_string().contains("copy"), "{e}");
|
||||
assert!(s.dirty, "the document keeps its unsaved changes");
|
||||
let on_disk = crate::io::open_path(&original).unwrap().plain_text(wordcraft_doc::StoryRef::Body);
|
||||
assert_eq!(on_disk, "first", "the original file on disk was not overwritten");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A Markdown file saved as another Markdown file is that file from now on: the next save goes
|
||||
/// there and the first file stays as it was. Other formats keep the #2376 rule.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
|
||||
@@ -1653,6 +1653,38 @@ fn a_link_keeps_a_selection_it_cannot_retype() {
|
||||
assert_eq!(s.doc.field_ranges(StoryRef::Body).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_column_selection_in_one_paragraph_is_not_one_line() {
|
||||
// A column (block) selection over the wrapped lines of one paragraph: both its ends are in
|
||||
// that paragraph, but it holds a piece of each line, so Word shows <<Selection in Document>>
|
||||
// for it and the text to display can't retype it (#8581).
|
||||
let mut s = typed("alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron pi rho sigma tau");
|
||||
let (first, second) = {
|
||||
let l = s.layout();
|
||||
let len = s.doc.para_at(&Pos::body(0, 0)).unwrap().text.len();
|
||||
let mut top = None;
|
||||
let mut first = None;
|
||||
let mut second = None;
|
||||
for off in 0..=len {
|
||||
let Some(c) = l.caret_on(&Pos::body(0, off), 0) else { continue };
|
||||
if top.is_some_and(|t| t != c.top) && second.is_none() {
|
||||
second = Some(off + 10);
|
||||
break;
|
||||
}
|
||||
if top.is_none() {
|
||||
top = Some(c.top);
|
||||
first = Some(off);
|
||||
}
|
||||
}
|
||||
(first.expect("the paragraph is laid out"), second.expect("the paragraph wraps"))
|
||||
};
|
||||
run(&mut s, "select.column", json!({"anchor": Pos::body(0, first), "focus": Pos::body(0, second)}));
|
||||
let segs = s.column_segments().expect("the block is one paragraph's lines").to_vec();
|
||||
assert_eq!(segs.len(), 2, "the block holds a piece of each of the paragraph's two lines");
|
||||
assert!(segs.iter().all(|(a, b)| a.path == segs[0].0.path && b.path == segs[0].0.path), "both pieces are in one paragraph");
|
||||
assert!(!crate::cmd::insert::selection_is_one_line(&s), "a column selection is not one line of text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typing_then_selecting_then_typing_are_two_undo_steps() {
|
||||
// #419: a selection that moves the insertion point ends the typing group, like a caret move.
|
||||
|
||||
@@ -129,6 +129,105 @@ fn a_date_field_in_a_header_is_refreshed_too() {
|
||||
assert_eq!(found, [today], "the header's field is refreshed as well as the body's");
|
||||
}
|
||||
|
||||
/// A document whose `docDefaults` set `lang`, so a field run that names no language inherits it,
|
||||
/// as a German Word document does.
|
||||
fn open_body_in_lang(lang: &str, body: &str) -> wordcraft_doc::Document {
|
||||
let rels = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
|
||||
let doc_rels = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rIdStyles" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>"#;
|
||||
let styles = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8"?><w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:docDefaults><w:rPrDefault><w:rPr><w:lang w:val="{lang}"/></w:rPr></w:rPrDefault></w:docDefaults><w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style></w:styles>"#
|
||||
);
|
||||
let doc = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
|
||||
);
|
||||
wordcraft_engine::io::open_bytes(
|
||||
"d.docx",
|
||||
&zip(&[("_rels/.rels", rels), ("word/document.xml", &doc), ("word/_rels/document.xml.rels", doc_rels), ("word/styles.xml", &styles)]),
|
||||
)
|
||||
.expect("opens")
|
||||
}
|
||||
|
||||
/// German documents carry their language in `docDefaults`, not on each field run. A `DATE` field
|
||||
/// without `\@` therefore uses `dd.MM.yyyy`, and `MMMM`/`dddd` name the day in German, on open
|
||||
/// and on an explicit refresh, for `de-DE`, `de-AT` and `de-CH` (#7146).
|
||||
#[test]
|
||||
fn german_date_fields_inherit_the_document_default_language() {
|
||||
const PICTURE: &str = "dddd, d. MMMM yyyy";
|
||||
for lang in ["de-DE", "de-AT", "de-CH"] {
|
||||
let d = open_body_in_lang(
|
||||
lang,
|
||||
&format!(
|
||||
"<w:p>{}</w:p><w:p>{}</w:p>",
|
||||
field(&format!(r#"DATE \@ "{PICTURE}""#), "Wednesday, 1 January 2020", false),
|
||||
field("DATE", "1/1/2020", false)
|
||||
),
|
||||
);
|
||||
let expected = wordcraft_engine::cmd::insert::format_date_in(PICTURE, Some(lang));
|
||||
let got = fields(&d);
|
||||
assert_eq!(got.len(), 2, "{lang}");
|
||||
assert_eq!(got[0].1, expected, "{lang}: weekday and month names come from docDefaults");
|
||||
assert_ne!(got[0].1, wordcraft_engine::cmd::insert::format_date_in(PICTURE, None), "{lang}: not the English names");
|
||||
assert_eq!(
|
||||
got[1].1,
|
||||
wordcraft_engine::cmd::insert::format_date_in("dd.MM.yyyy", Some(lang)),
|
||||
"{lang}: a DATE field without a picture uses the German default"
|
||||
);
|
||||
// Saving and reopening keeps the inherited language, and an explicit refresh does not
|
||||
// fall back to English.
|
||||
let written = wordcraft_docx::write(&d).unwrap();
|
||||
let mut reopened = wordcraft_engine::io::open_bytes("reopened.docx", &written).unwrap();
|
||||
wordcraft_engine::cmd::references::refresh_date_fields(&mut reopened);
|
||||
let got = fields(&reopened);
|
||||
assert_eq!(got[0].1, expected, "{lang}: after round-trip");
|
||||
assert_eq!(got[1].1, wordcraft_engine::cmd::insert::format_date_in("dd.MM.yyyy", Some(lang)), "{lang}: after round-trip");
|
||||
}
|
||||
}
|
||||
|
||||
/// `MMM` and `ddd` use Word's Windows NLS short forms for German: two-letter weekdays (`So`,
|
||||
/// `Mo`…) and `Mrz` for March, with no trailing full stop (#7146).
|
||||
#[test]
|
||||
fn a_german_short_date_field_uses_windows_nls_abbreviations() {
|
||||
const PICTURE: &str = "ddd, d. MMM yyyy";
|
||||
let d = open_body_in_lang("de-DE", &format!("<w:p>{}</w:p>", field(&format!(r#"DATE \@ "{PICTURE}""#), "Wed, 1 Jan 2020", false)));
|
||||
let got = fields(&d);
|
||||
assert_eq!(got[0].1, wordcraft_engine::cmd::insert::format_date_in(PICTURE, Some("de-DE")));
|
||||
// The abbreviations at a fixed date, independent of when the test runs.
|
||||
assert_eq!(wordcraft_engine::cmd::insert::format_date_parts_in(PICTURE, Some("de-DE"), 2026, 3, 15, (12, 0, 0), 3), "So, 15. Mrz 2026");
|
||||
}
|
||||
|
||||
/// A `TIME` field whose picture carries German name tokens inherits the language too, so the
|
||||
/// English result cached in the fixture is replaced with German weekday and month names.
|
||||
#[test]
|
||||
fn a_german_time_field_uses_german_names() {
|
||||
const PICTURE: &str = "dddd, d. MMMM yyyy 'um' HH:mm";
|
||||
let d =
|
||||
open_body_in_lang("de-DE", &format!("<w:p>{}</w:p>", field(&format!(r#"TIME \@ "{PICTURE}""#), "Wednesday, 1 January 2020 um 00:00", false)));
|
||||
let got = fields(&d);
|
||||
assert_eq!(got[0].0, format!(r#"TIME \@ "{PICTURE}""#));
|
||||
assert_eq!(got[0].1, wordcraft_engine::cmd::insert::format_date_in(PICTURE, Some("de-DE")));
|
||||
}
|
||||
|
||||
/// Austrian Standard German writes January as `Jänner` (`Jän`), while Germany, Switzerland and
|
||||
/// bare `de` keep `Januar` (`Jan`), as in Windows NLS (#7146). A `de-AT` document reads German
|
||||
/// through `docDefaults`; the refresh always uses the real clock, so the January names are asked
|
||||
/// of the same formatter at a fixed January instant.
|
||||
#[test]
|
||||
fn austrian_german_documents_use_jaenner() {
|
||||
const PICTURE: &str = "dddd, d. MMMM yyyy";
|
||||
let d = open_body_in_lang("de-AT", &format!("<w:p>{}</w:p>", field(&format!(r#"DATE \@ "{PICTURE}""#), "Wednesday, 1 January 2020", false)));
|
||||
let got = fields(&d);
|
||||
assert_eq!(got[0].1, wordcraft_engine::cmd::insert::format_date_in(PICTURE, Some("de-AT")), "an Austrian document reads German");
|
||||
|
||||
let january = |lang: &str, picture: &str| wordcraft_engine::cmd::insert::format_date_parts_in(picture, Some(lang), 2026, 1, 15, (12, 0, 0), 0);
|
||||
assert_eq!(january("de-AT", "MMMM"), "Jänner");
|
||||
assert_eq!(january("de-AT", "MMM"), "Jän");
|
||||
assert_eq!(january("de-AT", PICTURE), "Donnerstag, 15. Jänner 2026");
|
||||
for lang in ["de-DE", "de-CH", "de"] {
|
||||
assert_eq!(january(lang, "MMMM"), "Januar", "{lang}");
|
||||
assert_eq!(january(lang, "MMM"), "Jan", "{lang}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A minimal Word 97-2003 file whose only paragraph holds a `DATE` field cached as " 2001":
|
||||
/// FIB, one compressed text piece, and the Clx that points at it.
|
||||
fn binary_doc_with_stale_date() -> Vec<u8> {
|
||||
|
||||
@@ -25,7 +25,7 @@ mod lookup;
|
||||
mod names;
|
||||
|
||||
use face::{BUNDLED, FontBytes};
|
||||
pub use face::{FALLBACK_FAMILY, FaceRef, FontFace, bundled};
|
||||
pub use face::{FALLBACK_FAMILY, FaceRef, FontFace, bundled, bundled_inter};
|
||||
#[cfg(test)]
|
||||
use fallback_data::{Coverage, RUN_FALLBACK_CACHE_CHARS, SYS_FALLBACK_MAX_FILE, file_coverage, ranges_hold};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
|
||||
@@ -13,6 +13,16 @@ pub fn bundled() -> &'static [&'static [u8]] {
|
||||
BUNDLED
|
||||
}
|
||||
|
||||
/// The bundled Inter Regular and SemiBold, each with its style name: the same bytes as in [`bundled`], so a caller
|
||||
/// adds no second copy to the binary. The interface draws with them behind the suite's Inter, which is cut to Latin,
|
||||
/// Greek and Cyrillic.
|
||||
pub fn bundled_inter() -> [(&'static str, &'static [u8]); 2] {
|
||||
[("Regular", INTER_REGULAR), ("SemiBold", INTER_SEMIBOLD)]
|
||||
}
|
||||
|
||||
static INTER_REGULAR: &[u8] = include_bytes!("../../../../assets/fonts/Inter-Regular.ttf");
|
||||
static INTER_SEMIBOLD: &[u8] = include_bytes!("../../../../assets/fonts/Inter-SemiBold.ttf");
|
||||
|
||||
pub(super) static BUNDLED: &[&[u8]] = &[
|
||||
include_bytes!("../../../../assets/fonts/SourceSans3-Regular.ttf"),
|
||||
include_bytes!("../../../../assets/fonts/SourceSans3-Semibold.ttf"),
|
||||
@@ -23,9 +33,9 @@ pub(super) static BUNDLED: &[&[u8]] = &[
|
||||
include_bytes!("../../../../assets/fonts/SourceSerif4-Semibold.ttf"),
|
||||
include_bytes!("../../../../assets/fonts/SourceSerif4-Bold.ttf"),
|
||||
include_bytes!("../../../../assets/fonts/SourceSerif4-BoldIt.ttf"),
|
||||
include_bytes!("../../../../assets/fonts/Inter-Regular.ttf"),
|
||||
INTER_REGULAR,
|
||||
include_bytes!("../../../../assets/fonts/Inter-Medium.ttf"),
|
||||
include_bytes!("../../../../assets/fonts/Inter-SemiBold.ttf"),
|
||||
INTER_SEMIBOLD,
|
||||
include_bytes!("../../../../assets/fonts/JetBrainsMono-Regular.ttf"),
|
||||
];
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ pub mod word;
|
||||
|
||||
pub use fontdb::{
|
||||
FALLBACK_FAMILY, FONT_FILE_EXTS, FaceRef, FontDb, FontFace, FontFormat, Installed, LocalName, MAX_FONT_FILE_BYTES, UserFont, UserFontError,
|
||||
base_style, bundled, decode_font_file, is_font_file_name, name_language_matches, sniff, system_font_dirs,
|
||||
base_style, bundled, bundled_inter, decode_font_file, is_font_file_name, name_language_matches, sniff, system_font_dirs,
|
||||
};
|
||||
pub use harfrust::Feature;
|
||||
use harfrust::{Direction, ShapeOptions, ShapePlan, ShapePlanKey, Shaper, Tag, UnicodeBuffer};
|
||||
|
||||
+337
-9
@@ -95,15 +95,7 @@ pub fn read_rows(bytes: &[u8], pick: Pick<'_>) -> Result<(Vec<String>, Vec<Vec<S
|
||||
let names: Vec<String> = book.sheets.iter().map(|s| s.name.clone()).collect();
|
||||
let i = resolve(&names, pick)?;
|
||||
let sheet = &book.sheets[i];
|
||||
let rows = cells_to_rows(&sheet.cells, |c| {
|
||||
if !c.text.is_empty() {
|
||||
clamp_cell(c.text.clone())
|
||||
} else if let Some(v) = c.value() {
|
||||
format_value(&v)
|
||||
} else {
|
||||
String::new()
|
||||
}
|
||||
});
|
||||
let rows = cells_to_rows(&sheet.cells, ods_value);
|
||||
return Ok((names, rows));
|
||||
}
|
||||
Err("not an Excel or OpenDocument spreadsheet".into())
|
||||
@@ -178,6 +170,187 @@ fn format_value(v: &Value) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// An OpenDocument cell's display string, from `office:value-type`: floats from `office:value`,
|
||||
/// dates and times from `office:date-value` / `office:time-value` in ISO 8601 form (`yyyy-mm-dd`,
|
||||
/// `yyyy-mm-dd hh:mm[:ss]`, `hh:mm[:ss]`), booleans as `TRUE`/`FALSE`, and strings, percentages
|
||||
/// and currencies as the cell's text (their value when the text is blank). A value that does not
|
||||
/// parse falls back to the text. A covered cell under a merged cell is blank.
|
||||
///
|
||||
/// A float merges its value, not the text its number format shows: a ZIP code `01234` shown
|
||||
/// through the format `00000` merges as `1234`, and `1,234` shown with a thousands separator
|
||||
/// merges as `1234`.
|
||||
fn ods_value(c: &craft_ods::Cell) -> String {
|
||||
use craft_ods::ValueType as T;
|
||||
if c.covered {
|
||||
return String::new();
|
||||
}
|
||||
let typed = match (c.value_type, c.raw.as_deref().map(str::trim)) {
|
||||
(Some(T::Float | T::Boolean), Some(_)) => c.value().map(|v| format_value(&v)),
|
||||
(Some(T::Date), Some(v)) => iso_datetime(v),
|
||||
(Some(T::Time), Some(v)) => iso_time(v),
|
||||
(Some(T::Percentage | T::Currency | T::String), Some(_)) if c.text.is_empty() => c.value().map(|v| format_value(&v)),
|
||||
_ => None,
|
||||
};
|
||||
typed.map(clamp_cell).unwrap_or_else(|| clamp_cell(c.text.clone()))
|
||||
}
|
||||
|
||||
/// An ISO 8601 date or date-time (`2024-03-05`, `2024-03-05T13:45:00.000`) as `yyyy-mm-dd`,
|
||||
/// with ` hh:mm[:ss]` when the time isn't midnight. `None` unless the whole value is a valid
|
||||
/// calendar date and clock time.
|
||||
fn iso_datetime(v: &str) -> Option<String> {
|
||||
use chrono::Datelike;
|
||||
let v = v.trim();
|
||||
let (date, time) = match v.split_once('T') {
|
||||
Some((date, time)) => (date, Some(time)),
|
||||
None => (v, None),
|
||||
};
|
||||
// A date alone may carry a zone (`Z` or `±hh:mm`), which is left out.
|
||||
let date = match (time, date.strip_suffix('Z')) {
|
||||
(None, Some(d)) => d,
|
||||
(None, None) if date.len() > 6 && date.get(date.len() - 6..).is_some_and(|z| z.starts_with(['+', '-']) && z.get(3..4) == Some(":")) => {
|
||||
zone_offset(date.get(date.len() - 5..)?)?;
|
||||
date.get(..date.len() - 6)?
|
||||
}
|
||||
_ => date,
|
||||
};
|
||||
let date = chrono::NaiveDate::parse_from_str(date, "%Y-%m-%d").ok()?;
|
||||
let mut out = format!("{:04}-{:02}-{:02}", date.year(), date.month(), date.day());
|
||||
if let Some(time) = time {
|
||||
let (clock, fraction) = clock_time(time)?;
|
||||
if clock != chrono::NaiveTime::MIN || !fraction.is_empty() {
|
||||
out.push(' ');
|
||||
out.push_str(&hh_mm((clock, fraction)));
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// A clock time `hh:mm[:ss[.s…]]` with an optional `Z` or `±hh:mm` zone (one, not both), which is
|
||||
/// left out. The seconds' fraction comes back as its digits as written, trailing zeros dropped,
|
||||
/// so a fraction finer than a nanosecond is kept.
|
||||
fn clock_time(t: &str) -> Option<(chrono::NaiveTime, String)> {
|
||||
let t = match (t.strip_suffix('Z'), t.rfind(['+', '-'])) {
|
||||
(Some(t), _) => t,
|
||||
(None, Some(i)) => {
|
||||
zone_offset(t.get(i + 1..)?)?;
|
||||
t.get(..i)?
|
||||
}
|
||||
(None, None) => t,
|
||||
};
|
||||
let (clock, fraction) = match t.split_once('.') {
|
||||
// A fraction needs whole seconds before it.
|
||||
Some((t, frac)) => {
|
||||
if frac.is_empty() || !frac.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
(chrono::NaiveTime::parse_from_str(t, "%H:%M:%S").ok()?, frac.trim_end_matches('0'))
|
||||
}
|
||||
None => (chrono::NaiveTime::parse_from_str(t, "%H:%M:%S").or_else(|_| chrono::NaiveTime::parse_from_str(t, "%H:%M")).ok()?, ""),
|
||||
};
|
||||
// A leap second (`23:59:60`) is not a time a cell holds.
|
||||
(chrono::Timelike::nanosecond(&clock) < 1_000_000_000).then(|| (clock, fraction.to_string()))
|
||||
}
|
||||
|
||||
/// A zone offset's `hh:mm`, two digits each and at most `14:00` as XML Schema allows.
|
||||
fn zone_offset(z: &str) -> Option<()> {
|
||||
use chrono::Timelike;
|
||||
let two_digit = z.len() == 5 && z.bytes().enumerate().all(|(i, b)| if i == 2 { b == b':' } else { b.is_ascii_digit() });
|
||||
if !two_digit {
|
||||
return None;
|
||||
}
|
||||
let z = chrono::NaiveTime::parse_from_str(z, "%H:%M").ok()?;
|
||||
(z.hour() < 14 || (z.hour() == 14 && z.minute() == 0)).then_some(())
|
||||
}
|
||||
|
||||
/// `hh:mm`, with `:ss` when the seconds aren't zero and their fraction when it isn't.
|
||||
fn hh_mm((t, fraction): (chrono::NaiveTime, String)) -> String {
|
||||
use chrono::Timelike;
|
||||
let (h, m, s) = (t.hour(), t.minute(), t.second());
|
||||
if !fraction.is_empty() {
|
||||
format!("{h:02}:{m:02}:{s:02}.{fraction}")
|
||||
} else if s == 0 {
|
||||
format!("{h:02}:{m:02}")
|
||||
} else {
|
||||
format!("{h:02}:{m:02}:{s:02}")
|
||||
}
|
||||
}
|
||||
|
||||
/// An ISO 8601 duration (`PT13H45M00S`, `P1DT2H`, `-PT1H`) or clock time (`13:45[:00]`) as
|
||||
/// `hh:mm[:ss]`, a duration's days counted as hours and a negative one with a leading `-`.
|
||||
/// `None` for anything else, years and months included.
|
||||
fn iso_time(v: &str) -> Option<String> {
|
||||
let t = v.trim();
|
||||
let (negative, t) = match t.strip_prefix('-') {
|
||||
Some(rest) => (true, rest),
|
||||
None => (false, t),
|
||||
};
|
||||
let Some(t) = t.strip_prefix('P') else {
|
||||
return if negative { None } else { clock_time(t).map(hh_mm) };
|
||||
};
|
||||
let (days, t, has_t) = match t.split_once('T') {
|
||||
Some((days, time)) => (days, time, true),
|
||||
None => (t, "", false),
|
||||
};
|
||||
// A `T` needs a time after it.
|
||||
if has_t && t.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut any = !days.is_empty();
|
||||
let days: u64 = if days.is_empty() { 0 } else { days.strip_suffix('D')?.parse().ok()? };
|
||||
let (mut h, mut m, mut s) = (0u64, 0u64, 0u64);
|
||||
// The seconds' fraction digits, kept as written.
|
||||
let mut fraction = String::new();
|
||||
let mut num = String::new();
|
||||
// Units come in the order H, M, S, each at most once.
|
||||
let mut next_unit = 0;
|
||||
for c in t.chars() {
|
||||
let unit = match c {
|
||||
'H' => 1,
|
||||
'M' => 2,
|
||||
'S' => 3,
|
||||
'0'..='9' | '.' if num.len() < 20 => {
|
||||
num.push(c);
|
||||
continue;
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
if unit <= next_unit {
|
||||
return None;
|
||||
}
|
||||
next_unit = unit;
|
||||
let n = std::mem::take(&mut num);
|
||||
match unit {
|
||||
1 => h = n.parse().ok()?,
|
||||
2 => m = n.parse().ok()?,
|
||||
_ => {
|
||||
let (whole, frac) = n.split_once('.').unwrap_or((&n, ""));
|
||||
if whole.is_empty() || (n.contains('.') && frac.is_empty()) || !frac.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
s = whole.parse().ok()?;
|
||||
fraction = frac.trim_end_matches('0').to_string();
|
||||
}
|
||||
}
|
||||
any = true;
|
||||
}
|
||||
if !any || !num.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// A duration too long to count in hours is not a time.
|
||||
m = m.checked_add(s / 60)?;
|
||||
s %= 60;
|
||||
h = h.checked_add(m / 60)?.checked_add(days.checked_mul(24)?)?;
|
||||
m %= 60;
|
||||
let sign = if negative && ((h, m, s) != (0, 0, 0) || !fraction.is_empty()) { "-" } else { "" };
|
||||
Some(if !fraction.is_empty() {
|
||||
format!("{sign}{h:02}:{m:02}:{s:02}.{fraction}")
|
||||
} else if s == 0 {
|
||||
format!("{sign}{h:02}:{m:02}")
|
||||
} else {
|
||||
format!("{sign}{h:02}:{m:02}:{s:02}")
|
||||
})
|
||||
}
|
||||
|
||||
fn cells_to_rows<C>(cells: &BTreeMap<CellRef, C>, fmt: impl Fn(&C) -> String) -> Vec<Vec<String>> {
|
||||
let mut grid: BTreeMap<(u32, u32), String> = BTreeMap::new();
|
||||
for (r, c) in cells {
|
||||
@@ -208,3 +381,158 @@ fn grid_to_rows(grid: &BTreeMap<(u32, u32), String>) -> Vec<Vec<String>> {
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// An `.ods` package whose body is `tables` (`table:table` elements).
|
||||
fn spreadsheet(tables: &str) -> Result<Vec<u8>, craft_odf::Error> {
|
||||
let content = format!(
|
||||
r#"<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"><office:body><office:spreadsheet>{tables}</office:spreadsheet></office:body></office:document-content>"#
|
||||
);
|
||||
let mut w = craft_odf::PackageWriter::new(craft_odf::mime::SPREADSHEET);
|
||||
w.file("content.xml", "text/xml", content.as_bytes());
|
||||
w.finish()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ods_cells_read_their_typed_values() {
|
||||
let book = spreadsheet(
|
||||
r#"<table:table table:name="Guests">
|
||||
<table:table-row><table:table-cell office:value-type="string"><text:p>Name</text:p></table:table-cell><table:table-cell table:number-columns-repeated="2"/><table:table-cell office:value-type="string"><text:p>When</text:p></table:table-cell><table:table-cell office:value-type="string" table:number-columns-repeated="2"><text:p>Tag</text:p></table:table-cell></table:table-row>
|
||||
<table:table-row table:number-rows-repeated="2"><table:table-cell office:value-type="string" table:number-columns-spanned="2"><text:p>Ada<text:s text:c="2"/>L</text:p><text:p>x</text:p><office:annotation><text:p>note</text:p></office:annotation></table:table-cell><table:covered-table-cell office:value-type="string"><text:p>hidden</text:p></table:covered-table-cell><table:table-cell office:value-type="float" office:value="3.50"><text:p>3,5</text:p></table:table-cell><table:table-cell office:value-type="date" office:date-value="2024-03-05T00:00:00"><text:p>05/03/24</text:p></table:table-cell><table:table-cell office:value-type="boolean" office:boolean-value="false"><text:p>NO</text:p></table:table-cell><table:table-cell office:value-type="time" office:time-value="PT13H45M00S"><text:p>01:45 PM</text:p></table:table-cell></table:table-row>
|
||||
<table:table-row><table:table-cell office:value-type="date" office:date-value="2024-03-05T13:45:30"><text:p>Tue</text:p></table:table-cell><table:table-cell office:value-type="date" office:date-value="not a date"><text:p>someday</text:p></table:table-cell><table:table-cell office:value-type="percentage" office:value="0.25"><text:p>25%</text:p></table:table-cell><table:table-cell office:value-type="currency" office:value="9"/></table:table-row>
|
||||
</table:table>"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (_, rows) = read_rows(&book, Pick::Name("Guests")).unwrap();
|
||||
assert_eq!(rows.len(), 4);
|
||||
assert_eq!(rows[0], ["Name", "", "", "When", "Tag", "Tag"]);
|
||||
assert_eq!(rows[1], ["Ada L\nx", "", "3.5", "2024-03-05", "FALSE", "13:45"]);
|
||||
assert_eq!(rows[1], rows[2]);
|
||||
assert_eq!(rows[3], ["2024-03-05 13:45:30", "someday", "25%", "9"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ods_date_with_two_zones_reads_its_text() {
|
||||
let book = spreadsheet(
|
||||
r#"<table:table table:name="Dates">
|
||||
<table:table-row><table:table-cell office:value-type="date" office:date-value="2024-03-05T13:45:00+02:00Z"><text:p>offset then Z</text:p></table:table-cell><table:table-cell office:value-type="date" office:date-value="2024-03-05T13:45:00Z+02:00"><text:p>Z then offset</text:p></table:table-cell><table:table-cell office:value-type="date" office:date-value="2024-03-05T13:45:00+02:00"><text:p>one zone</text:p></table:table-cell></table:table-row>
|
||||
</table:table>"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (_, rows) = read_rows(&book, Pick::Name("Dates")).unwrap();
|
||||
assert_eq!(rows, [["offset then Z", "Z then offset", "2024-03-05 13:45"]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ods_dates_and_durations() {
|
||||
assert_eq!(iso_time("PT1H59M59.6S").as_deref(), Some("01:59:59.6"));
|
||||
assert_eq!(iso_time("PT0.25S").as_deref(), Some("00:00:00.25"));
|
||||
assert_eq!(iso_time("PT59M60.50S").as_deref(), Some("01:00:00.5"));
|
||||
assert_eq!(iso_time("PT0H0M59S").as_deref(), Some("00:00:59"));
|
||||
assert_eq!(iso_time("PT1H2M3S").as_deref(), Some("01:02:03"));
|
||||
assert_eq!(iso_time("PT1.S"), None);
|
||||
assert_eq!(iso_time("P1000000000000000000D"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clock_time_keeps_its_seconds_fraction_as_written() {
|
||||
assert_eq!(iso_datetime("2024-03-05T00:00:00.0000000001").as_deref(), Some("2024-03-05 00:00:00.0000000001"));
|
||||
assert_eq!(iso_datetime("2024-03-05T13:45:30.1234567891Z").as_deref(), Some("2024-03-05 13:45:30.1234567891"));
|
||||
assert_eq!(iso_datetime("2024-03-05T13:45:30.500+02:00").as_deref(), Some("2024-03-05 13:45:30.5"));
|
||||
assert_eq!(iso_datetime("2024-03-05T00:00:00.000").as_deref(), Some("2024-03-05"));
|
||||
assert_eq!(iso_time("13:45:00.1234567891").as_deref(), Some("13:45:00.1234567891"));
|
||||
assert_eq!(iso_time("PT13H45M0.1234567891S").as_deref(), Some("13:45:00.1234567891"));
|
||||
assert_eq!(iso_time("13:45:00."), None);
|
||||
assert_eq!(iso_time("13:45:00.5x"), None);
|
||||
assert_eq!(iso_time("13:45.5"), None);
|
||||
assert_eq!(iso_time("23:59:60.5"), None);
|
||||
assert_eq!(iso_time("13: 45.5"), None);
|
||||
assert_eq!(iso_time("1:45:30.5").as_deref(), Some("01:45:30.5"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_typed_ods_value_keeps_to_the_cell_limit() {
|
||||
let long = format!("2024-03-05T13:45:30.{}", "1".repeat(MAX_CELL_CHARS));
|
||||
let book = spreadsheet(&format!(
|
||||
r#"<table:table table:name="Long"><table:table-row><table:table-cell office:value-type="date" office:date-value="{long}"><text:p>x</text:p></table:table-cell></table:table-row></table:table>"#
|
||||
))
|
||||
.unwrap();
|
||||
let (_, rows) = read_rows(&book, Pick::Name("Long")).unwrap();
|
||||
assert_eq!(rows[0][0].chars().count(), MAX_CELL_CHARS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_date_alone_drops_its_zone() {
|
||||
assert_eq!(iso_datetime("2024-03-05Z").as_deref(), Some("2024-03-05"));
|
||||
assert_eq!(iso_datetime("2024-03-05+02:00").as_deref(), Some("2024-03-05"));
|
||||
assert_eq!(iso_datetime("2024-03-05-05:00").as_deref(), Some("2024-03-05"));
|
||||
assert_eq!(iso_datetime("2024-03-05+02:99"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_zone_is_at_most_fourteen_hours() {
|
||||
assert_eq!(iso_datetime("2024-03-05+14:00").as_deref(), Some("2024-03-05"));
|
||||
assert_eq!(iso_datetime("2024-03-05-14:00").as_deref(), Some("2024-03-05"));
|
||||
assert_eq!(iso_datetime("2024-03-05+14:01"), None);
|
||||
assert_eq!(iso_datetime("2024-03-05-15:00"), None);
|
||||
assert_eq!(iso_datetime("2024-03-05T13:45:00+14:00").as_deref(), Some("2024-03-05 13:45"));
|
||||
assert_eq!(iso_datetime("2024-03-05T13:45:00+14:01"), None);
|
||||
assert_eq!(iso_time("13:45:00-15:00"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_zone_is_z_or_an_offset_not_both() {
|
||||
assert_eq!(iso_datetime("2024-03-05T13:45:00+02:00Z"), None);
|
||||
assert_eq!(iso_datetime("2024-03-05T13:45:00Z+02:00"), None);
|
||||
assert_eq!(iso_datetime("2024-03-05+02:00Z"), None);
|
||||
assert_eq!(iso_datetime("2024-03-05Z+02:00"), None);
|
||||
assert_eq!(iso_time("13:45:00+02:00Z"), None);
|
||||
assert_eq!(iso_time("13:45:00Z+02:00"), None);
|
||||
assert_eq!(iso_datetime("2024-03-05T13:45:00Z").as_deref(), Some("2024-03-05 13:45"));
|
||||
assert_eq!(iso_datetime("2024-03-05T13:45:00-05:00").as_deref(), Some("2024-03-05 13:45"));
|
||||
assert_eq!(iso_time("13:45:00+02:00").as_deref(), Some("13:45"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_zone_offset_has_two_digit_hours_and_minutes() {
|
||||
assert_eq!(iso_datetime("2024-03-05T13:45:00+2:00"), None);
|
||||
assert_eq!(iso_datetime("2024-03-05T13:45:00+ 2:00"), None);
|
||||
assert_eq!(iso_time("13:45:00-5:00"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_leap_second_is_not_a_time() {
|
||||
assert_eq!(iso_datetime("2024-03-05T23:59:60Z"), None);
|
||||
assert_eq!(iso_time("23:59:60"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_duration_with_t_needs_a_time() {
|
||||
assert_eq!(iso_time("P1DT"), None);
|
||||
assert_eq!(iso_time("P0DT"), None);
|
||||
assert_eq!(iso_time("P1D").as_deref(), Some("24:00"));
|
||||
assert_eq!(iso_time("PT.S"), None);
|
||||
assert_eq!(iso_time("13:45:00Z").as_deref(), Some("13:45"));
|
||||
assert_eq!(iso_time("-PT1H").as_deref(), Some("-01:00"));
|
||||
assert_eq!(iso_time("P2DT1H30M").as_deref(), Some("49:30"));
|
||||
assert_eq!(iso_time("P1D").as_deref(), Some("24:00"));
|
||||
assert_eq!(iso_time("P1Y2M"), None);
|
||||
assert_eq!(iso_time("PT"), None);
|
||||
assert_eq!(iso_time("PT5"), None);
|
||||
assert_eq!(iso_time("PT1H2H"), None);
|
||||
assert_eq!(iso_time("PT1S2H"), None);
|
||||
assert_eq!(iso_datetime("2024-03-05T"), None);
|
||||
assert_eq!(iso_datetime("2024-03-05T00:00:00.500").as_deref(), Some("2024-03-05 00:00:00.5"));
|
||||
assert_eq!(iso_time("00:00:00.250").as_deref(), Some("00:00:00.25"));
|
||||
assert_eq!(iso_time("25:00"), None);
|
||||
assert_eq!(iso_datetime("2024-03-05T00:00:00.000").as_deref(), Some("2024-03-05"));
|
||||
assert_eq!(iso_datetime("2024-03-05T13:45:30+02:00").as_deref(), Some("2024-03-05 13:45:30"));
|
||||
assert_eq!(iso_datetime("2024-13-05"), None);
|
||||
assert_eq!(iso_datetime("2023-02-29"), None);
|
||||
assert_eq!(iso_datetime("2024-03-05junk"), None);
|
||||
assert_eq!(iso_datetime("2024-03-05T13:99"), None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -152,7 +152,7 @@ pub(crate) fn add(ctx: &mut Ctx, lay: &mut DocLayout) {
|
||||
author_name(&cm.author),
|
||||
CharProps { bold: Some(true), size: Some(9.0), color: Some(TextColor::Rgb(color)), ..Default::default() },
|
||||
);
|
||||
let pl = ctx.para_labelled(&head, inner, None, &[], None);
|
||||
let pl = ctx.para_labelled(&head, inner, None, &[], 0.0, None);
|
||||
let lead = pl.lines.first().map_or(0.0, |l| l.top.max(0.0));
|
||||
push_para(&mut items, (story, &[HEADER_PATH]), &pl, (0, pl.lines.len()), (x, y + lead), inner, Edges::own(&pl, 0, pl.lines.len()));
|
||||
y += pl.height + 2.0;
|
||||
|
||||
+19
-10
@@ -276,17 +276,17 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
|
||||
Block::Para(p) => {
|
||||
// A paragraph after one whose mark is hidden goes on from that one's last line
|
||||
// (Word, #3986; see `Joint`); one that shows nothing passes the place on.
|
||||
let (mark_hidden, shows_nothing, taken) = Joint::arrive(ctx, &mut joint, (i, p), (width, frames), table);
|
||||
let (mark_hidden, shows_nothing, taken) = Joint::arrive(ctx, &mut joint, (i, p), (width, frames), table, cell_frame);
|
||||
let p = taken.as_ref().map_or(p, |t| &t.para);
|
||||
let label = ctx.next_label(p);
|
||||
let listed = label.is_some();
|
||||
let mut pl = ctx.para_labelled(p, width, table, &[], label.clone());
|
||||
let mut pl = ctx.para_labelled(p, width, table, &[], 0.0, label.clone());
|
||||
// A text frame (a footer's page number in a frame, say) is placed apart, like a
|
||||
// floating object, and the text after it wraps around it; it takes no room in
|
||||
// the flow.
|
||||
if let Some(fr) = pl.rp.frame.clone().filter(|fr| frames && cell_frame(fr)) {
|
||||
let fw = fr.w.unwrap_or_else(|| natural_width(&pl)).clamp(1.0, 1584.0);
|
||||
let pf = if (fw - width).abs() > 0.01 { ctx.para_labelled(p, fw, table, &[], label) } else { pl };
|
||||
let pf = if (fw - width).abs() > 0.01 { ctx.para_labelled(p, fw, table, &[], 0.0, label) } else { pl };
|
||||
let h = match fr.h {
|
||||
Some(h) if fr.h_exact => h,
|
||||
Some(h) => h.max(pf.height),
|
||||
@@ -318,7 +318,8 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
|
||||
// body path. Keep text and wrap exclusions relative to the text's actual top.
|
||||
// A paragraph going on from a shared line has its origin at that line's top.
|
||||
let para_top = taken.as_ref().map_or(y, |t| t.joint.top);
|
||||
y += if i == 0 { before } else { before.max(0.0) };
|
||||
let applied = if i == 0 { before } else { before.max(0.0) };
|
||||
y += applied;
|
||||
TakenUp::start(taken.as_ref(), &mut y, &mut excl);
|
||||
// Floating objects anchored here: place them, then wrap the text around them.
|
||||
// One left out of the layout (hidden, or deleted in the final text) takes no room.
|
||||
@@ -364,7 +365,7 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
|
||||
}
|
||||
let rel = rel_exclusions(&excl, 0.0, y);
|
||||
if !rel.is_empty() {
|
||||
pl = ctx.para_labelled(p, width, table, &rel, label);
|
||||
pl = ctx.para_labelled(p, width, table, &rel, applied, label);
|
||||
}
|
||||
TakenUp::clear(taken.as_ref(), &mut excl);
|
||||
// Bordered paragraphs: room for their borders, those of a group joined in one box.
|
||||
@@ -477,7 +478,7 @@ fn natural_width(pl: &ParaLayout) -> f32 {
|
||||
}
|
||||
|
||||
/// A text frame's placement as a floating object's (`w:framePr` → anchors, alignment, wrap).
|
||||
fn frame_float(fr: &wordcraft_doc::props::TextFrame) -> Float {
|
||||
pub(crate) fn frame_float(fr: &wordcraft_doc::props::TextFrame) -> Float {
|
||||
let anchor = |a: &str, text: Anchor| match a {
|
||||
"page" => Anchor::Page,
|
||||
"margin" => Anchor::Margin,
|
||||
@@ -777,13 +778,14 @@ impl Joint {
|
||||
(i, p): (usize, &Paragraph),
|
||||
(width, frames): (f32, bool),
|
||||
table: Option<¶::CellText>,
|
||||
cell_frame: impl Fn(&wordcraft_doc::props::TextFrame) -> bool,
|
||||
) -> (bool, bool, Option<TakenUp>) {
|
||||
let chr = table.map(|t| &t.chr);
|
||||
let mark_hidden = ctx.mark_hidden(p, chr);
|
||||
let shows_nothing = mark_hidden && ctx.text_hidden(p, chr);
|
||||
let came = joint.take().filter(|j| j.next == i);
|
||||
*joint = came.filter(|_| shows_nothing).map(|j| Joint { next: i + 1, ..j });
|
||||
let taken = came.filter(|_| !shows_nothing).and_then(|j| j.take_up(ctx, p, (width, frames), table));
|
||||
let taken = came.filter(|_| !shows_nothing).and_then(|j| j.take_up(ctx, p, (width, frames), table, cell_frame));
|
||||
(mark_hidden, shows_nothing, taken)
|
||||
}
|
||||
|
||||
@@ -799,7 +801,7 @@ impl Joint {
|
||||
/// taller than the text going on from it), with the room for its bottom border (Word).
|
||||
pub(crate) fn fit(&self, ctx: &mut Ctx, q: &Paragraph, width: f32, table: Option<¶::CellText>) -> (f32, Vec<WrapArea>) {
|
||||
let eq = ctx.eq_count;
|
||||
let probe = again(ctx, eq, |ctx| ctx.para_labelled(q, width, table, &[], None));
|
||||
let probe = again(ctx, eq, |ctx| ctx.para_labelled(q, width, table, &[], 0.0, None));
|
||||
let (gap, height) = probe.lines.first().map_or((0.0, self.height), |l| ((self.baseline - (l.baseline - l.top)).max(0.0), l.height));
|
||||
let rect = Rect::new(self.left, self.top, (self.end - self.left).max(0.0), (gap + height - 0.01).max(0.01));
|
||||
let mut areas = vec![(rect, false, None, WrapText::Right, false)];
|
||||
@@ -827,9 +829,16 @@ impl Joint {
|
||||
/// Paragraph `p` of a box `width` wide going on from here, unless a page break comes before
|
||||
/// it, it runs right to left or it is a text frame (`frames`: placed apart, sharing no line):
|
||||
/// without its space before, as [`Joint::fit`] lays it out.
|
||||
fn take_up(self, ctx: &mut Ctx, p: &Paragraph, (width, frames): (f32, bool), table: Option<¶::CellText>) -> Option<TakenUp> {
|
||||
fn take_up(
|
||||
self,
|
||||
ctx: &mut Ctx,
|
||||
p: &Paragraph,
|
||||
(width, frames): (f32, bool),
|
||||
table: Option<¶::CellText>,
|
||||
cell_frame: impl Fn(&wordcraft_doc::props::TextFrame) -> bool,
|
||||
) -> Option<TakenUp> {
|
||||
let own = ctx.doc.styles.resolve_para_in(&p.props, table.map(|t| &t.para));
|
||||
if own.page_break_before || own.bidi || (frames && own.frame.is_some()) {
|
||||
if own.page_break_before || own.bidi || own.frame.as_ref().is_some_and(|fr| frames && cell_frame(fr)) {
|
||||
return None;
|
||||
}
|
||||
let mut para = p.clone();
|
||||
|
||||
@@ -16,6 +16,9 @@ pub(crate) struct Key {
|
||||
pub(crate) table: u64,
|
||||
pub(crate) notes: u64,
|
||||
pub(crate) excl: u64,
|
||||
/// The space before the paragraph layout applied above it, which a Top-and-Bottom object in
|
||||
/// it is laid out again below ([`para::ParaEnv::space_before`]).
|
||||
pub(crate) space_before: u32,
|
||||
pub(crate) eq: u32,
|
||||
pub(crate) read_spacing: Option<u32>,
|
||||
pub(crate) grid: (u32, u32, u32, bool),
|
||||
@@ -149,6 +152,8 @@ pub(crate) fn env_hash(doc: &Document, cache: &mut LayoutCache, opts: &LayoutOpt
|
||||
let outline = (opts.view == ViewMode::Outline).then(|| opts.outline.as_ref().is_some_and(|o| o.plain));
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
styles.hash(&mut h);
|
||||
// The compatibility mode changes paragraph layout too (widow control in table cells).
|
||||
doc.settings.compat_mode.hash(&mut h);
|
||||
opts.show_hidden.hash(&mut h);
|
||||
opts.hide_deleted.hash(&mut h);
|
||||
opts.hide_marked.hash(&mut h);
|
||||
|
||||
@@ -113,12 +113,21 @@ struct ParaEnvInput<'a> {
|
||||
label: Option<(String, Level)>,
|
||||
table: Option<&'a para::CellText>,
|
||||
exclusions: &'a [para::Exclusion],
|
||||
space_before: f32,
|
||||
eq_number: u32,
|
||||
typing_word: Option<(usize, usize)>,
|
||||
fitted: &'a [(usize, f32)],
|
||||
joined: bool,
|
||||
}
|
||||
|
||||
/// The flow's wrap context for a paragraph's layout, as its cache key needs it: the areas text
|
||||
/// flows around (relative to its first line) and the space before it the flow laid out, which
|
||||
/// reaches up to them (see [`para::ParaEnv::space_before`]).
|
||||
struct WrapAreas<'a> {
|
||||
exclusions: &'a [para::Exclusion],
|
||||
space_before: f32,
|
||||
}
|
||||
|
||||
/// A header or footer (`story`) laid out for page `number` of a section (`sect`, `mirror`): its
|
||||
/// table cells' floats placed on the page rather than in their cell ([`Float::outside_cell`],
|
||||
/// Word's picture watermark in a header that starts with a table), drawn behind the header's
|
||||
@@ -252,6 +261,7 @@ impl Ctx<'_> {
|
||||
typing_word: None,
|
||||
numeral: self.opts.numeral,
|
||||
exclusions: &[],
|
||||
space_before: 0.0,
|
||||
eq_number: 0,
|
||||
read_line_spacing: None,
|
||||
grid: para::Grid::default(),
|
||||
@@ -299,16 +309,18 @@ impl Ctx<'_> {
|
||||
|
||||
/// Lay out `p` with its already counted `label`, so laying a paragraph out again (around
|
||||
/// floating objects, or after it moved) doesn't advance the list counters twice.
|
||||
/// `space_before` is the space before `p` that the flow laid out above it ([`para::ParaEnv`]).
|
||||
pub(crate) fn para_labelled(
|
||||
&mut self,
|
||||
p: &Paragraph,
|
||||
width: f32,
|
||||
table: Option<¶::CellText>,
|
||||
exclusions: &[para::Exclusion],
|
||||
space_before: f32,
|
||||
label: Option<(String, Level)>,
|
||||
) -> Arc<ParaLayout> {
|
||||
let fitted = self.fitted_boxes(p);
|
||||
let (key, eq_number) = self.para_key(p, width, table, exclusions, label.as_ref(), &fitted);
|
||||
let (key, eq_number) = self.para_key(p, width, table, WrapAreas { exclusions, space_before }, label.as_ref(), &fitted);
|
||||
self.cache.used.insert(key.clone());
|
||||
if let Some(pl) = self.cache.paras.get(&key) {
|
||||
self.cache.hits += 1;
|
||||
@@ -323,6 +335,7 @@ impl Ctx<'_> {
|
||||
label,
|
||||
table,
|
||||
exclusions,
|
||||
space_before,
|
||||
eq_number,
|
||||
typing_word: typing,
|
||||
fitted: &fitted,
|
||||
@@ -347,7 +360,7 @@ impl Ctx<'_> {
|
||||
return None;
|
||||
}
|
||||
let kept = (self.eq_count, self.uses_totals);
|
||||
let (key, eq_number) = self.para_key(p, width, None, &[], label.as_ref(), &[]);
|
||||
let (key, eq_number) = self.para_key(p, width, None, WrapAreas { exclusions: &[], space_before: 0.0 }, label.as_ref(), &[]);
|
||||
(self.eq_count, self.uses_totals) = kept;
|
||||
if key.typing.is_some() {
|
||||
return None;
|
||||
@@ -365,6 +378,7 @@ impl Ctx<'_> {
|
||||
label,
|
||||
table: None,
|
||||
exclusions: &[],
|
||||
space_before: 0.0,
|
||||
eq_number,
|
||||
typing_word: None,
|
||||
fitted: &[],
|
||||
@@ -387,7 +401,7 @@ impl Ctx<'_> {
|
||||
measure: impl FnOnce(&ParaLayout) -> (f32, f32),
|
||||
) -> (f32, f32) {
|
||||
let fitted = self.fitted_boxes(p);
|
||||
let (key, eq_number) = self.para_key(p, width, table, &[], label.as_ref(), &fitted);
|
||||
let (key, eq_number) = self.para_key(p, width, table, WrapAreas { exclusions: &[], space_before: 0.0 }, label.as_ref(), &fitted);
|
||||
self.cache.used.insert(key.clone());
|
||||
if let Some(m) = self.cache.measures.get(&key) {
|
||||
self.cache.hits += 1;
|
||||
@@ -402,6 +416,7 @@ impl Ctx<'_> {
|
||||
label,
|
||||
table,
|
||||
exclusions: &[],
|
||||
space_before: 0.0,
|
||||
eq_number,
|
||||
typing_word: typing,
|
||||
fitted: &fitted,
|
||||
@@ -455,10 +470,11 @@ impl Ctx<'_> {
|
||||
p: &Paragraph,
|
||||
width: f32,
|
||||
table: Option<¶::CellText>,
|
||||
exclusions: &[para::Exclusion],
|
||||
wrap: WrapAreas<'_>,
|
||||
label: Option<&(String, Level)>,
|
||||
fitted: &[(usize, f32)],
|
||||
) -> (Key, u32) {
|
||||
let WrapAreas { exclusions, space_before } = wrap;
|
||||
let page = if has_page_fields(p) { Some(self.fields.page_key()) } else { None };
|
||||
if self.track_totals && !self.uses_totals && has_total_fields(p) {
|
||||
self.uses_totals = true;
|
||||
@@ -483,6 +499,7 @@ impl Ctx<'_> {
|
||||
table: table.map(|t| self.table_key(t)).unwrap_or(0),
|
||||
notes: if p.objects.iter().any(|o| matches!(o, InlineObject::NoteRef { .. })) { self.notes_hash } else { 0 },
|
||||
excl: if exclusions.is_empty() { 0 } else { hash_of(&format!("{exclusions:?}")) },
|
||||
space_before: space_before.to_bits(),
|
||||
eq: if eq_here > 0 { eq_number } else { 0 },
|
||||
read_spacing: if self.opts.view == ViewMode::Read { self.opts.read_line_spacing.map(f32::to_bits) } else { None },
|
||||
grid: self.grid.key(),
|
||||
@@ -512,7 +529,7 @@ impl Ctx<'_> {
|
||||
}
|
||||
|
||||
fn para_env<'b>(&'b self, input: ParaEnvInput<'b>) -> para::ParaEnv<'b> {
|
||||
let ParaEnvInput { width, label, table, exclusions, eq_number, typing_word, fitted, joined } = input;
|
||||
let ParaEnvInput { width, label, table, exclusions, space_before, eq_number, typing_word, fitted, joined } = input;
|
||||
para::ParaEnv {
|
||||
doc: self.doc,
|
||||
width,
|
||||
@@ -526,6 +543,7 @@ impl Ctx<'_> {
|
||||
typing_word,
|
||||
numeral: self.opts.numeral,
|
||||
exclusions,
|
||||
space_before,
|
||||
eq_number,
|
||||
read_line_spacing: if self.opts.view == ViewMode::Read { self.opts.read_line_spacing } else { None },
|
||||
grid: self.grid,
|
||||
|
||||
@@ -232,7 +232,10 @@ pub(crate) fn rel_exclusions(excl: &[WrapArea], x0: f32, y0: f32) -> Vec<para::E
|
||||
side: *side,
|
||||
table: *table,
|
||||
})
|
||||
.filter(|e| e.bottom > 0.0)
|
||||
// Top-and-Bottom areas above the first line can still take room: they sit in the
|
||||
// paragraph's space before, which Word lays out again below them (#7143). Side-wrapping
|
||||
// areas there are above the text and take no room, as before.
|
||||
.filter(|e| e.bottom > 0.0 || e.top_bottom)
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -526,7 +529,7 @@ fn anchor_floats_but(
|
||||
}
|
||||
}
|
||||
let rel = rel_exclusions(&body_wraps(ctx, pb), col_x, y0);
|
||||
let pl = ctx.para_labelled(p, width, None, &rel, label.clone());
|
||||
let pl = ctx.para_labelled(p, width, None, &rel, before, label.clone());
|
||||
(rects, pl, rel)
|
||||
}
|
||||
|
||||
|
||||
+81
-20
@@ -1,9 +1,9 @@
|
||||
use super::boxes::{BoxInput, BoxLayout, Edges, Joint, joined, layout_box, push_para};
|
||||
use super::boxes::{BoxInput, BoxLayout, Edges, Joint, frame_float, joined, layout_box, push_para};
|
||||
use super::cache::has_page_number_fields;
|
||||
use super::ctx::{Ctx, Joining};
|
||||
use super::floats::{
|
||||
FloatAnchor, LateFloats, ObjFrame, ObjectPlacement, anchor_floats, body_wraps, continued_exclusions, fitting, late_floats, place_late,
|
||||
place_objects,
|
||||
FloatAnchor, LateFloats, ObjFrame, ObjectPlacement, anchor_floats, body_wraps, continued_exclusions, fitting, float_rect, late_floats,
|
||||
place_late, place_objects, wrap_area,
|
||||
};
|
||||
use super::notes::{DECOR_STORY, NoteBox, para_notes};
|
||||
use super::page::{PageBuilder, PageFrame, item_bottom};
|
||||
@@ -19,6 +19,9 @@ use crate::WRAP_RELAYS;
|
||||
/// A body paragraph. One after a paragraph whose mark is hidden goes on from that one's last line,
|
||||
/// as Word shows them, on one line (#3986): see [`Joint`].
|
||||
pub(crate) fn place_para(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block: usize, body_top: f32) {
|
||||
if place_page_text_frame(ctx, pb, p, block) {
|
||||
return;
|
||||
}
|
||||
let joint = pb.joint.take().filter(|j| !pb.web && j.next == block && j.page == pb.pages.len() && j.col == pb.col);
|
||||
let mark_hidden = ctx.mark_hidden(p, None);
|
||||
// Nothing of it is shown: the place passes on to the paragraph after it.
|
||||
@@ -96,6 +99,39 @@ fn unjoin(ctx: &mut Ctx, p: &Paragraph) {
|
||||
}
|
||||
}
|
||||
|
||||
fn place_page_text_frame(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block: usize) -> bool {
|
||||
if pb.web {
|
||||
return false;
|
||||
}
|
||||
let Some(fr) = ctx.doc.styles.resolve_para_in(&p.props, None).frame else { return false };
|
||||
if fr.h_anchor != "page" || fr.v_anchor != "page" {
|
||||
return false;
|
||||
}
|
||||
let width = fr.w.unwrap_or_else(|| pb.col_w()).clamp(1.0, 1584.0);
|
||||
let label = ctx.next_label(p);
|
||||
let pl = ctx.para_labelled(p, width, None, &[], 0.0, label);
|
||||
let notes = para_notes(ctx.doc, p, &pl);
|
||||
let mut new_notes = Vec::new();
|
||||
for line in &pl.lines {
|
||||
new_notes.extend(notes_on_line(ctx, pb, line, ¬es, &new_notes));
|
||||
}
|
||||
add_notes(pb, new_notes, ¬es, pl.lines.last().map_or(0, |line| line.c1));
|
||||
let height = fr.h.map_or(pl.height, |h| if fr.h_exact { h } else { h.max(pl.height) });
|
||||
let float = frame_float(&fr);
|
||||
let page = PageFrame { sect: pb.sect, margin_top: None, origin: (0.0, 0.0), number: pb.number, mirror: ctx.mirror };
|
||||
let rect = float_rect(Some(page), (pb.col_x(), pb.col_w()), pb.y, width, height, &float);
|
||||
let path = [block as u32];
|
||||
if let Some(page) = pb.page() {
|
||||
push_para(&mut page.items, (StoryRef::Body, &path), &pl, (0, pl.lines.len()), (rect.x, rect.y), width, Edges::own(&pl, 0, pl.lines.len()));
|
||||
}
|
||||
// The body text after the frame wraps around it as its wrap mode says.
|
||||
if let Some(area) = wrap_area(rect, &float, None) {
|
||||
pb.framed.push(area.0);
|
||||
pb.excl.push(area);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// A closing mark before a continuous section takes no room after content. An otherwise empty
|
||||
/// section starting a new page retains its paragraph line.
|
||||
fn place_para_alone(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block: usize, body_top: f32) {
|
||||
@@ -236,6 +272,10 @@ struct Flow<'a> {
|
||||
label: Option<(String, Level)>,
|
||||
/// Where it was expected to start; floats anchored here are placed again if it starts elsewhere.
|
||||
guess: f32,
|
||||
/// The space before it that its layout (`pl`) was broken with: the declared space before
|
||||
/// until the flow settles what it really lays out, then that, so a later relay keeps a
|
||||
/// Top-and-Bottom object in it pushing the first line to the same place.
|
||||
space_applied: f32,
|
||||
excl_mark: usize,
|
||||
/// Where its automatic equation numbers start: each layout of it again counts from here.
|
||||
eq_start: u32,
|
||||
@@ -269,6 +309,21 @@ struct Flow<'a> {
|
||||
}
|
||||
|
||||
impl<'a> Flow<'a> {
|
||||
/// [`PageBuilder::fresh`] for this paragraph's text, which its negative indents take past the
|
||||
/// column's edges: the first line's indent while it is still to place, the other lines'
|
||||
/// indent while lines after the first are, on the physical sides the paragraph's direction
|
||||
/// puts them.
|
||||
fn fresh(&self, pb: &PageBuilder) -> bool {
|
||||
let rp = &self.pl.rp;
|
||||
let first = rp.indent_left + rp.indent_first;
|
||||
let leading = match (self.l0 == 0, self.pl.lines.len() > 1) {
|
||||
(true, true) => rp.indent_left.min(first),
|
||||
(true, false) => first,
|
||||
(false, _) => rp.indent_left,
|
||||
};
|
||||
let (leading, trailing) = ((-leading).max(0.0), (-rp.indent_right).max(0.0));
|
||||
pb.fresh(if rp.bidi { (trailing, leading) } else { (leading, trailing) })
|
||||
}
|
||||
fn new(ctx: &mut Ctx, pb: &mut PageBuilder, p: &'a Paragraph, (block, body_top): (usize, f32)) -> Self {
|
||||
let width = pb.col_w();
|
||||
// Floating objects anchored here join the page's wrap areas before the text is laid out; if
|
||||
@@ -288,6 +343,7 @@ impl<'a> Flow<'a> {
|
||||
width,
|
||||
label,
|
||||
guess,
|
||||
space_applied: space_before,
|
||||
excl_mark,
|
||||
eq_start,
|
||||
float_rects,
|
||||
@@ -324,13 +380,14 @@ impl<'a> Flow<'a> {
|
||||
});
|
||||
(self.float_rects, self.pl, self.rel) = (rects, pl, rel);
|
||||
self.late = LateFloats::new(&late);
|
||||
self.space_applied = before;
|
||||
(self.laid_page, self.laid_width) = (pb.number, pb.col_w());
|
||||
}
|
||||
|
||||
/// Lay the paragraph out again around the wrap areas `rel`, with its fields on their pages.
|
||||
fn relay(&mut self, ctx: &mut Ctx, rel: &[para::Exclusion]) -> Arc<ParaLayout> {
|
||||
let (p, width, eq_start, label) = (self.p, self.laid_width, self.eq_start, &self.label);
|
||||
with_page_map(ctx, &mut self.page_map, |ctx| again(ctx, eq_start, |ctx| ctx.para_labelled(p, width, None, rel, label.clone())))
|
||||
let (p, width, eq_start, label, space_before) = (self.p, self.laid_width, self.eq_start, &self.label, self.space_applied);
|
||||
with_page_map(ctx, &mut self.page_map, |ctx| again(ctx, eq_start, |ctx| ctx.para_labelled(p, width, None, rel, space_before, label.clone())))
|
||||
}
|
||||
|
||||
/// The space before the paragraph, after the one between it and the previous paragraph is
|
||||
@@ -367,7 +424,7 @@ impl<'a> Flow<'a> {
|
||||
// space before (Word's PDFs: 0 pt and 12 pt before put the text after it at the same place).
|
||||
// Only that shape is observed: later pages and columns keep theirs.
|
||||
if self.block == 1
|
||||
&& pb.fresh()
|
||||
&& self.fresh(pb)
|
||||
&& !pb.web
|
||||
&& pb.pages.last().is_some_and(|pg| pg.float_tables.contains(&Path::top(0)))
|
||||
&& only_markers(self.p, 0..self.p.text.len())
|
||||
@@ -444,7 +501,7 @@ impl<'a> Flow<'a> {
|
||||
// (Against the whole column: balanced columns grow to hold it.)
|
||||
// With the 0.01 pt of slack the other fit checks take. Balancing from Word 2013's layout
|
||||
// keeps the lines and the next paragraph together at the top of a column too (#6821).
|
||||
if pb.y + need > pb.bottom + 0.01 && (!pb.fresh() || Self::strict_widow_control(ctx, pb)) && need <= pb.next_room(self.body_top) {
|
||||
if pb.y + need > pb.bottom + 0.01 && (!self.fresh(pb) || Self::strict_widow_control(ctx, pb)) && need <= pb.next_room(self.body_top) {
|
||||
pb.advance(self.block, self.body_top);
|
||||
unjoin(ctx, self.p);
|
||||
pb.y += rp.space_before.min(0.0);
|
||||
@@ -458,7 +515,7 @@ impl<'a> Flow<'a> {
|
||||
/// paragraph, together there too: asks again, and places the paragraph's floats again where it
|
||||
/// ends up (#6821).
|
||||
fn keep_again(&mut self, ctx: &mut Ctx, pb: &mut PageBuilder, rooms: Rooms) {
|
||||
while self.l0 == 0 && (self.pl.rp.keep_lines || self.pl.rp.keep_next) && pb.fresh() && Self::strict_widow_control(ctx, pb) {
|
||||
while self.l0 == 0 && (self.pl.rp.keep_lines || self.pl.rp.keep_next) && self.fresh(pb) && Self::strict_widow_control(ctx, pb) {
|
||||
let (col, pages) = (pb.col, pb.pages.len());
|
||||
let before = self.keep_together(ctx, pb, rooms, 0.0);
|
||||
if (pb.col, pb.pages.len()) == (col, pages) {
|
||||
@@ -550,7 +607,7 @@ impl<'a> Flow<'a> {
|
||||
if over && fit.l1 > l0 && !split {
|
||||
break;
|
||||
}
|
||||
if over && fit.l1 == l0 && !pb.fresh() && !split && !self.stays_at_bottom(pb, l) {
|
||||
if over && fit.l1 == l0 && !self.fresh(pb) && !split && !self.stays_at_bottom(pb, l) {
|
||||
break;
|
||||
}
|
||||
fit.notes.extend(line_notes);
|
||||
@@ -608,11 +665,11 @@ impl<'a> Flow<'a> {
|
||||
// one (#6821).
|
||||
let strict = Self::strict_widow_control(ctx, pb);
|
||||
if fit.forced.is_none() && l1 < n && self.pl.rp.widow_control && n >= 2 {
|
||||
if l1 - l0 == 1 && l0 == 0 && (!pb.fresh() || strict) {
|
||||
if l1 - l0 == 1 && l0 == 0 && (!self.fresh(pb) || strict) {
|
||||
l1 = l0; // orphan: move the first line to the next page
|
||||
} else if n - l1 == 1 && (l1 - l0 >= 3 || (l0 > 0 && l1 - l0 >= 2)) {
|
||||
l1 -= 1; // widow: take one more line along
|
||||
} else if n - l1 == 1 && l0 == 0 && l1 - l0 == 2 && (!pb.fresh() || strict) {
|
||||
} else if n - l1 == 1 && l0 == 0 && l1 - l0 == 2 && (!self.fresh(pb) || strict) {
|
||||
// Neither split of a three-line paragraph is allowed (two and a widow, or an
|
||||
// orphan and two): it moves whole, as in Word.
|
||||
l1 = l0;
|
||||
@@ -776,6 +833,7 @@ impl<'a> Flow<'a> {
|
||||
(self.float_rects, self.pl, self.rel) = (rects, relaid, relaid_rel);
|
||||
(self.laid_page, self.laid_width) = (pb.number, pb.col_w());
|
||||
self.anchor_y = y0;
|
||||
self.space_applied = 0.0;
|
||||
self.l0 = k;
|
||||
}
|
||||
}
|
||||
@@ -890,10 +948,10 @@ fn notes_limit(pb: &PageBuilder, new_notes: &[NoteBox], line_notes: &[NoteBox])
|
||||
/// the text (see `baseline_offset`), and Word lets that leading of a page's last line run into the
|
||||
/// bottom margin: only the text has to fit (observed: a double-spaced 12pt line stays on the page
|
||||
/// while its text ends above the margin, about half a line lower than when the whole line must
|
||||
/// fit). Only the bottom margin takes that leading: a footer taller than the margin, or
|
||||
/// footnotes (`free` is false), keep the whole line clear of them.
|
||||
/// fit). Only the bottom margin takes that leading, or the top of a footer that reaches above it
|
||||
/// (see [`PageBuilder::at_margin`]): footnotes (`free` is false) keep the whole line clear of them.
|
||||
fn fit_height(pb: &PageBuilder, l: ¶::Line, rp: &wordcraft_doc::resolve::ResolvedPara, free: bool) -> f32 {
|
||||
let at_margin = pb.bottom >= pb.sect.page_h - pb.sect.margin_bottom - 0.01;
|
||||
let at_margin = pb.at_margin();
|
||||
match rp.line_spacing {
|
||||
// The text (or a taller picture) ends `leading` above the line's bottom.
|
||||
wordcraft_doc::props::LineSpacing::Multiple(m) if m > 1.0 && at_margin && free => (l.height - l.leading).clamp(0.0, l.height),
|
||||
@@ -989,8 +1047,10 @@ fn place_para_in_flow(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block:
|
||||
let mut f = Flow::new(ctx, pb, p, (block, body_top));
|
||||
let spot = |pb: &PageBuilder| (pb.pages.len(), pb.col);
|
||||
let placed_at = spot(pb);
|
||||
// A continuous section's top mid-page is not a page top, so the break still applies.
|
||||
let broke_before = f.pl.rp.page_break_before && !pb.fresh() && !pb.web;
|
||||
// A continuous section's top mid-page is not a page top, so the break still applies. A
|
||||
// page-anchored frame is not content above the paragraph, so it does not make the break
|
||||
// apply either: the frame's wrap area moves the text below or beside it (#8577).
|
||||
let broke_before = f.pl.rp.page_break_before && !pb.at_page_top() && !pb.web;
|
||||
if broke_before {
|
||||
pb.new_page(block, body_top);
|
||||
}
|
||||
@@ -1023,7 +1083,7 @@ fn place_para_in_flow(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block:
|
||||
fit.l1 = end;
|
||||
// On a fresh column an unfitting line can overflow. Strict widow control instead moves
|
||||
// the lines on without emitting anything and must release their late floats as well.
|
||||
let overflow = end == f.l0 && pb.fresh() && !widowed;
|
||||
let overflow = end == f.l0 && f.fresh(pb) && !widowed;
|
||||
if f.settle_late(pb, end, overflow) {
|
||||
continue;
|
||||
}
|
||||
@@ -1085,7 +1145,7 @@ pub(crate) fn place_outline_para(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragr
|
||||
let width = (pb.col_w() - indent - outline::SYMBOL_W).max(72.0);
|
||||
let q = outline::outline_para(ctx.doc, p, o.view.plain);
|
||||
ctx.fields.page = pb.number;
|
||||
let pl = ctx.para_labelled(&q, width, None, &[], label);
|
||||
let pl = ctx.para_labelled(&q, width, None, &[], 0.0, label);
|
||||
pb.y += pl.rp.space_before.max(0.0);
|
||||
let n = pl.lines.len();
|
||||
let l1 = if o.view.first_line_only && level >= outline::BODY { n.min(1) } else { n };
|
||||
@@ -1197,6 +1257,7 @@ fn next_first_line(ctx: &mut Ctx, block: usize, width: f32, depth: usize, new_pa
|
||||
typing_word: None,
|
||||
numeral: ctx.opts.numeral,
|
||||
exclusions: &[],
|
||||
space_before: 0.0,
|
||||
eq_number: ctx.eq_count,
|
||||
read_line_spacing: if ctx.opts.view == ViewMode::Read { ctx.opts.read_line_spacing } else { None },
|
||||
grid: ctx.grid,
|
||||
@@ -1311,7 +1372,7 @@ mod tests {
|
||||
// Continue after the first line. The balance attempt can fit only one of the two lines left.
|
||||
flow.l0 = 1;
|
||||
pb.advance(0, top);
|
||||
assert!(pb.fresh());
|
||||
assert!(flow.fresh(pb));
|
||||
assert!((pb.bottom - pb.top - height).abs() < 0.01);
|
||||
flow.place_due_late(ctx, pb);
|
||||
assert_eq!(pb.excl.len(), 1, "the anchor line fits before widow control");
|
||||
@@ -1320,7 +1381,7 @@ mod tests {
|
||||
assert_eq!(fit.l1, 2);
|
||||
let (end, widowed) = flow.settled_end(ctx, pb, &fit);
|
||||
assert_eq!((end, widowed), (1, true));
|
||||
let overflow = end == flow.l0 && pb.fresh() && !widowed;
|
||||
let overflow = end == flow.l0 && flow.fresh(pb) && !widowed;
|
||||
assert!(!flow.settle_late(pb, end, overflow));
|
||||
assert!(pb.excl.is_empty(), "no text is emitted here, so no wrap area may remain here");
|
||||
});
|
||||
|
||||
@@ -36,6 +36,27 @@ pub(crate) fn section_side(start: SectionStart, restart: Option<u32>, last: u32,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `page` (after `prev`) is its section's first page, the one a different first page's
|
||||
/// header and footer go on: the page where the section begins. A page's section is the one at its
|
||||
/// top, so a section that starts continuously part-way down `prev` has no first page of its own:
|
||||
/// Word shows the earlier section's header there and the section's default one from the next page
|
||||
/// on, also when its first paragraph begins on `prev` and runs over. `sections` as
|
||||
/// [`Document::sections`] gives them (each with its last block).
|
||||
pub(crate) fn begins_section(sections: &[(usize, &SectionProps)], prev: Option<&Page>, page: &Page) -> bool {
|
||||
if prev.is_some_and(|p| p.section == page.section) {
|
||||
return false;
|
||||
}
|
||||
let start = page.section.checked_sub(1).and_then(|k| sections.get(k)).map_or(0, |(end, _)| end.saturating_add(1));
|
||||
// A first paragraph (or table) that begins part-way down `prev` and runs over still began
|
||||
// the section there.
|
||||
let began_before = prev.is_some_and(|p| {
|
||||
p.items
|
||||
.iter()
|
||||
.any(|it| matches!(it, Placed::Lines { story: StoryRef::Body, path, .. } if path.0.first().is_some_and(|&b| b as usize >= start)))
|
||||
});
|
||||
start >= page.first_block && !began_before
|
||||
}
|
||||
|
||||
/// The document's sections with their headers and footers (Word's "link to previous"), each
|
||||
/// section's resolved once for the whole layout in document order rather than by looking back
|
||||
/// over the sections before it whenever one is needed.
|
||||
@@ -174,12 +195,12 @@ pub(crate) fn header_table_areas(ctx: &mut Ctx, pb: &PageBuilder) -> Vec<Rect> {
|
||||
return Vec::new();
|
||||
}
|
||||
let Some(page) = pb.pages.last() else { return Vec::new() };
|
||||
let first = pb.pages.iter().rev().nth(1).is_none_or(|prev| prev.section != page.section);
|
||||
let hf = Arc::clone(&ctx.hf);
|
||||
let first = begins_section(&hf.sections, pb.pages.iter().rev().nth(1), page);
|
||||
let key = (page.section, page.number, first);
|
||||
if let Some(areas) = ctx.header_tables.get(&key) {
|
||||
return areas.clone();
|
||||
}
|
||||
let hf = Arc::clone(&ctx.hf);
|
||||
let Some((_, sect)) = hf.sections.get(page.section) else { return Vec::new() };
|
||||
if sect.text_direction.is_turned() {
|
||||
return Vec::new();
|
||||
@@ -405,13 +426,9 @@ pub(crate) fn headers_footers(ctx: &mut Ctx, pages: &mut [Page], sections: &[(us
|
||||
let hf = Arc::clone(&ctx.hf);
|
||||
let even_odd = ctx.doc.settings.even_odd_headers;
|
||||
let styles = styleref::headers_use_styleref(ctx.doc).then(|| ctx.cache.style_index(ctx.doc));
|
||||
let mut first_of_section: HashSet<usize> = HashSet::new();
|
||||
let mut seen = HashSet::new();
|
||||
for (i, p) in pages.iter().enumerate() {
|
||||
if seen.insert(p.section) {
|
||||
first_of_section.insert(i);
|
||||
}
|
||||
}
|
||||
let first_of_section: HashSet<usize> = (0..pages.len())
|
||||
.filter(|&i| pages.get(i).is_some_and(|p| begins_section(sections, i.checked_sub(1).and_then(|k| pages.get(k)), p)))
|
||||
.collect();
|
||||
for (i, page) in pages.iter_mut().enumerate() {
|
||||
let Some((_, sect)) = sections.get(page.section) else { continue };
|
||||
// Inherit header/footer references from earlier sections (Word's "link to previous").
|
||||
|
||||
@@ -210,10 +210,31 @@ impl NoteBox {
|
||||
cuts
|
||||
}
|
||||
|
||||
/// The least of the note that must stay with its reference: its first line (all of it if it
|
||||
/// can't be split).
|
||||
/// Whether widow/orphan control in the note's paragraphs forbids splitting at `cut`: a
|
||||
/// paragraph's first line alone above it (an orphan) or its last line alone below it (a
|
||||
/// widow), as in Word for Mac 16.114.4.
|
||||
pub(crate) fn breaks_widow_control(&self, cut: f32) -> bool {
|
||||
self.items.iter().filter(|it| self.splittable(it)).any(|it| {
|
||||
let Placed::Lines { para, l0, l1, y, .. } = it else { return false };
|
||||
let Some(first) = para.lines.get(*l0) else { return false };
|
||||
let ends_at = |k: usize| para.lines.get(k).is_some_and(|l| (y + l.top - first.top + l.height - cut).abs() < 0.01);
|
||||
let n = para.lines.len();
|
||||
para.rp.widow_control && n >= 2 && ((*l0 == 0 && *l1 >= 2 && ends_at(0)) || (*l1 == n && ends_at(n - 2)))
|
||||
})
|
||||
}
|
||||
|
||||
/// Where the note may be split with its paragraphs' widow/orphan control kept, ascending.
|
||||
pub(crate) fn kept_cuts(&self) -> Vec<f32> {
|
||||
let mut cuts = self.cuts();
|
||||
cuts.retain(|&c| !self.breaks_widow_control(c));
|
||||
cuts
|
||||
}
|
||||
|
||||
/// The least of the note that must stay with its reference: its first line, or more under
|
||||
/// widow/orphan control (all of it if it can't be split).
|
||||
pub(crate) fn first_piece(&self) -> f32 {
|
||||
self.cuts().first().copied().unwrap_or(self.h).min(self.h)
|
||||
// Widow/orphan control may keep more lines together (two, or a short paragraph whole).
|
||||
self.kept_cuts().first().copied().unwrap_or(self.h).min(self.h)
|
||||
}
|
||||
|
||||
/// Split the note at line bottom `cut`: the part above (`cut` tall) and the rest, moved up to
|
||||
|
||||
@@ -89,10 +89,16 @@ pub(crate) struct PageBuilder<'a> {
|
||||
/// Top of the footer of the pages being started: a footer reaching above the bottom margin
|
||||
/// pushes the body up (`f32::MAX`: no footer).
|
||||
pub(crate) foot_top: f32,
|
||||
/// How low the last line's leading may reach on the current page: the bottom margin, or the
|
||||
/// top of a footer reaching above it (set as the page starts, from that page's footer).
|
||||
pub(crate) leading_floor: f32,
|
||||
/// The wrap areas pages start with ([`EarlyFloats`]) ...
|
||||
pub(crate) early: &'a EarlyFloats,
|
||||
/// ... and how many of the current page's `excl` they are (its first ones).
|
||||
pub(crate) seeded: usize,
|
||||
/// The wrap areas of the page-anchored body text frames on the current page. Text at the top
|
||||
/// of a column that one of them reaches into gains room by moving on.
|
||||
pub(crate) framed: Vec<Rect>,
|
||||
/// No layout pass follows for floats found above their anchors: each is kept clear of the
|
||||
/// text laid out before it ([`settle_early`]).
|
||||
pub(crate) settle: bool,
|
||||
@@ -160,7 +166,7 @@ impl PageBuilder<'_> {
|
||||
// The note area starts below the text (a page of continued notes alone: at its top).
|
||||
let area = self.bottom.max(self.body_floor());
|
||||
let fits = total <= self.orig_bottom - area + 0.01;
|
||||
let top = match (fits, self.beneath) {
|
||||
let mut top = match (fits, self.beneath) {
|
||||
(false, _) => area,
|
||||
// Below the page's last line of text.
|
||||
(true, true) => self.body_floor().min(self.orig_bottom - total),
|
||||
@@ -173,12 +179,15 @@ impl PageBuilder<'_> {
|
||||
let mut placed = Vec::new();
|
||||
// Where the continuation notice goes, below a note that continues on the next page.
|
||||
let mut notice_y = None;
|
||||
// The bottom of what is placed (with the notice).
|
||||
let mut end = y;
|
||||
let mut rest = notes.into_iter();
|
||||
while let Some(n) = rest.next() {
|
||||
let room = self.orig_bottom - y;
|
||||
if fits || n.h <= room + 0.01 {
|
||||
let ny = y;
|
||||
y += n.h;
|
||||
end = y;
|
||||
placed.push((n, ny));
|
||||
continue;
|
||||
}
|
||||
@@ -186,21 +195,38 @@ impl PageBuilder<'_> {
|
||||
// always leaves something here (its first line, or all of it if it can't be split),
|
||||
// so continuing ends.
|
||||
let first = placed.is_empty();
|
||||
let cuts = n.cuts();
|
||||
// Widow/orphan control in the note keeps two of a paragraph's lines on either side;
|
||||
// the page's first note gives that up before it gives up the page's room.
|
||||
let room = room - self.seps.notice_h();
|
||||
match cuts.iter().rev().find(|&&c| c <= room + 0.01).or(cuts.first().filter(|_| first)).copied() {
|
||||
let fit = |cuts: Vec<f32>| cuts.into_iter().rev().find(|&c| c <= room + 0.01);
|
||||
let cut = fit(n.kept_cuts()).or_else(|| if first { fit(n.cuts()).or(n.cuts().first().copied()) } else { None });
|
||||
match cut {
|
||||
Some(c) => {
|
||||
let (head, tail) = n.split(c);
|
||||
notice_y = Some(y + head.h);
|
||||
end = y + head.h + self.seps.notice_h();
|
||||
placed.push((head, y));
|
||||
self.carry.push(tail);
|
||||
}
|
||||
None if first => placed.push((n, y)),
|
||||
None if first => {
|
||||
end = y + n.h;
|
||||
placed.push((n, y));
|
||||
}
|
||||
None => self.carry.push(n),
|
||||
}
|
||||
self.carry.extend(rest.by_ref());
|
||||
break;
|
||||
}
|
||||
// Notes that continue on the next page still end on the bottom margin, the room left
|
||||
// going above the separator (Word for Mac 16.114.4), unless they go beneath the text.
|
||||
if !fits && !self.beneath {
|
||||
let shift = (self.orig_bottom - end).max(0.0);
|
||||
top += shift;
|
||||
notice_y = notice_y.map(|ny| ny + shift);
|
||||
for (_, ny) in &mut placed {
|
||||
*ny += shift;
|
||||
}
|
||||
}
|
||||
if let Some(pg) = self.pages.last_mut() {
|
||||
match if cont { &self.seps.cont } else { &self.seps.sep } {
|
||||
Some((items, _)) => pg.items.extend(items.iter().cloned().map(|mut it| {
|
||||
@@ -351,6 +377,7 @@ impl PageBuilder<'_> {
|
||||
let early = self.early;
|
||||
self.excl.extend(early.get(&self.pages.len()).into_iter().flatten().map(|(_, _, a)| a.clone()));
|
||||
self.seeded = self.excl.len();
|
||||
self.framed.clear();
|
||||
self.float_tables.clear();
|
||||
if self.sect.line_numbers.as_ref().is_some_and(|l| l.restart == wordcraft_doc::section::LineNumberRestart::Page) {
|
||||
self.line_no = 0;
|
||||
@@ -359,6 +386,7 @@ impl PageBuilder<'_> {
|
||||
self.number = self.restart_at.take().unwrap_or_else(|| self.number.saturating_add(1));
|
||||
let (w, h) = if self.web { (s.page_w, f32::MAX / 4.0) } else { (s.page_w, s.page_h) };
|
||||
let bottom = self.body_bottom(body_top);
|
||||
self.leading_floor = (s.page_h - s.margin_bottom).min(self.foot_top);
|
||||
let body = Rect::new(s.margin_left + s.gutter, body_top, s.text_width(), (bottom - body_top).max(36.0));
|
||||
let mut decor = Vec::new();
|
||||
if !self.web {
|
||||
@@ -437,6 +465,13 @@ impl PageBuilder<'_> {
|
||||
self.bottom = self.bottom.min(self.top + h);
|
||||
}
|
||||
}
|
||||
/// Whether the body ends at the bottom margin, or at the top of a footer that reaches above
|
||||
/// it: the page's last multiple-spaced line may leave its leading there (see `fit_height`).
|
||||
/// Word lets it run past the footer's top as into the margin, whatever the footer holds (a
|
||||
/// page number, several lines of text, an empty paragraph): only the text has to end above it.
|
||||
pub(crate) fn at_margin(&self) -> bool {
|
||||
self.bottom >= self.leading_floor - 0.01
|
||||
}
|
||||
/// The bottom of the body on a page started with its body at `body_top`: a footer taller than
|
||||
/// the bottom margin pushes it up (Word: no gap), leaving it at least a little room.
|
||||
fn body_bottom(&self, body_top: f32) -> f32 {
|
||||
@@ -476,9 +511,22 @@ impl PageBuilder<'_> {
|
||||
/// At the top with nothing above on this page, so moving on gains no room. A continuous
|
||||
/// section starting mid-page is at its top but not fresh: what doesn't fit there goes to the
|
||||
/// next page (#3907).
|
||||
pub(crate) fn fresh(&self) -> bool {
|
||||
/// `reach` is how far the text reaches past the column's left and right edges (a paragraph's
|
||||
/// negative indents).
|
||||
pub(crate) fn fresh(&self, reach: (f32, f32)) -> bool {
|
||||
self.at_page_top() && !self.framed_here(reach)
|
||||
}
|
||||
/// At the top of the page's text with nothing placed above it. A page-anchored frame is not
|
||||
/// content above it: a paragraph with a page break before needs no new page for one.
|
||||
pub(crate) fn at_page_top(&self) -> bool {
|
||||
self.at_top() && self.top <= self.page_top + 0.01
|
||||
}
|
||||
/// A page-anchored body text frame's wrap area reaches into the current column's text,
|
||||
/// widened by `reach` on the left and right.
|
||||
fn framed_here(&self, (left, right): (f32, f32)) -> bool {
|
||||
let (x0, x1) = (self.col_x() - left, self.col_x() + self.col_w() + right);
|
||||
self.framed.iter().any(|r| r.x < x1 && r.right() > x0 && r.y < self.bottom && r.bottom() > self.y)
|
||||
}
|
||||
/// Move to the next column or page.
|
||||
pub(crate) fn advance(&mut self, block: usize, body_top: f32) {
|
||||
if self.col + 1 < self.cols.len() {
|
||||
|
||||
@@ -367,6 +367,7 @@ mod label_spacing_tests {
|
||||
field_codes: false,
|
||||
grid: Grid::default(),
|
||||
exclusions: &[],
|
||||
space_before: 0.0,
|
||||
eq_number: 0,
|
||||
numeral: crate::NumeralMode::default(),
|
||||
read_line_spacing: None,
|
||||
@@ -513,6 +514,7 @@ mod tests {
|
||||
field_codes: false,
|
||||
grid: Grid::default(),
|
||||
exclusions: &[],
|
||||
space_before: 0.0,
|
||||
eq_number: 0,
|
||||
numeral: Default::default(),
|
||||
read_line_spacing: None,
|
||||
|
||||
@@ -5,7 +5,7 @@ use super::chars::{
|
||||
};
|
||||
use super::grid::east_asian;
|
||||
use super::model::{ClKind, Cluster, Enclosed, Glyph, ParaEnv, RubyLayout, StyleRun, SymbolRun};
|
||||
use super::{Arc, Document, FaceRef, NumeralMode, ResolvedChar, RubyAlign, SOFT_HYPHEN};
|
||||
use super::{Arc, Document, FaceRef, NumeralMode, OBJ, ResolvedChar, RubyAlign, SOFT_HYPHEN};
|
||||
use wordcraft_fonts::ShapeContext;
|
||||
|
||||
pub(super) struct Builder<'a> {
|
||||
@@ -52,6 +52,25 @@ struct SegmentInput<'a> {
|
||||
context: &'a [bool],
|
||||
}
|
||||
|
||||
/// Whether `face` draws `cluster`, a character and its combining marks, with no missing glyph.
|
||||
/// The shaper composes a pair the face has a precomposed glyph for (`=` and U+0338 as `≠`), so a
|
||||
/// face without the mark itself can still draw the pair.
|
||||
fn draws_all(face: FaceRef, cluster: &str) -> bool {
|
||||
let glyphs = wordcraft_fonts::shape_in(&face, cluster, &[], |c| c, ShapeContext::default());
|
||||
!glyphs.is_empty() && glyphs.iter().all(|g| g.gid != 0)
|
||||
}
|
||||
|
||||
/// A face other than `current` that draws all of `cluster` (CSS Fonts 4 §5.3, cluster matching):
|
||||
/// the run's Thai face or its own font when one does, else the first face in fallback order with
|
||||
/// every character of it that draws something.
|
||||
fn cluster_face(cluster: &str, current: FaceRef, run_face: Option<FaceRef>, primary: FaceRef, bold: bool, italic: bool) -> Option<FaceRef> {
|
||||
if let Some(f) = run_face.into_iter().chain([primary]).filter(|f| f.id() != current.id()).find(|f| draws_all(*f, cluster)) {
|
||||
return Some(f);
|
||||
}
|
||||
let chars: Vec<char> = cluster.chars().filter(|c| draws_something(*c)).collect();
|
||||
wordcraft_fonts::FontDb::global().fallback_for_run(&chars, primary.id(), bold, italic).map(|f| FaceRef::of(&f))
|
||||
}
|
||||
|
||||
impl<'a> Builder<'a> {
|
||||
/// Displayed form of `c` at run-relative byte `at` (Word › Numeral): one char in, one
|
||||
/// char out. `rtl` is the shaping direction; in Context mode `context` (from
|
||||
@@ -68,6 +87,10 @@ impl<'a> Builder<'a> {
|
||||
let mut seg_start = 0;
|
||||
let mut cur: Option<SegKey> = None;
|
||||
let mut segs = Vec::new();
|
||||
// The character the marks after it belong to: where it starts, and as drawn.
|
||||
let mut base: Option<(usize, char)> = None;
|
||||
// The character whose cluster was matched, and whether its marks stay with it.
|
||||
let mut matched: Option<(usize, bool)> = None;
|
||||
for (i, c) in text.char_indices() {
|
||||
let rtl = use_levels && levels.get(lbase + i).is_some_and(|l| l % 2 == 1);
|
||||
let c = show(c);
|
||||
@@ -78,19 +101,67 @@ impl<'a> Builder<'a> {
|
||||
_ => rc_cs.is_some() && rc.uses_complex(dc),
|
||||
};
|
||||
let primary = if complex { primary_cs.unwrap_or(primary) } else { primary };
|
||||
let face = match cur {
|
||||
Some(k) if mark => k.face,
|
||||
let (bold, italic) = if complex { (rc.bold_cs, rc.italic_cs) } else { (rc.bold, rc.italic) };
|
||||
// A mark stays in the face of the character it belongs to (Arabic harakat with their
|
||||
// letter, so the letters join) while that face draws it. When it doesn't, the
|
||||
// character and its marks go together to a face that draws them all (CSS Fonts 4
|
||||
// §5.3, cluster matching). With no such face, a mark in left-to-right text that isn't
|
||||
// complex script is matched on its own like any other character; in right-to-left or
|
||||
// complex-script text it stays with its letter (#7865). A cluster is matched once, at
|
||||
// its first mark the face lacks: matching it again at every later mark would make a
|
||||
// long run of marks quadratic.
|
||||
let mut with_base = false;
|
||||
let mut moved = None;
|
||||
if let Some(k) = cur.filter(|_| mark) {
|
||||
let current = k.face.unwrap_or(primary);
|
||||
with_base = !draws_something(c) || current.covers(dc);
|
||||
if !with_base {
|
||||
match (base.filter(|(at, _)| *at >= seg_start), matched) {
|
||||
(Some((at, _)), Some((done, stays))) if done == at => with_base = stays,
|
||||
(Some((at, b)), _) => {
|
||||
let marks = text.get(at..).unwrap_or("").chars().skip(1).map(show).take_while(|m| is_mark(*m));
|
||||
let all: String = std::iter::once(b).chain(marks).inspect(|_| crate::work::steps(1)).collect();
|
||||
if draws_all(current, &all) {
|
||||
with_base = true;
|
||||
} else if let Some(f) = cluster_face(&all, current, run_face, primary, bold, italic) {
|
||||
// The character goes to that face with its marks.
|
||||
if at > seg_start {
|
||||
segs.push((seg_start, at, k));
|
||||
seg_start = at;
|
||||
}
|
||||
let face = (f.id() != primary.id()).then_some(f);
|
||||
cur = Some(SegKey { face, ..k });
|
||||
moved = Some(face);
|
||||
} else {
|
||||
with_base = k.complex || k.rtl;
|
||||
}
|
||||
matched = Some((at, with_base || moved.is_some()));
|
||||
}
|
||||
(None, _) => with_base = k.complex || k.rtl,
|
||||
}
|
||||
}
|
||||
}
|
||||
if !mark {
|
||||
base = (!c.is_control() && c != OBJ).then_some((i, dc));
|
||||
}
|
||||
let face = match (moved, cur) {
|
||||
(Some(face), _) => face,
|
||||
(None, Some(k)) if with_base => k.face,
|
||||
_ if !complex && east_asian(c) && primary_ea.is_some_and(|f| f.covers(c)) => primary_ea,
|
||||
_ if !c.is_control() && c != SOFT_HYPHEN && run_face.is_some_and(|f| f.covers(dc)) => run_face,
|
||||
_ if primary.covers(dc) || c.is_whitespace() || c.is_control() || c == SOFT_HYPHEN => None,
|
||||
Some(SegKey { face: Some(face), .. }) if face.covers(dc) => Some(face),
|
||||
(None, Some(SegKey { face: Some(face), .. })) if face.covers(dc) => Some(face),
|
||||
_ if !complex && ea_face.is_some() && crate::kinsoku::is_east_asian(c) => ea_face,
|
||||
_ => {
|
||||
let (bold, italic) = if complex { (rc.bold_cs, rc.italic_cs) } else { (rc.bold, rc.italic) };
|
||||
wordcraft_fonts::FontDb::global().fallback_styled(dc, primary.id(), bold, italic).map(|f| FaceRef::of(&f))
|
||||
}
|
||||
_ => wordcraft_fonts::FontDb::global().fallback_styled(dc, primary.id(), bold, italic).map(|f| FaceRef::of(&f)),
|
||||
};
|
||||
let key = SegKey { face, small: rc.small_caps && !rc.caps && c.is_lowercase(), complex, rtl };
|
||||
// A mark is set like the character it belongs to, as for `complex`: in small capitals at
|
||||
// that character's size, so the two stay in one shaping run and its cluster is matched
|
||||
// whole.
|
||||
let small = match cur {
|
||||
Some(k) if mark => k.small,
|
||||
_ => rc.small_caps && !rc.caps && c.is_lowercase(),
|
||||
};
|
||||
let key = SegKey { face, small, complex, rtl };
|
||||
match cur {
|
||||
Some(previous) if previous.same(&key) => {}
|
||||
Some(previous) => {
|
||||
@@ -139,6 +210,15 @@ impl<'a> Builder<'a> {
|
||||
// the height Word gives it.
|
||||
let (a, d) = match wordcraft_fonts::word::symbol_line(&rc.font, &r) {
|
||||
Some((a, d)) => (a * face.upem, d * face.upem),
|
||||
// A character Times New Roman or its metric twin lacks: the twin lacks more than
|
||||
// Times New Roman ("‒", "₽" in Liberation Serif), so the line is as tall as the run's
|
||||
// font, as with Times New Roman in Word, not as the taller fallback. East Asian text
|
||||
// keeps its face's height.
|
||||
None if face_override.is_some() && is_times_twin(&r.face.family) && !face.is_east_asian() => {
|
||||
let (a, d) = wordcraft_fonts::word::line_metrics(&r.face);
|
||||
let k = face.upem / r.face.upem.max(1.0);
|
||||
(a * k, d * k)
|
||||
}
|
||||
None => wordcraft_fonts::word::line_metrics(&face),
|
||||
};
|
||||
let k = size as f64 / face.upem.max(1.0);
|
||||
@@ -422,12 +502,15 @@ impl<'a> Builder<'a> {
|
||||
let ge = bounds.get(bi + 1).copied().unwrap_or(shape_text.len());
|
||||
let g0 = self.glyphs.len() as u32;
|
||||
let mut adv = 0.0f32;
|
||||
// What kerning added to the last glyph's advance: its pair with the next glyph.
|
||||
let mut kern = 0.0f32;
|
||||
while let Some(g) = shaped.get(gi) {
|
||||
if g.cluster >= ge {
|
||||
break;
|
||||
}
|
||||
self.glyphs.push(Glyph { gid: g.gid, dx: adv + g.x_offset as f32 * k * hscale, dy: g.y_offset as f32 * k });
|
||||
adv += g.x_advance as f32 * k * hscale;
|
||||
kern = if rc.kerned() && !key.rtl { pair_with_next(g, st.face.advance(g.gid)) * k * hscale } else { 0.0 };
|
||||
gi += 1;
|
||||
}
|
||||
let g1 = self.glyphs.len() as u32;
|
||||
@@ -455,6 +538,7 @@ impl<'a> Builder<'a> {
|
||||
obj_h: 0.0,
|
||||
obj_d: 0.0,
|
||||
dot: s == "." || s == ",",
|
||||
kern: if kind == ClKind::Text && g1 == g0 + 1 { kern } else { 0.0 },
|
||||
});
|
||||
}
|
||||
if matches!(dir, Dir::Para) {
|
||||
@@ -497,6 +581,13 @@ impl<'a> Builder<'a> {
|
||||
}
|
||||
}
|
||||
}
|
||||
// The ligature glyph's kerning pair with the following glyph belongs after its last
|
||||
// letter, not on the head inside the ligature (#8618).
|
||||
if let Some((head, rest)) = self.clusters.get_mut(i..=i + n).and_then(|cs| cs.split_first_mut())
|
||||
&& let Some(last) = rest.last_mut()
|
||||
{
|
||||
last.kern = std::mem::take(&mut head.kern);
|
||||
}
|
||||
i += n + 1;
|
||||
}
|
||||
}
|
||||
@@ -527,6 +618,7 @@ impl<'a> Builder<'a> {
|
||||
obj_h: 0.0,
|
||||
obj_d: 0.0,
|
||||
dot: false,
|
||||
kern: 0.0,
|
||||
});
|
||||
return;
|
||||
};
|
||||
@@ -560,7 +652,20 @@ impl<'a> Builder<'a> {
|
||||
let style = first.style;
|
||||
let g1 = added.last().map(|c| c.g1).unwrap_or(g0);
|
||||
self.shown.push((self.clusters.len(), text.to_string(), ranges));
|
||||
self.clusters.push(Cluster { start, end, adv: x, kind: ClKind::Text, style, g0, g1, break_after: false, obj_h: 0.0, obj_d: 0.0, dot: false });
|
||||
self.clusters.push(Cluster {
|
||||
start,
|
||||
end,
|
||||
adv: x,
|
||||
kind: ClKind::Text,
|
||||
style,
|
||||
g0,
|
||||
g1,
|
||||
break_after: false,
|
||||
obj_h: 0.0,
|
||||
obj_d: 0.0,
|
||||
dot: false,
|
||||
kern: 0.0,
|
||||
});
|
||||
}
|
||||
|
||||
/// Shape `texts` on top of one another as one cluster for `start..end`: each aligned within
|
||||
@@ -610,11 +715,38 @@ impl<'a> Builder<'a> {
|
||||
if !text.is_empty() {
|
||||
self.shown.push((k, text, ranges));
|
||||
}
|
||||
self.clusters.push(Cluster { start, end, adv, kind: ClKind::Text, style, g0, g1, break_after: false, obj_h: 0.0, obj_d: 0.0, dot: false });
|
||||
self.clusters.push(Cluster {
|
||||
start,
|
||||
end,
|
||||
adv,
|
||||
kind: ClKind::Text,
|
||||
style,
|
||||
g0,
|
||||
g1,
|
||||
break_after: false,
|
||||
obj_h: 0.0,
|
||||
obj_d: 0.0,
|
||||
dot: false,
|
||||
kern: 0.0,
|
||||
});
|
||||
Some(k)
|
||||
}
|
||||
}
|
||||
|
||||
/// What kerning added to a glyph's advance (in font units) for its pair with the next glyph. An
|
||||
/// old-style `kern` table's pair is split between its two glyphs, the second's half in its advance
|
||||
/// and its offset alike: that half is the pair with the glyph before, which stays on the line.
|
||||
fn pair_with_next(g: &wordcraft_fonts::ShapedGlyph, plain_advance: f64) -> f32 {
|
||||
let added = g.x_advance as f32 - plain_advance as f32;
|
||||
let before = if added != 0.0 { g.x_offset as f32 } else { 0.0 };
|
||||
added - before
|
||||
}
|
||||
|
||||
/// Times New Roman or one of its metric twins.
|
||||
fn is_times_twin(family: &str) -> bool {
|
||||
["Times New Roman", "Liberation Serif", "Tinos"].iter().any(|f| family.eq_ignore_ascii_case(f))
|
||||
}
|
||||
|
||||
/// Lay out an `EQ \o` field (ECMA-376 Part 1 §17.16.5.20): its arguments drawn on top of one
|
||||
/// another, as one cluster. An enclosure symbol among them (○ □ △ ◇, see
|
||||
/// [`wordcraft_doc::eq::EncloseShape`]) is drawn as a shape around the text rather than as a
|
||||
|
||||
@@ -55,7 +55,8 @@ pub(super) fn caps_expands(c: char) -> bool {
|
||||
}
|
||||
|
||||
/// Combining marks and joiners (bidi classes NSM, BN: harakat, ZWNJ, ZWJ) belong to the
|
||||
/// character before them: same font, same shaping run, so Arabic joining isn't broken.
|
||||
/// character before them: same font, same shaping run, so Arabic joining isn't broken. A mark
|
||||
/// that font can't draw takes its character to a face that draws both (`segment_keys`, #7865).
|
||||
pub(super) fn is_mark(c: char) -> bool {
|
||||
use unicode_bidi::BidiClass::{BN, NSM};
|
||||
// No ASCII character is a mark (its BN characters are controls).
|
||||
|
||||
@@ -99,14 +99,17 @@ fn auto_space_room(st: &StyleRun) -> f32 {
|
||||
/// size for Times New Roman, 0.2203 for Arial, 0.2575 for Calibri, 0.2980 for Courier New,
|
||||
/// 0.3041 for Cambria — which is half each face's average character width. With different sizes
|
||||
/// either side, the room after the Latin run takes the Latin size, not the Asian one.
|
||||
pub(super) fn auto_space(b: &mut Builder, text: &str, de: bool, dn: bool) -> Vec<(usize, f32)> {
|
||||
///
|
||||
/// `ea_lacks(at, c)`: the run at byte `at` names an installed East Asian font that has no glyph
|
||||
/// for `c`. Word adds no room beside such a character, though a substituted face draws it (#6591).
|
||||
pub(super) fn auto_space(b: &mut Builder, text: &str, de: bool, dn: bool, ea_lacks: impl Fn(usize, char) -> bool) -> Vec<(usize, f32)> {
|
||||
let mut out = Vec::new();
|
||||
if !de && !dn {
|
||||
return out;
|
||||
}
|
||||
let mut shown = b.shown.iter().map(|s| (s.0, s.1.as_str())).peekable();
|
||||
// The previous text cluster: index and its last character.
|
||||
let mut prev: Option<(usize, char)> = None;
|
||||
// The previous text cluster: index, its last character and its start byte.
|
||||
let mut prev: Option<(usize, char, usize)> = None;
|
||||
for k in 0..b.clusters.len() {
|
||||
let Some(c) = b.clusters.get(k) else { break };
|
||||
match c.kind {
|
||||
@@ -126,8 +129,13 @@ pub(super) fn auto_space(b: &mut Builder, text: &str, de: bool, dn: bool) -> Vec
|
||||
prev = None;
|
||||
continue;
|
||||
};
|
||||
if let Some((pk, pc)) = prev
|
||||
let start = c.start;
|
||||
if let Some((pk, pc, pstart)) = prev
|
||||
&& let Some(side) = crate::kinsoku::auto_space(pc, first, de, dn)
|
||||
&& !match side {
|
||||
crate::kinsoku::AsianSide::Left => ea_lacks(pstart, pc),
|
||||
crate::kinsoku::AsianSide::Right => ea_lacks(start, first),
|
||||
}
|
||||
{
|
||||
let style = b.clusters.get(pk).map(|p| p.style as usize);
|
||||
let st = style.and_then(|i| b.styles.get(i));
|
||||
@@ -142,7 +150,7 @@ pub(super) fn auto_space(b: &mut Builder, text: &str, de: bool, dn: bool) -> Vec
|
||||
out.push((pk, gap));
|
||||
}
|
||||
}
|
||||
prev = Some((k, last));
|
||||
prev = Some((k, last, start));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -14,6 +14,9 @@ const MIN_LINE_WIDTH: f32 = 1.0;
|
||||
struct Breaker<'e> {
|
||||
level: Option<&'e Level>,
|
||||
rp: wordcraft_doc::resolve::ResolvedPara,
|
||||
/// The space before the paragraph that the flow laid out above it, which a Top-and-Bottom
|
||||
/// object in it is laid out again below (see [`ParaEnv::space_before`]).
|
||||
space_before: f32,
|
||||
mark_style: u32,
|
||||
exclusions: &'e [Exclusion],
|
||||
n: usize,
|
||||
@@ -220,6 +223,7 @@ impl<'e> Breaker<'e> {
|
||||
// Exact spacing fixes the table-contact boundary even when the mark has other metrics.
|
||||
// Keep the existing estimate for shapes and for non-exact spacing.
|
||||
table_h: if let LineSpacing::Exactly(h) = rp.line_spacing { h } else { est_h },
|
||||
space_before: env.space_before,
|
||||
rp,
|
||||
first_x0: None,
|
||||
hcache: Vec::new(),
|
||||
@@ -262,6 +266,26 @@ impl<'e> Breaker<'e> {
|
||||
let mut guard = 0;
|
||||
loop {
|
||||
let lo = self.row_left(pl);
|
||||
// A Top-and-Bottom object ending in the paragraph's space before (or reaching into
|
||||
// its first line) is a block the first line must start below, with that space before
|
||||
// laid out again under it (#7143). Exclusions are relative to the first line, so look
|
||||
// `space_before` above it too: the space the flow actually laid out, so an object
|
||||
// above a gap that collapsing, contextual spacing or a page top removed takes no
|
||||
// room, while the part of a merged gap that was laid out still does.
|
||||
if self.first && self.space_before > 0.0 {
|
||||
let before = self.space_before;
|
||||
let row = (self.top - before, self.est_h + before, self.table_h);
|
||||
if let Some(below) = self
|
||||
.exclusions
|
||||
.iter()
|
||||
.filter(|e| e.top_bottom)
|
||||
.filter(|e| e.intersects_row(row.0, row.1, row.2, lo, self.base_right))
|
||||
.map(|e| e.bottom)
|
||||
.reduce(f32::max)
|
||||
{
|
||||
self.top = self.top.max(below + before);
|
||||
}
|
||||
}
|
||||
let row = (self.top, self.est_h, self.table_h);
|
||||
match row_spans(self.exclusions, row, (lo, self.base_right), self.tight_indent).map(|mut spans| (spans.pop_front(), spans)) {
|
||||
Ok((Some((a, b)), rest)) => {
|
||||
@@ -442,7 +466,7 @@ impl<'e> Breaker<'e> {
|
||||
/// tallest picture on it (which sits on the baseline).
|
||||
fn extents(&self, pl: &ParaLayout, (c0, c1): (usize, usize)) -> Extents {
|
||||
let rp = &self.rp;
|
||||
let mut ex = Extents { asc: 0.0, desc: 0.0, obj_asc: 0.0, obj_desc: 0.0, text: false };
|
||||
let mut ex = Extents { asc: 0.0, desc: 0.0, obj_asc: 0.0, obj_desc: 0.0, text: false, single: 0.0 };
|
||||
let mut any = false;
|
||||
let dropped = pl.drop_cap.map_or(0, |d| d.0);
|
||||
for (k, c) in pl.clusters.get(c0..c1).into_iter().flatten().enumerate() {
|
||||
@@ -486,6 +510,7 @@ impl<'e> Breaker<'e> {
|
||||
};
|
||||
ex.asc = ex.asc.max(a);
|
||||
ex.desc = ex.desc.max(d);
|
||||
ex.single = ex.single.max(a + d);
|
||||
any = true;
|
||||
// Text needs its descent below the line; so do inline math (an object with its own
|
||||
// descent) and a check box. A line break ending the line is no text.
|
||||
@@ -503,7 +528,7 @@ impl<'e> Breaker<'e> {
|
||||
/// The line's height, baseline and text extent.
|
||||
fn measure(&self, pl: &ParaLayout, range: (usize, usize)) -> Measure {
|
||||
let rp = &self.rp;
|
||||
let Extents { mut asc, mut desc, obj_asc, obj_desc, text } = self.extents(pl, range);
|
||||
let Extents { mut asc, mut desc, obj_asc, obj_desc, text, single } = self.extents(pl, range);
|
||||
let mut text_natural = asc + desc;
|
||||
let font_desc = desc;
|
||||
desc = desc.max(obj_desc);
|
||||
@@ -554,6 +579,10 @@ impl<'e> Breaker<'e> {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Multiple spacing adds (m - 1) x the tallest of the line's runs, not of the line: a line
|
||||
// mixing fonts is as much taller as its runs' extents make it, once (Word for Mac and
|
||||
// Windows: 10 pt Times New Roman with 10 pt Courier New at 1.5 and double spacing).
|
||||
let run_leading = if single > 0.0 && !pictures_alone { single.min(text_natural) } else { text_natural };
|
||||
// Keep the picture floor independent of list-label metrics.
|
||||
let natural = asc + desc;
|
||||
let pictures = if obj_asc > asc { obj_asc + desc } else { 0.0 };
|
||||
@@ -562,7 +591,9 @@ impl<'e> Breaker<'e> {
|
||||
let (height, centred) = match (rp.line_spacing, grid) {
|
||||
(LineSpacing::Multiple(m), Some(g)) => ((g.snap_height(natural) * m).max(g.snap_height(pictures)), true),
|
||||
(LineSpacing::AtLeast(v), Some(g)) => (g.snap_height(natural.max(pictures)).max(v), true),
|
||||
(LineSpacing::Multiple(m), None) => ((text_natural * m + label_extra).max(text_pictures + (m - 1.0).max(0.0) * font_natural), false),
|
||||
(LineSpacing::Multiple(m), None) => {
|
||||
((text_natural + (m - 1.0) * run_leading + label_extra).max(text_pictures + (m - 1.0).max(0.0) * font_natural), false)
|
||||
}
|
||||
(LineSpacing::AtLeast(v), None) => (natural.max(text_pictures).max(v), false),
|
||||
(LineSpacing::Exactly(v), _) => (v, false),
|
||||
};
|
||||
@@ -745,6 +776,8 @@ struct Extents {
|
||||
obj_desc: f32,
|
||||
/// Whether the line holds text besides its pictures (spaces and tabs don't count).
|
||||
text: bool,
|
||||
/// The tallest of its runs' own heights (ascent plus descent): the multiple's leading.
|
||||
single: f32,
|
||||
}
|
||||
|
||||
/// A line's height and baseline, and the extent of its text.
|
||||
@@ -876,6 +909,14 @@ impl Scan {
|
||||
bk.wrapped_tab = Some(j);
|
||||
return true;
|
||||
}
|
||||
if bk.wrapped_tab == Some(j) && self.narrowed && stop.pos > bk.base_right + 0.01 && bk.skipped < 50 {
|
||||
// A left tab past the right indent that wrapped into a span narrowed by a
|
||||
// floating object (the far side of it, say): like Word, it goes on to the
|
||||
// first line clear of the object (#6577). A stop inside the right indent
|
||||
// keeps the zero-width path below.
|
||||
self.skip = true;
|
||||
return true;
|
||||
}
|
||||
if bk.wrapped_tab == Some(j) {
|
||||
// Still past the right indent on the line it wrapped to: it takes no
|
||||
// room, and its text starts at the indent rather than on a line of its own.
|
||||
@@ -909,19 +950,33 @@ impl Scan {
|
||||
}
|
||||
self.x += w;
|
||||
}
|
||||
_ => self.pending_tab = Some((j, stop, self.x)),
|
||||
_ => {
|
||||
// A right tab's room grows from nothing with its text (a tab moved on from the
|
||||
// line before may still hold the width it had there).
|
||||
if stop.align == TabAlign::Right
|
||||
&& let Some(c) = pl.clusters.get_mut(j)
|
||||
{
|
||||
c.adv = 0.0;
|
||||
}
|
||||
self.pending_tab = Some((j, stop, self.x));
|
||||
}
|
||||
}
|
||||
if stop.leader != TabLeader::None {
|
||||
self.leaders.push((j, stop.leader));
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether text after a right/centre tab grows leftwards into the tab's space first.
|
||||
/// Whether text after a right/centre tab grows leftwards into the tab's space first. Up to a
|
||||
/// right stop it fits even past the right indent (Word: a TOC entry whose text ends
|
||||
/// less than a digit short of the indent keeps its page number on its line when the stop is
|
||||
/// at the margin); unshifted, the text after the tab ends at `x - room`.
|
||||
fn absorbs(&self, pl: &ParaLayout, advance: f32) -> bool {
|
||||
self.pending_tab.is_some_and(|(tj, stop, _)| {
|
||||
let room = pl.clusters.get(tj).map(|t| t.adv).unwrap_or(0.0);
|
||||
match stop.align {
|
||||
TabAlign::Right | TabAlign::Decimal => room >= advance,
|
||||
// Not where a floating object narrows the line: the text would run into it.
|
||||
TabAlign::Right => room >= advance || (!self.narrowed && self.x - room + advance <= stop.pos + 0.01),
|
||||
TabAlign::Decimal => room >= advance,
|
||||
TabAlign::Center => room >= advance / 2.0 && self.x + advance / 2.0 <= self.right_edge + 0.01,
|
||||
_ => false,
|
||||
}
|
||||
@@ -947,7 +1002,7 @@ impl Scan {
|
||||
0.0
|
||||
};
|
||||
let fits = absorbs
|
||||
|| self.x + advance - pl.auto_space_after(j) <= self.right_edge + shrink + 0.01
|
||||
|| self.x + advance - pl.auto_space_after(j) - line_end_kern(pl, j) <= self.right_edge + shrink + 0.01
|
||||
|| c.kind == ClKind::Space
|
||||
|| c.kind == ClKind::Marker;
|
||||
if !fits && pl.is_edit_boundary(c.start) && (c0..j).any(|k| pl.clusters.get(k).is_some_and(takes_room)) {
|
||||
@@ -997,7 +1052,9 @@ impl Scan {
|
||||
/// Text after a decimal/centre/right tab shifts as it grows.
|
||||
fn shift_pending_tab(&mut self, pl: &mut ParaLayout) {
|
||||
let Some((tj, stop, tx)) = self.pending_tab else { return };
|
||||
let seg_w = self.x - tx;
|
||||
// For a right tab `x` includes the room the tab has so far (it starts from none).
|
||||
let old = pl.clusters.get(tj).map(|c| c.adv).unwrap_or(0.0);
|
||||
let seg_w = self.x - tx - if stop.align == TabAlign::Right { old } else { 0.0 };
|
||||
let shift = match stop.align {
|
||||
TabAlign::Right => stop.pos - tx - seg_w,
|
||||
TabAlign::Center => stop.pos - tx - seg_w / 2.0,
|
||||
@@ -1006,7 +1063,6 @@ impl Scan {
|
||||
_ => 0.0,
|
||||
};
|
||||
let shift = shift.max(0.0);
|
||||
let old = pl.clusters.get(tj).map(|c| c.adv).unwrap_or(0.0);
|
||||
if (shift - old).abs() > 0.001 {
|
||||
let delta = shift - old;
|
||||
if let Some(c) = pl.clusters.get_mut(tj) {
|
||||
@@ -1114,6 +1170,17 @@ impl Scan {
|
||||
}
|
||||
}
|
||||
|
||||
/// The kerning cluster `j` loses when the line ends after it inside a word: Word measures a line's
|
||||
/// last letter without its pair with the letter that goes on to the next line (a cell's width
|
||||
/// swept a twip at a time in Word: the letters before a broken kerning pair fit only where they
|
||||
/// fit on their own, without the pair).
|
||||
fn line_end_kern(pl: &ParaLayout, j: usize) -> f32 {
|
||||
match (pl.clusters.get(j), pl.clusters.get(j + 1)) {
|
||||
(Some(c), Some(next)) if next.kind == ClKind::Text => c.kern,
|
||||
_ => 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Narrowest span text flows into beside a floating object, points. Word puts an empty
|
||||
/// paragraph beside a floating table in a 21.3pt gap but not in an 18.6pt one.
|
||||
const MIN_SPAN: f32 = 20.0;
|
||||
|
||||
@@ -147,6 +147,9 @@ pub struct Cluster {
|
||||
pub obj_d: f32,
|
||||
/// The cluster is a decimal separator (decimal tabs align on it).
|
||||
pub dot: bool,
|
||||
/// The kerning between this cluster and the next (part of `adv`, usually negative): a line
|
||||
/// that ends between them lays the cluster out without it.
|
||||
pub kern: f32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -391,8 +394,14 @@ pub struct ParaEnv<'a> {
|
||||
/// How digits look on screen (an unresolved `System` shows Western digits).
|
||||
pub numeral: NumeralMode,
|
||||
/// Areas text must flow around (floating objects), relative to the paragraph: x from the
|
||||
/// column's left edge, y from the top of the first line.
|
||||
/// column's left edge, y from the top of the first line (its top with the space before
|
||||
/// applied, which is where [`ParaEnv::space_before`] reaches up to).
|
||||
pub exclusions: &'a [Exclusion],
|
||||
/// The space before the paragraph that the flow above it actually laid out: its declared
|
||||
/// space before less what collapsing against the previous paragraph's space after, contextual
|
||||
/// spacing or a page top took away (and the negative space applied at a page top). A
|
||||
/// Top-and-Bottom object reaching into it is laid out again below it (#7143).
|
||||
pub space_before: f32,
|
||||
/// Automatic equation numbers used before this paragraph.
|
||||
pub eq_number: u32,
|
||||
pub read_line_spacing: Option<f32>,
|
||||
|
||||
@@ -62,6 +62,7 @@ impl Slot {
|
||||
obj_h,
|
||||
obj_d,
|
||||
dot: false,
|
||||
kern: 0.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -101,6 +102,11 @@ fn is_special(c: char) -> bool {
|
||||
fn paragraph_props(p: &Paragraph, env: &ParaEnv) -> ResolvedPara {
|
||||
let doc = env.doc;
|
||||
let mut rp = doc.styles.resolve_para_in(&p.props, env.table.map(|t| &t.para));
|
||||
// Before Word 2013 layout (compatibility mode 15) a row split across pages divides its cells'
|
||||
// text at any line: widow/orphan control doesn't apply in a table (measured in modes 12, 14).
|
||||
if env.table.is_some() && doc.settings.compat_mode < wordcraft_doc::COMPAT_MODE_CURRENT {
|
||||
rp.widow_control = false;
|
||||
}
|
||||
if let Some(spacing) = env.read_line_spacing.filter(|s| s.is_finite() && (1.0..=2.0).contains(s)) {
|
||||
rp.line_spacing = wordcraft_doc::props::LineSpacing::Multiple(spacing);
|
||||
}
|
||||
@@ -546,7 +552,12 @@ fn list_label(cx: &Cx, b: &mut Builder, mark_style: u32) -> Option<Label> {
|
||||
let break_only =
|
||||
b.clusters.iter().any(|c| c.kind == ClKind::PageBreak) && b.clusters.iter().all(|c| matches!(c.kind, ClKind::PageBreak | ClKind::Marker));
|
||||
let (text, lvl) = cx.env.label.as_ref().filter(|_| !break_only && !cx.env.joined)?;
|
||||
let rc = cx.res.char(&p.mark.clone().overlaid(&lvl.chr));
|
||||
let mut rc = cx.res.char(&p.mark.clone().overlaid(&lvl.chr));
|
||||
// Word never kerns a list number, whatever the kerning of the paragraph mark or the level
|
||||
// (measured in Word for Mac: "11)" in Times New Roman with kerning on is 16 pt wide, not
|
||||
// the 15.55 pt of the kerned "11", so it passes a 312-twip hanging indent and the text goes on
|
||||
// to the next tab stop).
|
||||
Arc::make_mut(&mut rc).kern = 0.0;
|
||||
// A bullet no installed font can draw would come from whatever icon font has its
|
||||
// private-use code (Font Awesome's Twitter logo at U+F081, #1683): it shows the level's
|
||||
// default bullet instead.
|
||||
@@ -652,6 +663,22 @@ fn shown_text(cx: &Cx) -> Option<String> {
|
||||
Some(shown)
|
||||
}
|
||||
|
||||
/// Each run's end byte and the installed East Asian font (`w:eastAsia`) it names, `None` when it
|
||||
/// names none or one that isn't installed. Empty when `wanted` is false or the text is ASCII, which
|
||||
/// has no East Asian characters to look the fonts up for.
|
||||
fn installed_east_asian_fonts(cx: &Cx, wanted: bool) -> Vec<(usize, Option<wordcraft_fonts::FaceRef>)> {
|
||||
if !wanted || cx.p.text.is_ascii() {
|
||||
return Vec::new();
|
||||
}
|
||||
cx.p.run_ranges()
|
||||
.map(|(range, props)| {
|
||||
let rc = cx.res.char(props);
|
||||
let face = rc.font_ea.as_deref().filter(|f| !f.trim().is_empty()).map(|f| wordcraft_fonts::word::resolve(f, rc.bold, rc.italic));
|
||||
(range.end, face.filter(|r| !r.substituted).map(|r| r.face))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Lay out one paragraph.
|
||||
pub fn layout_para(p: &Paragraph, env: &ParaEnv) -> ParaLayout {
|
||||
#[cfg(test)]
|
||||
@@ -687,7 +714,12 @@ pub fn layout_para(p: &Paragraph, env: &ParaEnv) -> ParaLayout {
|
||||
let auto_space = if rp.snap_to_grid && env.grid.snap_all && env.grid.chars.is_some() {
|
||||
Vec::new()
|
||||
} else {
|
||||
auto_space(&mut sh.b, &p.text, rp.auto_space_de, rp.auto_space_dn)
|
||||
let ea = installed_east_asian_fonts(&cx, rp.auto_space_de || rp.auto_space_dn);
|
||||
// Runs come in order, so their ends rise: the run holding `at` is a binary search away.
|
||||
let ea_lacks = |at: usize, c: char| {
|
||||
ea.get(ea.partition_point(|(end, _)| *end <= at)).and_then(|(_, face)| *face).is_some_and(|f: wordcraft_fonts::FaceRef| !f.covers(c))
|
||||
};
|
||||
auto_space(&mut sh.b, &p.text, rp.auto_space_de, rp.auto_space_dn, ea_lacks)
|
||||
};
|
||||
let mut skip = sh.left.clone();
|
||||
skip.extend(sh.bare.iter().cloned());
|
||||
|
||||
@@ -234,8 +234,10 @@ fn new_page_builder<'p>(
|
||||
sect_beneath: false,
|
||||
beneath: false,
|
||||
foot_top: f32::MAX,
|
||||
leading_floor: 0.0,
|
||||
early,
|
||||
seeded: 0,
|
||||
framed: Vec::new(),
|
||||
settle,
|
||||
column_lines: None,
|
||||
}
|
||||
@@ -445,9 +447,10 @@ fn section_endnotes(ctx: &mut Ctx, pb: &mut PageBuilder, endnotes: &mut VecDeque
|
||||
/// the turned pages of vertical sections.
|
||||
fn finish_pages(pb: PageBuilder, doc: &Document, sections: &[(usize, &SectionProps)], web: bool) -> Vec<Page> {
|
||||
let mut pb = pb;
|
||||
pb.close_column_lines();
|
||||
pb.apply_valign();
|
||||
pb.flush_notes();
|
||||
// Each page is aligned once, before its notes go on it: `finish_page` leaves the page
|
||||
// top-aligned after, so a page of continued notes isn't moved down again past the bottom
|
||||
// margin when the next one starts.
|
||||
pb.finish_page();
|
||||
let last_block = doc.body.len().saturating_sub(1);
|
||||
for _ in 0..MAX_NOTE_PAGES {
|
||||
if pb.carry.is_empty() {
|
||||
@@ -455,7 +458,7 @@ fn finish_pages(pb: PageBuilder, doc: &Document, sections: &[(usize, &SectionPro
|
||||
}
|
||||
let top = pb.top;
|
||||
pb.new_page(last_block, top);
|
||||
pb.flush_notes();
|
||||
pb.finish_page();
|
||||
}
|
||||
pb.carry.clear();
|
||||
pb.raise_front();
|
||||
|
||||
@@ -248,6 +248,7 @@ pub fn measure_table_columns(doc: &wordcraft_doc::Document, t: &Table) -> Vec<(f
|
||||
// Measurement uses a fixed environment (like show_hidden/proofing above).
|
||||
numeral: crate::NumeralMode::default(),
|
||||
exclusions: &[],
|
||||
space_before: 0.0,
|
||||
eq_number: 0,
|
||||
read_line_spacing: None,
|
||||
grid: crate::para::Grid::default(),
|
||||
@@ -616,6 +617,51 @@ fn table_frame(ctx: &mut Ctx, t: &Table, avail: f32, depth: usize, style: Option
|
||||
}
|
||||
|
||||
pub fn layout_table(ctx: &mut Ctx, story: StoryRef, t: &Table, path: &[u32], avail: f32, depth: usize) -> TableLayout {
|
||||
layout_table_rows(ctx, story, t, path, avail, depth, None)
|
||||
}
|
||||
|
||||
/// Row `ri` of the body table laid out again for where it lands on a page, `room` points above the
|
||||
/// bottom of the page body: a merged cell starting in it that runs on past the page end is
|
||||
/// aligned (and its turned text laid out) within that room, as its text is drawn with this row.
|
||||
/// The row's height is the one [`layout_table`] gave it.
|
||||
pub fn layout_table_row_in(ctx: &mut Ctx, t: &Table, path: &[u32], avail: f32, ri: usize, room: f32) -> Option<RowLayout> {
|
||||
// A look ahead: list and equation numbers in the cells don't count again.
|
||||
let (counters, eq_count) = (ctx.counters.clone(), ctx.eq_count);
|
||||
let mut tl = layout_table_rows(ctx, StoryRef::Body, t, path, avail, 1, Some((ri, room)));
|
||||
(ctx.counters, ctx.eq_count) = (counters, eq_count);
|
||||
tl.rows.pop()
|
||||
}
|
||||
|
||||
/// How many rows after row `ri` the merged cells starting in it run on (0 without any).
|
||||
pub(crate) fn merge_rows_after(t: &Table, ri: usize) -> usize {
|
||||
let Some(row) = t.rows.get(ri) else { return 0 };
|
||||
let mut gx = row.first_grid();
|
||||
let mut most = 0;
|
||||
for c in &row.cells {
|
||||
let g = gx;
|
||||
gx += c.span();
|
||||
if c.props.vmerge != VMerge::Restart {
|
||||
continue;
|
||||
}
|
||||
let mut k = ri + 1;
|
||||
while t.rows.get(k).is_some_and(|r| {
|
||||
let mut gx = r.first_grid();
|
||||
r.cells.iter().any(|x| {
|
||||
let at = gx;
|
||||
gx += x.span();
|
||||
at == g && x.props.vmerge == VMerge::Continue
|
||||
})
|
||||
}) {
|
||||
k += 1;
|
||||
}
|
||||
most = most.max(k - ri - 1);
|
||||
}
|
||||
most
|
||||
}
|
||||
|
||||
/// [`layout_table`], or with `only` = (row, room) just that row, its merged cells aligned within
|
||||
/// `room` (see [`layout_table_row_in`]).
|
||||
fn layout_table_rows(ctx: &mut Ctx, story: StoryRef, t: &Table, path: &[u32], avail: f32, depth: usize, only: Option<(usize, f32)>) -> TableLayout {
|
||||
let style = table_style(ctx, t);
|
||||
// Cell text formatting and looks per set of style parts, built once per table.
|
||||
let mut cell_text: Vec<(Region, CellText)> = Vec::new();
|
||||
@@ -797,7 +843,7 @@ pub fn layout_table(ctx: &mut Ctx, story: StoryRef, t: &Table, path: &[u32], ava
|
||||
rows.push(cells);
|
||||
}
|
||||
grow_vertical_merges(&rows, &mut heights);
|
||||
finish_table_rows(ctx, TableRows { story, table: t, path, depth, cell_text, rows, heights, bottoms, edges, x, total })
|
||||
finish_table_rows(ctx, TableRows { story, table: t, path, depth, cell_text, rows, heights, bottoms, edges, x, total, only })
|
||||
}
|
||||
|
||||
fn grow_vertical_merges(rows: &[Vec<CellBox>], heights: &mut [f32]) {
|
||||
@@ -832,13 +878,15 @@ struct TableRows<'a> {
|
||||
edges: Vec<f32>,
|
||||
x: f32,
|
||||
total: f32,
|
||||
/// Only this row (and the room under its top for its merged cells), when set.
|
||||
only: Option<(usize, f32)>,
|
||||
}
|
||||
|
||||
/// 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.
|
||||
fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout {
|
||||
let TableRows { story, table: t, path, depth, cell_text, rows, heights, bottoms, edges, x, total } = input;
|
||||
let TableRows { story, table: t, path, depth, cell_text, rows, heights, bottoms, edges, x, total, only } = input;
|
||||
// Grid columns holding a vertical-merge continuation, per row.
|
||||
let cont: Vec<Vec<usize>> = t
|
||||
.rows
|
||||
@@ -858,6 +906,9 @@ 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());
|
||||
for (ri, cells) in rows.into_iter().enumerate() {
|
||||
if only.is_some_and(|(row, _)| row != ri) {
|
||||
continue;
|
||||
}
|
||||
let rh = heights.get(ri).copied().unwrap_or(0.0);
|
||||
let exact = t.rows.get(ri).is_some_and(|r| r.props.height_rule == HeightRule::Exact && r.props.height.is_some_and(|h| h > 0.0));
|
||||
let mut items = Vec::new();
|
||||
@@ -898,10 +949,16 @@ fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout {
|
||||
_ => None,
|
||||
})
|
||||
.fold(c.h, f32::max);
|
||||
// A merged cell's text is drawn with its restart row, even when the merge runs on
|
||||
// over later pages: only the room left on the page it starts on can align it.
|
||||
let align_span = match only {
|
||||
Some((_, room)) if c.vmerge == VMerge::Restart => span_h.min(room.max(0.0)),
|
||||
_ => span_h,
|
||||
};
|
||||
let mut dy = match c.valign {
|
||||
VAlign::Top => 0.0,
|
||||
VAlign::Center => ((span_h - align_h) / 2.0).max(0.0),
|
||||
VAlign::Bottom => (span_h - align_h).max(0.0),
|
||||
VAlign::Center => ((align_span - align_h) / 2.0).max(0.0),
|
||||
VAlign::Bottom => (align_span - align_h).max(0.0),
|
||||
};
|
||||
let end = (c.vmerge != VMerge::Continue && c.turned.is_none()).then_some(c.end + dy);
|
||||
let mut cell_items = c.items;
|
||||
@@ -909,7 +966,7 @@ fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout {
|
||||
dy = 0.0;
|
||||
let m = c.margins;
|
||||
// The lines run the cell's whole height (laid out again if the row grew).
|
||||
let len = (span_h - (c.h - tn.len)).clamp(4.0, TURNED_LIMIT);
|
||||
let len = (align_span - (c.h - tn.len)).clamp(4.0, TURNED_LIMIT);
|
||||
let mut across = tn.across;
|
||||
if (len - tn.len).abs() > 0.01
|
||||
&& let Some(cell) = t.rows.get(ri).and_then(|r| r.cells.get(tn.ci))
|
||||
|
||||
@@ -2,7 +2,7 @@ use super::boxes::{BoxInput, clear_of_float_tables, layout_box};
|
||||
use super::ctx::{Ctx, with_pct_base};
|
||||
use super::floats::{WrapArea, align_in, body_wraps};
|
||||
use super::flow::again;
|
||||
use super::headers::{header_items_cap, header_table_areas, placed_cost};
|
||||
use super::headers::{begins_section, header_items_cap, header_table_areas, placed_cost};
|
||||
use super::notes::table_notes;
|
||||
use super::page::{PageBuilder, PageFrame, page_frame};
|
||||
use super::placed::Placed;
|
||||
@@ -14,14 +14,14 @@ pub(crate) fn footer_table_wraps(ctx: &mut Ctx, pb: &PageBuilder) -> Vec<WrapAre
|
||||
return Vec::new();
|
||||
}
|
||||
let Some(page) = pb.pages.last() else { return Vec::new() };
|
||||
let first = pb.pages.iter().rev().nth(1).is_none_or(|prev| prev.section != page.section);
|
||||
let hf = Arc::clone(&ctx.hf);
|
||||
let first = begins_section(&hf.sections, pb.pages.iter().rev().nth(1), page);
|
||||
let key = (page.section, page.number, first);
|
||||
if let Some(areas) = ctx.footer_wraps.get(&key) {
|
||||
return areas.clone();
|
||||
}
|
||||
ctx.footer_wraps.insert(key, Vec::new());
|
||||
let doc = ctx.doc;
|
||||
let hf = Arc::clone(&ctx.hf);
|
||||
let Some((_, sect)) = hf.sections.get(page.section) else { return Vec::new() };
|
||||
if sect.text_direction.is_turned() {
|
||||
return Vec::new();
|
||||
@@ -73,6 +73,8 @@ pub(crate) fn footer_table_wraps(ctx: &mut Ctx, pb: &PageBuilder) -> Vec<WrapAre
|
||||
/// The room a table in the text needs to start on a page: its repeated header rows and the least
|
||||
/// room its first row can start in (whole, or the part of it that splits off). A paragraph kept
|
||||
/// with the table goes over with it when that much is not left, as in Word.
|
||||
/// Before Word 2013 layout (compatibility mode 15) the header rows may stay alone at the foot of a
|
||||
/// page, so the paragraph keeps with them only.
|
||||
pub(crate) fn table_start_need(ctx: &mut Ctx, t: &wordcraft_doc::Table, block: usize, width: f32) -> f32 {
|
||||
// A look ahead: list and equation numbers in the cells don't count yet.
|
||||
let (counters, eq_count) = (ctx.counters.clone(), ctx.eq_count);
|
||||
@@ -80,6 +82,10 @@ pub(crate) fn table_start_need(ctx: &mut Ctx, t: &wordcraft_doc::Table, block: u
|
||||
(ctx.counters, ctx.eq_count) = (counters, eq_count);
|
||||
let headers = t.rows.iter().take_while(|r| r.props.header).count();
|
||||
let head: f32 = tl.rows.iter().take(headers).map(|r| r.height).sum();
|
||||
if headers > 0 && ctx.doc.settings.compat_mode < wordcraft_doc::COMPAT_MODE_CURRENT {
|
||||
// With the border below the last of them, as `place_table` places them.
|
||||
return head + tl.rows.get(headers - 1).map_or(0.0, |r| r.edge);
|
||||
}
|
||||
let (Some(row), Some(laid)) = (t.rows.get(headers), tl.rows.get(headers)) else { return head };
|
||||
// ponytail: bisection assumes starting a row gets no harder with more room.
|
||||
let (mut lo, mut hi) = (0.0f32, laid.height + laid.edge);
|
||||
@@ -259,9 +265,11 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc
|
||||
t.rows.get(ri).is_some_and(|r| r.props.height_rule == HeightRule::AtLeast && r.props.height.is_some_and(|h| h > room + 0.01))
|
||||
};
|
||||
// Like Word, repeated header rows don't stay alone at the bottom of a page: when the first row
|
||||
// after them can't start under them there, the table starts on the next page.
|
||||
// after them can't start under them there, the table starts on the next page. Before Word
|
||||
// 2013 layout (compatibility mode 15) they do (measured in modes 12 and 14).
|
||||
let first = header_rows.len();
|
||||
if !header_rows.is_empty()
|
||||
&& ctx.doc.settings.compat_mode >= wordcraft_doc::COMPAT_MODE_CURRENT
|
||||
&& !pb.at_top()
|
||||
&& let Some(row) = tl.rows.get(first)
|
||||
{
|
||||
@@ -288,13 +296,22 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc
|
||||
.get(ri)
|
||||
.is_some_and(|r| r.props.cant_split && !(r.props.height_rule == HeightRule::Exact && r.props.height.is_some_and(|h| h > 0.0)));
|
||||
let mut rest: Option<table::RowLayout> = None;
|
||||
// The row laid out again for where it lands, when a merge starting in it runs past the
|
||||
// end of that page (its text is drawn with this row, so it can't be aligned below it).
|
||||
let mut aligned: Option<table::RowLayout> = None;
|
||||
let merge_rows = table::merge_rows_after(t, ri);
|
||||
let merge_h: f32 = tl.rows.iter().skip(ri).take(merge_rows + 1).map(|r| r.height).sum();
|
||||
// On a new page holding only the repeated header rows.
|
||||
let mut fresh = false;
|
||||
// Nothing but this table's header rows above it on a page it started at the top of.
|
||||
let under_top_headers = ri == first && table_at_top;
|
||||
// Each pass places the part of the row that fits, then breaks the page.
|
||||
for _ in 0..1000 {
|
||||
let cur = rest.as_ref().unwrap_or(row);
|
||||
if rest.is_none() && merge_rows > 0 {
|
||||
let room = (pb.bottom - pb.y).max(0.0);
|
||||
aligned = (merge_h > room + 0.01).then(|| table::layout_table_row_in(ctx, t, &[block as u32], width, ri, room)).flatten();
|
||||
}
|
||||
let cur = rest.as_ref().or(aligned.as_ref()).unwrap_or(row);
|
||||
// A fitting kept row follows the next row when that row cannot start below it.
|
||||
// Move only the prefix's start; an oversized follower cannot separate its kept rows.
|
||||
let defer_kept = pb.y + cur.height <= pb.bottom + 0.01
|
||||
@@ -351,7 +368,7 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc
|
||||
}
|
||||
fresh = true;
|
||||
}
|
||||
let last = rest.as_ref().unwrap_or(row);
|
||||
let last = rest.as_ref().or(aligned.as_ref()).unwrap_or(row);
|
||||
place(pb, last);
|
||||
table_notes(ctx, pb, &last.items);
|
||||
}
|
||||
|
||||
+1255
-1
File diff suppressed because it is too large
Load Diff
@@ -133,6 +133,34 @@ fn spaces_punctuation_hangul_and_latin_alone_get_nothing() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Word adds no automatic space, on either side, beside an ideograph whose run names an installed
|
||||
/// East Asian font without ideographs, even though a substituted face draws it (#6591: 0.00 pt
|
||||
/// with `w:eastAsia="Times New Roman"`). A font that isn't installed keeps the space.
|
||||
#[test]
|
||||
fn an_east_asian_font_without_ideographs_turns_it_off() {
|
||||
crate::test_fonts();
|
||||
let with = |latin: Option<&str>, asian: &str| {
|
||||
let mut d = Document::from_text("法院94年A字");
|
||||
let p = para0(&mut d);
|
||||
let len = p.text.len();
|
||||
p.format(0, len, &|c: &mut CharProps| {
|
||||
c.font = latin.map(str::to_string);
|
||||
c.font_ea = Some(asian.to_string());
|
||||
})
|
||||
.unwrap();
|
||||
d
|
||||
};
|
||||
// Source Serif 4 is installed for the tests and has no ideographs.
|
||||
for d in [with(None, "Source Serif 4"), with(Some("Source Serif 4"), "Source Serif 4")] {
|
||||
assert!(gaps(&d).iter().all(|g| *g == 0.0), "{:?}", gaps(&d));
|
||||
}
|
||||
let d = with(None, "No Such East Asian Font 6591");
|
||||
let q = quarter(&d);
|
||||
// The room after each Latin character follows the face that draws it, as without a
|
||||
// `w:eastAsia` font at all (#6583).
|
||||
assert_eq!(gaps(&d), [0.0, q, 0.0, after(&d, 7), q, after(&d, 11), 0.0], "a font that isn't installed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_field_result_is_classed_by_the_text_it_shows() {
|
||||
crate::test_fonts();
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
//! A combining mark the face of its character can't draw (#7865): the character and its marks are
|
||||
//! drawn together in a face that has them all (CSS Fonts 4 §5.3, cluster matching), and with no
|
||||
//! such face the mark on its own from a face that has it, except in right-to-left and
|
||||
//! complex-script text, where it stays with its letter. Marks the face draws and pairs it composes
|
||||
//! stay with their character. Fixed test fonts: Source Serif 4 lacks U+0336 and U+0338; Source
|
||||
//! Sans 3 has U+0338; only JetBrains Mono has U+0336.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use wordcraft_doc::{CharProps, Document, Paragraph, para_block};
|
||||
use wordcraft_fonts::{FaceRef, FontDb};
|
||||
|
||||
use super::lay;
|
||||
use super::linear::assert_linear_steps;
|
||||
use crate::display::DisplayOptions;
|
||||
use crate::{ParaLayout, Placed};
|
||||
|
||||
const SERIF: &str = "Source Serif 4";
|
||||
|
||||
fn serif() -> FaceRef {
|
||||
crate::test_fonts();
|
||||
let face = wordcraft_fonts::word::resolve(SERIF, false, false).face;
|
||||
assert_eq!(face.family, SERIF, "the fixed test fonts include {SERIF}");
|
||||
face
|
||||
}
|
||||
|
||||
/// A document of one paragraph, `text` set in Source Serif 4; `cs`: with complex-script
|
||||
/// formatting (`w:cs`), its complex-script font Source Serif 4 too.
|
||||
fn doc(text: &str, cs: bool) -> Document {
|
||||
let chr = CharProps { font: Some(SERIF.into()), font_cs: Some(SERIF.into()), cs: Some(cs), size: Some(12.0), ..Default::default() };
|
||||
let mut d = Document::new();
|
||||
d.body = vec![para_block(Paragraph::with_text(text, chr))];
|
||||
d
|
||||
}
|
||||
|
||||
/// [`doc`] laid out: its paragraph and the characters drawn as missing glyphs.
|
||||
fn laid(text: &str, cs: bool) -> (Arc<ParaLayout>, Vec<char>) {
|
||||
laid_doc(&doc(text, cs))
|
||||
}
|
||||
|
||||
/// `d`, a document of one paragraph, laid out: the paragraph and the characters drawn as missing
|
||||
/// glyphs.
|
||||
fn laid_doc(d: &Document) -> (Arc<ParaLayout>, Vec<char>) {
|
||||
crate::test_fonts();
|
||||
let l = lay(d);
|
||||
let missing = l.missing_glyphs(d, &DisplayOptions::default(), None).chars.iter().map(|(c, _)| *c).collect();
|
||||
let para = l
|
||||
.pages
|
||||
.iter()
|
||||
.flat_map(|p| &p.items)
|
||||
.find_map(|it| match it {
|
||||
Placed::Lines { para, .. } => Some(para.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.expect("the paragraph is laid out");
|
||||
(para, missing)
|
||||
}
|
||||
|
||||
/// The face that draws the character at byte `at` of the paragraph.
|
||||
fn face_at(para: &ParaLayout, at: usize) -> FaceRef {
|
||||
let c = para.clusters.iter().find(|c| c.start <= at && at < c.end).expect("a cluster holds the character");
|
||||
para.styles[c.style as usize].face
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mark_its_letters_font_lacks_goes_with_its_letter_to_a_face_that_has_both() {
|
||||
let serif = serif();
|
||||
let (letter, mark) = ('∞', '\u{338}');
|
||||
assert!(serif.covers(letter) && !serif.covers(mark), "{SERIF} has {letter} and lacks U+0338");
|
||||
let text = format!("x {letter}{mark} y");
|
||||
let (para, missing) = laid(&text, false);
|
||||
assert!(missing.is_empty(), "nothing is drawn as a missing glyph, but {missing:?} were");
|
||||
let at = text.find(letter).expect("the letter is in the text");
|
||||
let face = face_at(¶, at);
|
||||
assert_eq!(face.id(), face_at(¶, at + letter.len_utf8()).id(), "the letter and its mark are drawn in one face");
|
||||
assert!(face.covers(letter) && face.covers(mark), "that face has both");
|
||||
assert_eq!(face_at(¶, 0).id(), serif.id(), "the text before stays in the run's font");
|
||||
assert_eq!(face_at(¶, text.len() - 1).id(), serif.id(), "the text after goes back to the run's font");
|
||||
}
|
||||
|
||||
/// In small capitals a mark is set at the size of the lower-case letter it belongs to, so the
|
||||
/// letter and its marks still go together to a face that has them all, also when the run's font has
|
||||
/// the first mark and lacks the second.
|
||||
#[test]
|
||||
fn in_small_capitals_a_letter_and_its_marks_go_together_to_a_face_that_has_them_all() {
|
||||
let serif = serif();
|
||||
let (letter, has, lacks) = ('x', '\u{301}', '\u{336}');
|
||||
assert!(serif.covers(letter) && serif.covers(has) && !serif.covers(lacks), "{SERIF} has x and U+0301 and lacks U+0336");
|
||||
let text: String = [letter, has, lacks].iter().collect();
|
||||
let chr = CharProps { font: Some(SERIF.into()), size: Some(12.0), small_caps: Some(true), ..Default::default() };
|
||||
let mut d = Document::new();
|
||||
d.body = vec![para_block(Paragraph::with_text(&text, chr))];
|
||||
let (para, missing) = laid_doc(&d);
|
||||
assert!(missing.is_empty(), "nothing is drawn as a missing glyph, but {missing:?} were");
|
||||
let style_at = |at: usize| para.clusters.iter().find(|c| c.start <= at && at < c.end).expect("a cluster holds the character").style;
|
||||
let face = face_at(¶, 0);
|
||||
assert!(face.covers(lacks), "the letter is drawn in a face that has U+0336");
|
||||
for (at, c) in text.char_indices().skip(1) {
|
||||
assert_eq!(face_at(¶, at).id(), face.id(), "U+{:04X} is drawn in its letter's face", c as u32);
|
||||
assert_eq!(style_at(at), style_at(0), "U+{:04X} is set at its letter's size", c as u32);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mark_the_font_composes_with_its_letter_stays_in_the_run_font() {
|
||||
let serif = serif();
|
||||
// The font has no U+0338, but the shaper draws = with it as ≠, which the font has.
|
||||
assert!(!serif.covers('\u{338}') && serif.covers('≠'), "{SERIF} lacks U+0338 and has ≠");
|
||||
let text = "x =\u{338} y";
|
||||
let (para, missing) = laid(text, false);
|
||||
assert!(missing.is_empty(), "nothing is drawn as a missing glyph, but {missing:?} were");
|
||||
for (at, c) in text.char_indices() {
|
||||
assert_eq!(face_at(¶, at).id(), serif.id(), "U+{:04X} stays in the run's font", c as u32);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mark_no_face_draws_with_its_letter_is_drawn_from_a_face_that_has_it() {
|
||||
let serif = serif();
|
||||
let (letter, mark) = ('ǹ', '\u{336}');
|
||||
let db = FontDb::global();
|
||||
assert!(serif.covers(letter) && !serif.covers(mark), "{SERIF} has {letter} and lacks U+0336");
|
||||
assert!(db.fallback_for_run(&[letter, mark], serif.id(), false, false).is_none(), "no face has both");
|
||||
assert!(db.fallback_for(mark, serif.id()).is_some(), "a face has U+0336");
|
||||
let text = format!("{letter}{mark}");
|
||||
let (para, missing) = laid(&text, false);
|
||||
assert!(missing.is_empty(), "the mark is drawn, but {missing:?} were missing glyphs");
|
||||
assert_eq!(face_at(¶, 0).id(), serif.id(), "the letter stays in the run's font");
|
||||
assert!(face_at(¶, letter.len_utf8()).covers(mark), "the mark comes from a face that has it");
|
||||
}
|
||||
|
||||
/// In complex-script text a mark no face draws with its letter stays in the letter's face, so it is
|
||||
/// never split from its letter (Arabic harakat would lose their place on it).
|
||||
#[test]
|
||||
fn in_complex_script_text_a_mark_no_face_draws_with_its_letter_stays_with_it() {
|
||||
let serif = serif();
|
||||
let (letter, mark) = ('ǹ', '\u{336}');
|
||||
assert!(FontDb::global().fallback_for_run(&[letter, mark], serif.id(), false, false).is_none(), "no face has both");
|
||||
let (para, _) = laid(&format!("{letter}{mark}"), true);
|
||||
assert_eq!(face_at(¶, 0).id(), serif.id(), "the letter stays in the run's font");
|
||||
assert_eq!(face_at(¶, letter.len_utf8()).id(), serif.id(), "the mark stays with its letter");
|
||||
}
|
||||
|
||||
/// A letter followed by many marks no face draws with it, in complex-script text, where they stay
|
||||
/// with it: their cluster is matched once, not again at every mark, which made the layout quadratic
|
||||
/// in their number.
|
||||
#[test]
|
||||
fn a_long_run_of_marks_after_one_letter_lays_out_in_linear_time() {
|
||||
let serif = serif();
|
||||
let (letter, mark) = ('ǹ', '\u{336}');
|
||||
assert!(FontDb::global().fallback_for_run(&[letter, mark], serif.id(), false, false).is_none(), "no face has both");
|
||||
let text = |n: usize| std::iter::once(letter).chain(std::iter::repeat_n(mark, n)).collect::<String>();
|
||||
assert_linear_steps("marks after one letter", 200, |n| doc(&text(n), true), |d| drop(std::hint::black_box(lay(d))));
|
||||
}
|
||||
@@ -89,6 +89,20 @@ fn a_joined_paragraphs_drawings_are_relative_to_the_shared_line() {
|
||||
assert!(boxed < alpha + 12.0, "the box's text at {boxed} is below the shared line at {alpha}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_margin_anchored_frame_in_a_cell_joins_after_a_hidden_mark() {
|
||||
let mut d = Document::from_text("Alpha\nOmega");
|
||||
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().mark.hidden = Some(true);
|
||||
d.para_mut(StoryRef::Body, &Path::top(1)).unwrap().props.frame =
|
||||
Some(TextFrame { h_anchor: "page".into(), v_anchor: "margin".into(), ..Default::default() });
|
||||
in_cell(&mut d);
|
||||
|
||||
let l = lay(&d);
|
||||
let alpha = top_of(&l, &Path(vec![0, 0, 0, 0]));
|
||||
let omega = top_of(&l, &Path(vec![0, 0, 0, 1]));
|
||||
assert!((omega - alpha).abs() < 1.0, "framed paragraph should share hidden-mark line: {alpha} vs {omega}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_text_frame_after_a_hidden_mark_is_not_joined() {
|
||||
// A framed paragraph is placed apart, so it shares no line with the one before: its number is
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
//! A long word broken by letters: the letter ending the line is measured without its kerning
|
||||
//! pair with the letter that goes on to the next line (Word, a line's width swept a twip at a
|
||||
//! time: the letters before a broken kerning pair fit only where they fit on their own).
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_word_broken_by_letters_ends_without_its_kerning_pair() {
|
||||
let text = "AVAVAVAVAVAVAVAVAVAV";
|
||||
let doc = |indent_right: f32| {
|
||||
let mut d = Document::from_text(text);
|
||||
Arc::make_mut(&mut d.styles).default_chr.kern = Some(1.0);
|
||||
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| p.indent_right = Some(indent_right)).unwrap();
|
||||
d
|
||||
};
|
||||
// The word on one line: the first five letters' width with the "AV" pair after the fifth
|
||||
// and without it.
|
||||
let l = lay(&doc(0.0));
|
||||
let para = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para.clone()) } else { None }).unwrap();
|
||||
let paired: f32 = para.clusters[..5].iter().map(|c| c.adv).sum();
|
||||
let alone = paired - para.clusters[4].kern;
|
||||
assert!(alone - paired > 0.1, "the test font kerns \"AV\": {paired} vs {alone}");
|
||||
// A line between the two takes four letters, as in Word; with the pair it took five.
|
||||
let got = body_lines(&lay(&doc(468.0 - (paired + alone) / 2.0)), text);
|
||||
assert_eq!(got.first().map(String::as_str), Some("AVAV"), "{got:?}");
|
||||
// A line as wide as the five letters alone takes them.
|
||||
let got = body_lines(&lay(&doc(468.0 - alone - 0.004)), text);
|
||||
assert_eq!(got.first().map(String::as_str), Some("AVAVA"), "{got:?}");
|
||||
}
|
||||
|
||||
/// Inter under the family name "Kernx" with its `GPOS` hidden and an old-style `kern` table that
|
||||
/// kerns "AV" by `units` (and nothing else): a shaper splits such a pair between the two letters,
|
||||
/// half in the first one's advance and half in the second one's advance and offset.
|
||||
fn legacy_kern_family(units: i16) -> &'static str {
|
||||
const FAMILY: &str = "Kernx";
|
||||
let inter = wordcraft_fonts::word::resolve("Inter", false, false).face;
|
||||
let (a, v) = (inter.glyph_for('A') as u16, inter.glyph_for('V') as u16);
|
||||
let src = inter.data().to_vec();
|
||||
let u16_at = |d: &[u8], o: usize| u16::from_be_bytes([d[o], d[o + 1]]) as usize;
|
||||
let u32_at = |d: &[u8], o: usize| u32::from_be_bytes([d[o], d[o + 1], d[o + 2], d[o + 3]]) as usize;
|
||||
// The tables, `GPOS` renamed so no shaper reads it, and the new `kern` table.
|
||||
let mut tables: Vec<([u8; 4], Vec<u8>)> = (0..u16_at(&src, 4))
|
||||
.map(|i| {
|
||||
let r = 12 + 16 * i;
|
||||
let tag: [u8; 4] = src[r..r + 4].try_into().unwrap();
|
||||
let tag = if &tag == b"GPOS" { *b"XPOS" } else { tag };
|
||||
(tag, src[u32_at(&src, r + 8)..u32_at(&src, r + 8) + u32_at(&src, r + 12)].to_vec())
|
||||
})
|
||||
.collect();
|
||||
let mut kern = Vec::new();
|
||||
for x in [0u16, 1, 0, 20, 0x0001, 1, 6, 0, 0, a, v] {
|
||||
kern.extend(x.to_be_bytes());
|
||||
}
|
||||
kern.extend(units.to_be_bytes());
|
||||
tables.push((*b"kern", kern));
|
||||
tables.sort_by_key(|t| t.0);
|
||||
// The font file again: its header, the table records, then the tables (4-byte aligned).
|
||||
let n = tables.len();
|
||||
let mut data = src[..12].to_vec();
|
||||
data[4..6].copy_from_slice(&(n as u16).to_be_bytes());
|
||||
let mut at = 12 + 16 * n;
|
||||
let mut body = Vec::new();
|
||||
for (tag, t) in &tables {
|
||||
data.extend(tag);
|
||||
data.extend(0u32.to_be_bytes());
|
||||
data.extend((at as u32).to_be_bytes());
|
||||
data.extend((t.len() as u32).to_be_bytes());
|
||||
body.extend(t);
|
||||
while body.len() % 4 != 0 {
|
||||
body.push(0);
|
||||
}
|
||||
at = 12 + 16 * n + body.len();
|
||||
}
|
||||
data.extend(body);
|
||||
// The family name, in the name table's UTF-16 and single-byte records alike.
|
||||
let name = tables.iter().take_while(|t| &t.0 != b"name").map(|t| t.1.len().div_ceil(4) * 4).sum::<usize>() + 12 + 16 * n;
|
||||
let len = tables.iter().find(|t| &t.0 == b"name").map_or(0, |t| t.1.len());
|
||||
let wide = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::<Vec<u8>>();
|
||||
for (from, to) in [(wide("Inter"), wide(FAMILY)), (b"Inter".to_vec(), FAMILY.as_bytes().to_vec())] {
|
||||
for i in name..name + len - from.len() {
|
||||
if data[i..i + from.len()] == from[..] {
|
||||
data[i..i + from.len()].copy_from_slice(&to);
|
||||
}
|
||||
}
|
||||
}
|
||||
wordcraft_fonts::FontDb::global().add_font(data);
|
||||
FAMILY
|
||||
}
|
||||
|
||||
/// A letter ending a line whose kerning pair with the letter before it the shaper split between
|
||||
/// them keeps that pair: only its pair with the letter going on to the next line is dropped
|
||||
/// (Word for Windows, a font with only an old-style `kern` table: "...3Vy" of a base64 token on
|
||||
/// one line, where the "y" carrying half the "Vy" pair measured it wider and moved it on).
|
||||
#[test]
|
||||
fn a_letter_ending_a_line_keeps_its_pair_with_the_letter_before() {
|
||||
crate::test_fonts();
|
||||
let text = "AVAVAVAVAVAVAVAVAVAV";
|
||||
let family = legacy_kern_family(-300);
|
||||
let doc = |indent_right: f32| {
|
||||
let mut d = Document::from_text(text);
|
||||
let st = Arc::make_mut(&mut d.styles);
|
||||
st.default_chr.kern = Some(1.0);
|
||||
st.default_chr.font = Some(family.into());
|
||||
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| p.indent_right = Some(indent_right)).unwrap();
|
||||
d
|
||||
};
|
||||
let l = lay(&doc(0.0));
|
||||
let para = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para.clone()) } else { None }).unwrap();
|
||||
// "AVAVAV" on a line: the "AV" pairs in it kerned, the "VA" after it not kerned at all.
|
||||
let six: f32 = para.clusters[..6].iter().map(|c| c.adv).sum();
|
||||
assert!(para.clusters[0].kern < -0.5, "the test font kerns \"AV\": {}", para.clusters[0].kern);
|
||||
let got = body_lines(&lay(&doc(468.0 - six - 0.004)), text);
|
||||
assert_eq!(got.first().map(String::as_str), Some("AVAVAV"), "{got:?}");
|
||||
}
|
||||
|
||||
/// A ligature's kerning pair with the letter after it belongs on the ligature's last cluster, not
|
||||
/// on its head (#8618): a forced character wrap inside the ligature must not subtract the pair
|
||||
/// after the whole ligature, and a line ending after the ligature drops that pair.
|
||||
#[test]
|
||||
fn a_ligatures_kerning_pair_sits_on_its_last_cluster() {
|
||||
crate::test_fonts();
|
||||
let text = "flYflYflYflY";
|
||||
let doc = |indent_right: f32| {
|
||||
let mut d = Document::from_text(text);
|
||||
let st = Arc::make_mut(&mut d.styles);
|
||||
st.default_chr.font = Some("Source Serif 4".into());
|
||||
st.default_chr.size = Some(14.0);
|
||||
st.default_chr.kern = Some(1.0);
|
||||
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| p.indent_right = Some(indent_right)).unwrap();
|
||||
d
|
||||
};
|
||||
let l = lay(&doc(0.0));
|
||||
let para = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para.clone()) } else { None }).unwrap();
|
||||
assert!(para.clusters[0].g1 > para.clusters[0].g0 && para.clusters[1].g1 == para.clusters[1].g0, "fixture forms an \"fl\" ligature");
|
||||
assert_eq!(para.clusters[0].kern, 0.0, "the ligature's head cluster carries no kerning pair");
|
||||
assert!(para.clusters[1].kern < -0.3, "the ligature's last cluster carries its pair with \"Y\": {}", para.clusters[1].kern);
|
||||
assert_eq!(para.clusters[3].kern, 0.0);
|
||||
let paired: f32 = para.clusters[..5].iter().map(|c| c.adv).sum();
|
||||
let alone = paired - para.clusters[4].kern;
|
||||
assert!(alone - paired > 0.3, "Source Serif 4 kerns \"fl\" + \"Y\": {paired} vs {alone}");
|
||||
// Between paired and alone: "flYfl" fits only with its pair with "Y", so "fl" wraps whole.
|
||||
let got = body_lines(&lay(&doc(468.0 - (paired + alone) / 2.0)), text);
|
||||
assert_eq!(got.first().map(String::as_str), Some("flY"), "{got:?}");
|
||||
// Wide enough for "flYfl" without the pair after it.
|
||||
let got = body_lines(&lay(&doc(468.0 - alone - 0.004)), text);
|
||||
assert_eq!(got.first().map(String::as_str), Some("flYfl"), "{got:?}");
|
||||
|
||||
// A three-letter ligature ("ffi") also puts its pair with "V" only on its last cluster.
|
||||
let mut d3 = Document::from_text("ffiV");
|
||||
let st3 = Arc::make_mut(&mut d3.styles);
|
||||
st3.default_chr.font = Some("Source Serif 4".into());
|
||||
st3.default_chr.size = Some(14.0);
|
||||
st3.default_chr.kern = Some(1.0);
|
||||
let l3 = lay(&d3);
|
||||
let p3 = l3.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para.clone()) } else { None }).unwrap();
|
||||
assert!(p3.clusters[0].g1 > p3.clusters[0].g0 && p3.clusters[1].g1 == p3.clusters[1].g0 && p3.clusters[2].g1 == p3.clusters[2].g0);
|
||||
assert_eq!(p3.clusters[0].kern, 0.0);
|
||||
assert_eq!(p3.clusters[1].kern, 0.0);
|
||||
assert!(p3.clusters[2].kern < -0.2, "last cluster of \"ffi\" carries pair with \"V\": {}", p3.clusters[2].kern);
|
||||
}
|
||||
@@ -874,6 +874,70 @@ fn a_roman_page_number_in_the_footer_stays_roman_with_the_page_count_in_the_body
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multiple_spaced_lines_leading_may_run_past_a_footer_above_the_margin() {
|
||||
// A footer reaching above the bottom margin: Word lets the leading of the page's last
|
||||
// 1.5-spaced line run past its top as into the margin, only the text has to fit, whatever the
|
||||
// footer holds. Word for Mac and Windows, a 1.5-spaced 12pt line pushed down by half a point:
|
||||
// it stays while its text ends above the footer (up to 0.4pt above), with a one-line
|
||||
// page-number footer above the margin by 6.6pt and by 28pt, with a four-line footer, and with
|
||||
// an empty exact-height 120pt paragraph. Also when the footer is the first page's own (a title
|
||||
// page footer, the other pages' footer short): the first page's footer counts there.
|
||||
use wordcraft_doc::props::LineSpacing;
|
||||
// (footer lines, their text, the title page's own footer, footer distance from the page bottom)
|
||||
let cases: [(usize, &str, bool, Option<f32>); 4] =
|
||||
[(1, "", false, None), (1, "", true, None), (1, "7", false, Some(72.0)), (4, "Footer line", false, None)];
|
||||
for (lines, text, first, from_bottom) in cases {
|
||||
let mut past_footer = 0;
|
||||
for shift in (0..28).step_by(2) {
|
||||
let mut d = Document::from_text(&"Several words wrap onto many lines of a long paragraph. ".repeat(60));
|
||||
if let Some(wordcraft_doc::Block::Para(p)) = d.body.get_mut(0).map(Arc::make_mut) {
|
||||
p.props.line_spacing = Some(LineSpacing::Multiple(1.5));
|
||||
p.props.space_before = Some(shift as f32);
|
||||
p.props.widow_control = Some(false);
|
||||
}
|
||||
let foot_paras = (0..lines)
|
||||
.map(|_| {
|
||||
let mut f = Paragraph::with_text(text, Default::default());
|
||||
if text.is_empty() {
|
||||
f.props.line_spacing = Some(LineSpacing::Exactly(120.0));
|
||||
}
|
||||
para_block(f)
|
||||
})
|
||||
.collect();
|
||||
let id = d.add_part(PartKind::Footer, foot_paras);
|
||||
if let Some(f) = from_bottom {
|
||||
d.last_section.footer = f;
|
||||
}
|
||||
if first {
|
||||
d.last_section.title_page = true;
|
||||
d.last_section.footers.first = Some(id);
|
||||
} else {
|
||||
d.last_section.footers.default = Some(id);
|
||||
}
|
||||
let l = lay(&d);
|
||||
let foot = l.pages[0].body.bottom();
|
||||
let what = format!("footer of {lines} x {text:?}, shift {shift}");
|
||||
assert!(foot < d.last_section.page_h - d.last_section.margin_bottom - 1.0, "{what}: the footer reaches above the margin: {foot}");
|
||||
let Some(Placed::Lines { y, para, l0, l1, .. }) =
|
||||
l.pages[0].items.iter().find(|i| matches!(i, Placed::Lines { story: StoryRef::Body, .. }))
|
||||
else {
|
||||
panic!("{what}: no body lines on page 1")
|
||||
};
|
||||
let (first, last, next) = (¶.lines[*l0], ¶.lines[*l1 - 1], ¶.lines[*l1]);
|
||||
let top = y + last.top - first.top;
|
||||
let text_end = top + (last.baseline - last.top) + last.text_desc;
|
||||
assert!(text_end <= foot + 0.01, "{what}: the last line's text ends at {text_end}, below the footer at {foot}");
|
||||
let next_text_end = top + last.height + (next.baseline - next.top) + next.text_desc;
|
||||
assert!(next_text_end > foot + 0.01, "{what}: the next line's text would end at {next_text_end}, above the footer at {foot}");
|
||||
if top + last.height > foot + 0.01 {
|
||||
past_footer += 1;
|
||||
}
|
||||
}
|
||||
assert!(past_footer > 0, "footer of {lines} x {text:?}: some shift should leave the last line's leading past the footer");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_ends_when_a_multiple_spaced_lines_text_no_longer_fits() {
|
||||
// Multiple spacing puts its extra leading below the text, and Word lets that leading of a
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
//! A character Times New Roman's metric twin lacks ("‒", "₽" in Liberation Serif) is drawn from
|
||||
//! a fallback face, but the line is as tall as the twin's: Times New Roman has those characters,
|
||||
//! so Word's line is as tall as Times New Roman's, not the taller UI sans.
|
||||
|
||||
use crate::{Document, LayoutCache, LayoutOptions, Placed, layout};
|
||||
|
||||
/// Inter under the family name "Tinos" (a metric twin of Times New Roman), from the bundled font
|
||||
/// so the test needs no installed font. Inter lacks "☐"; Source Sans 3 (the fallback) has it and
|
||||
/// its line is taller (1.326 em against 1.21).
|
||||
fn fake_tinos() -> &'static str {
|
||||
const FAMILY: &str = "Tinos";
|
||||
let inter = wordcraft_fonts::word::resolve("Inter", false, false).face;
|
||||
assert!(!inter.covers('☐'));
|
||||
let mut data = inter.data().to_vec();
|
||||
let u16_at = |d: &[u8], o: usize| u16::from_be_bytes([d[o], d[o + 1]]) as usize;
|
||||
let u32_at = |d: &[u8], o: usize| u32::from_be_bytes([d[o], d[o + 1], d[o + 2], d[o + 3]]) as usize;
|
||||
let (name, len) = (0..u16_at(&data, 4))
|
||||
.map(|i| 12 + 16 * i)
|
||||
.find(|&r| &data[r..r + 4] == b"name")
|
||||
.map(|r| (u32_at(&data, r + 8), u32_at(&data, r + 12)))
|
||||
.unwrap();
|
||||
let wide = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::<Vec<u8>>();
|
||||
for (from, to) in [(wide("Inter"), wide(FAMILY)), (b"Inter".to_vec(), FAMILY.as_bytes().to_vec())] {
|
||||
for i in name..name + len - from.len() {
|
||||
if data[i..i + from.len()] == from[..] {
|
||||
data[i..i + from.len()].copy_from_slice(&to);
|
||||
}
|
||||
}
|
||||
}
|
||||
wordcraft_fonts::FontDb::global().add_font(data);
|
||||
FAMILY
|
||||
}
|
||||
|
||||
fn line_height(text: &str, font: &str) -> f32 {
|
||||
let chr = wordcraft_doc::CharProps { font: Some(font.into()), size: Some(14.0), ..Default::default() };
|
||||
let mut d = Document::new();
|
||||
d.body = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text(text, chr))];
|
||||
let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default());
|
||||
l.pages.iter().flat_map(|p| &p.items).find_map(|it| if let Placed::Lines { para, .. } = it { Some(para.lines[0].height) } else { None }).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_twin_fallback_keeps_the_twins_line_height() {
|
||||
crate::test_fonts();
|
||||
let tinos = fake_tinos();
|
||||
assert_eq!(wordcraft_fonts::word::resolve(tinos, false, false).face.family, tinos, "the test font is installed under its own name");
|
||||
let plain = line_height("Aa", tinos);
|
||||
let boxed = line_height("A☐a", tinos);
|
||||
assert!((boxed - plain).abs() < 0.01, "a line with a fallback character is {boxed} pt, without it {plain} pt");
|
||||
// Other fonts keep the fallback's taller line.
|
||||
assert!(line_height("A☐a", "Inter") > line_height("Aa", "Inter") + 1.0);
|
||||
}
|
||||
@@ -107,6 +107,7 @@ fn write_attempt(doc: &Document, lay: &DocLayout, opts: &PdfOptions, pages: &[us
|
||||
objects: crate::exporter::ObjectLookup::new(doc),
|
||||
at: (0, 0),
|
||||
links: Vec::new(),
|
||||
last_link: None,
|
||||
bookmarks: std::cell::OnceCell::new(),
|
||||
};
|
||||
if let Some(o) = ex.outline(pages) {
|
||||
@@ -136,8 +137,15 @@ fn write_attempt(doc: &Document, lay: &DocLayout, opts: &PdfOptions, pages: &[us
|
||||
}
|
||||
}
|
||||
surface.finish();
|
||||
for annotation in annotations {
|
||||
kp.add_annotation(annotation);
|
||||
for (annotation, tag_slot) in annotations {
|
||||
if opts.tagged
|
||||
&& let Some((para_idx, child_idx)) = tag_slot
|
||||
{
|
||||
let annot_id = kp.add_tagged_annotation(annotation);
|
||||
ex.attach_link_annotation(para_idx, child_idx, annot_id);
|
||||
} else {
|
||||
kp.add_annotation(annotation);
|
||||
}
|
||||
}
|
||||
kp.finish();
|
||||
}
|
||||
|
||||
+72
-28
@@ -3,7 +3,7 @@ use super::glyphs::{baseline, cluster_ends, glyph_id, glyph_outlines, left_to_ri
|
||||
use super::options::{PdfError, PdfOptions};
|
||||
use super::paint::{append_path, fill, grown, norm, ok, paint_fill, pdf_line_cap, rect_path, shape_effects, shape_path};
|
||||
use super::picture::{Vector, build_vector, load_image, paint_of, vector_picture};
|
||||
use super::tags::{Role, TagEntry, figure_alt, graphic_alt, holds_picture, holds_text};
|
||||
use super::tags::{Role, TagEntry, build_tag_tree, figure_alt, graphic_alt, holds_picture, holds_text};
|
||||
use super::{
|
||||
Annotation, Arc, Artifact, ArtifactType, ClKind, ContentTag, DocLayout, DocPath, Document, Draw, FaceRef, Fill, FillRule, Font, HashMap, HashSet,
|
||||
Identifier, Image, InlineObject, ItemDisplay, KrillaGlyph, LineCap, LineEnd, LineJoin, LineStyle, LinkAnnotation, Node, NonZeroU16, Outline,
|
||||
@@ -18,6 +18,16 @@ mod objects;
|
||||
pub(crate) use objects::ObjectLookup;
|
||||
mod text;
|
||||
|
||||
pub(crate) struct LinkRect {
|
||||
pub(crate) x0: f32,
|
||||
pub(crate) y0: f32,
|
||||
pub(crate) x1: f32,
|
||||
pub(crate) y1: f32,
|
||||
pub(crate) target: String,
|
||||
/// `(para_idx, child_idx)` in `Exporter::tags` for this link's `Tag::Link` group.
|
||||
pub(crate) tag: Option<(usize, usize)>,
|
||||
}
|
||||
|
||||
pub(crate) struct Exporter<'a> {
|
||||
pub(crate) doc: &'a Document,
|
||||
pub(crate) lay: &'a DocLayout,
|
||||
@@ -42,8 +52,10 @@ pub(crate) struct Exporter<'a> {
|
||||
pub(crate) objects: ObjectLookup<'a>,
|
||||
/// Where the item being drawn is read ([`TagEntry::at`]).
|
||||
pub(crate) at: (usize, usize),
|
||||
/// Link rectangles on the current page: (x0, y0, x1, y1, target).
|
||||
pub(crate) links: Vec<(f32, f32, f32, f32, String)>,
|
||||
/// Link rectangles on the current page.
|
||||
pub(crate) links: Vec<LinkRect>,
|
||||
/// Index in `links` touched by the most recent `Draw::Glyphs` item, if any.
|
||||
pub(crate) last_link: Option<usize>,
|
||||
/// Bookmark positions by name (the first of a name wins), gathered once: looking each internal
|
||||
/// link up by walking the whole document made a long document with a linked table of contents
|
||||
/// take seconds to export.
|
||||
@@ -146,13 +158,14 @@ impl Exporter<'_> {
|
||||
e.children.push(Node::Leaf(id));
|
||||
}
|
||||
}
|
||||
Role::Figure => {
|
||||
Role::Figure(source) => {
|
||||
let id: Identifier = s.start_tagged(ContentTag::Other);
|
||||
f(self, s);
|
||||
s.end_tagged();
|
||||
let alt = alt.map(str::to_string).filter(|a| !a.is_empty()).or_else(|| Some("picture".to_string()));
|
||||
let g = TagGroup::with_children(Tag::Figure(alt), vec![Node::Leaf(id)]);
|
||||
self.tags.push(TagEntry { kind: Tag::Div.into(), children: vec![Node::Group(g)], at: self.at });
|
||||
let source = source.filter(|(_, p)| p.0.len() >= 4).map(|(st, p)| (st, p.clone()));
|
||||
self.tags.push(TagEntry { kind: Tag::Div.into(), children: vec![Node::Group(g)], source, at: self.at });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -160,7 +173,7 @@ impl Exporter<'_> {
|
||||
/// A rotated inline picture or group: turned as a whole, with each picture in it tagged on its
|
||||
/// own, so a decorative picture is an artifact while the others stay figures with their alt
|
||||
/// text. A described shape's figure keeps its description; anything else is an artifact.
|
||||
fn rotated_pictures(&mut self, s: &mut Surface, d: &Draw) {
|
||||
fn rotated_pictures(&mut self, s: &mut Surface, d: &Draw, source: Option<(StoryRef, &DocPath)>) {
|
||||
match d {
|
||||
Draw::Rotated { cx, cy, spin, items } => {
|
||||
if !ok(*cx) || !ok(*cy) {
|
||||
@@ -169,7 +182,7 @@ impl Exporter<'_> {
|
||||
let [a, b, c, d, e, f] = spin.matrix(*cx, *cy);
|
||||
s.push_transform(&Transform::from_row(a, b, c, d, e, f));
|
||||
for it in items {
|
||||
self.rotated_pictures(s, it);
|
||||
self.rotated_pictures(s, it, source);
|
||||
}
|
||||
s.pop();
|
||||
}
|
||||
@@ -178,13 +191,13 @@ impl Exporter<'_> {
|
||||
let Some(clip) = rect_path(rect) else { return };
|
||||
s.push_clip_path(&clip, &FillRule::NonZero);
|
||||
for it in items {
|
||||
self.rotated_pictures(s, it);
|
||||
self.rotated_pictures(s, it, source);
|
||||
}
|
||||
s.pop();
|
||||
}
|
||||
Draw::Image { decorative: true, .. } => self.tagged(s, Role::Artifact(ArtifactType::Other), None, |me, s| me.draw(s, d)),
|
||||
Draw::Image { alt, .. } => self.tagged(s, Role::Figure, Some(alt), |me, s| me.draw(s, d)),
|
||||
Draw::Figure { alt, draws, .. } => self.tagged(s, Role::Figure, Some(alt), |me, s| {
|
||||
Draw::Image { alt, .. } => self.tagged(s, Role::Figure(source), Some(alt), |me, s| me.draw(s, d)),
|
||||
Draw::Figure { alt, draws, .. } => self.tagged(s, Role::Figure(source), Some(alt), |me, s| {
|
||||
for d in draws {
|
||||
me.draw(s, d);
|
||||
}
|
||||
@@ -193,24 +206,62 @@ impl Exporter<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Attach a paragraph's marked-content `id` to its `Tag::Link` group when `draw` recorded a
|
||||
/// link rectangle, or directly to the paragraph entry otherwise.
|
||||
fn attach_para_link(&mut self, idx: usize, id: Identifier) {
|
||||
if let Some(li) = self.last_link.take()
|
||||
&& let Some(link) = self.links.get_mut(li)
|
||||
{
|
||||
if let Some((p_idx, c_idx)) = link.tag
|
||||
&& let Some(Node::Group(g)) = self.tags.get_mut(p_idx).and_then(|e| e.children.get_mut(c_idx))
|
||||
{
|
||||
g.push(Node::Leaf(id));
|
||||
return;
|
||||
}
|
||||
if let Some(e) = self.tags.get_mut(idx) {
|
||||
let c_idx = e.children.len();
|
||||
e.children.push(Node::Group(TagGroup::with_children(Tag::Link, vec![Node::Leaf(id)])));
|
||||
link.tag = Some((idx, c_idx));
|
||||
return;
|
||||
}
|
||||
}
|
||||
if let Some(e) = self.tags.get_mut(idx) {
|
||||
e.children.push(Node::Leaf(id));
|
||||
}
|
||||
}
|
||||
|
||||
/// Insert a link annotation's `OBJR` identifier as the first child of its `Tag::Link` group.
|
||||
pub(crate) fn attach_link_annotation(&mut self, para_idx: usize, child_idx: usize, annot_id: Identifier) {
|
||||
if let Some(Node::Group(g)) = self.tags.get_mut(para_idx).and_then(|e| e.children.get_mut(child_idx)) {
|
||||
g.children.insert(0, Node::Leaf(annot_id));
|
||||
}
|
||||
}
|
||||
|
||||
/// One draw of a paragraph's line, tagged for what it is: text as the paragraph's content
|
||||
/// (structure entry `idx`), pictures and figures on their own, anything else an artifact.
|
||||
fn line_item(&mut self, s: &mut Surface, d: &Draw, idx: usize) {
|
||||
fn line_item(&mut self, s: &mut Surface, d: &Draw, idx: usize, story: StoryRef, path: &DocPath) {
|
||||
match d {
|
||||
Draw::Glyphs { link: Some(_), .. } if self.opts.tagged && self.opts.links => {
|
||||
self.last_link = None;
|
||||
let id = s.start_tagged(ContentTag::Span(SpanTag::empty()));
|
||||
self.draw(s, d);
|
||||
s.end_tagged();
|
||||
self.attach_para_link(idx, id);
|
||||
}
|
||||
Draw::Glyphs { .. } | Draw::Turned { .. } => self.tagged(s, Role::Para(idx), None, |me, s| me.draw(s, d)),
|
||||
// A picture marked decorative: an artifact screen readers skip.
|
||||
Draw::Image { decorative: true, .. } => self.tagged(s, Role::Artifact(ArtifactType::Other), None, |me, s| me.draw(s, d)),
|
||||
Draw::Image { alt, .. } => self.tagged(s, Role::Figure, Some(alt), |me, s| me.draw(s, d)),
|
||||
Draw::Image { alt, .. } => self.tagged(s, Role::Figure(Some((story, path))), Some(alt), |me, s| me.draw(s, d)),
|
||||
// A rotated inline picture, or a rotated group holding pictures: turned as a
|
||||
// whole, each picture tagged on its own (see `rotated_pictures`).
|
||||
Draw::Rotated { items, .. } if items.iter().any(holds_picture) => self.rotated_pictures(s, d),
|
||||
Draw::Rotated { items, .. } if items.iter().any(holds_picture) => self.rotated_pictures(s, d, Some((story, path))),
|
||||
// A clip (a turned picture cut at its line, an exact-height cell's lines, a canvas's
|
||||
// members): each draw in it tagged as it would be outside it.
|
||||
Draw::Clip { rect, items } => {
|
||||
let Some(clip) = rect_path(rect) else { return };
|
||||
s.push_clip_path(&clip, &FillRule::NonZero);
|
||||
for it in items {
|
||||
self.line_item(s, it, idx);
|
||||
self.line_item(s, it, idx, story, path);
|
||||
}
|
||||
s.pop();
|
||||
}
|
||||
@@ -218,7 +269,7 @@ impl Exporter<'_> {
|
||||
// without text falls to the artifacts below.
|
||||
Draw::Rotated { items, .. } if items.iter().any(holds_text) => self.tagged(s, Role::Para(idx), None, |me, s| me.draw(s, d)),
|
||||
// An inline chart, diagram or described shape: its text is part of the figure, not the paragraph.
|
||||
Draw::Figure { alt, kind, draws: inner } => self.tagged(s, Role::Figure, Some(figure_alt(alt, *kind)), |me, s| {
|
||||
Draw::Figure { alt, kind, draws: inner } => self.tagged(s, Role::Figure(Some((story, path))), Some(figure_alt(alt, *kind)), |me, s| {
|
||||
for d in inner {
|
||||
me.draw(s, d);
|
||||
}
|
||||
@@ -267,7 +318,7 @@ impl Exporter<'_> {
|
||||
Placed::Lines { story, path, para, .. } => {
|
||||
let idx = self.entry(*story, path, para);
|
||||
for d in &draws {
|
||||
self.line_item(s, d, idx);
|
||||
self.line_item(s, d, idx, *story, path);
|
||||
}
|
||||
}
|
||||
Placed::Image { story, path, off, .. } => {
|
||||
@@ -276,7 +327,7 @@ impl Exporter<'_> {
|
||||
let role = if obj.is_some_and(InlineObject::is_decorative) || *off == usize::MAX {
|
||||
Role::Artifact(ArtifactType::Other)
|
||||
} else {
|
||||
Role::Figure
|
||||
Role::Figure(Some((*story, path)))
|
||||
};
|
||||
let alt = match obj {
|
||||
Some(InlineObject::Image { alt, .. }) => alt.clone(),
|
||||
@@ -289,7 +340,7 @@ impl Exporter<'_> {
|
||||
});
|
||||
}
|
||||
// A floating shape with a description: a figure (see `shape_figure_alt`).
|
||||
Placed::Shape { alt, .. } if !alt.is_empty() => self.tagged(s, Role::Figure, Some(alt), |me, s| {
|
||||
Placed::Shape { alt, .. } if !alt.is_empty() => self.tagged(s, Role::Figure(None), Some(alt), |me, s| {
|
||||
for d in &draws {
|
||||
me.draw(s, d);
|
||||
}
|
||||
@@ -299,7 +350,7 @@ impl Exporter<'_> {
|
||||
Some(InlineObject::Graphic { alt, .. }) => graphic_alt(alt, graphic.kind).to_string(),
|
||||
_ => graphic.kind.noun().to_string(),
|
||||
};
|
||||
self.tagged(s, Role::Figure, Some(&alt), |me, s| {
|
||||
self.tagged(s, Role::Figure(Some((*story, path))), Some(&alt), |me, s| {
|
||||
for d in &draws {
|
||||
me.draw(s, d);
|
||||
}
|
||||
@@ -337,26 +388,19 @@ impl Exporter<'_> {
|
||||
}
|
||||
_ => Tag::P.into(),
|
||||
};
|
||||
self.tags.push(TagEntry { kind, children: Vec::new(), at: self.at });
|
||||
self.tags.push(TagEntry { kind, children: Vec::new(), source: Some((story, path.clone())), at: self.at });
|
||||
let i = self.tags.len() - 1;
|
||||
self.tag_index.insert((story, path.clone()), i);
|
||||
i
|
||||
}
|
||||
|
||||
pub(crate) fn tag_tree(&mut self) -> TagTree {
|
||||
let mut tree = TagTree::new().with_lang(self.doc.styles.default_chr.lang.clone());
|
||||
// In reading order: a floating object drawn over the text after it is read after its
|
||||
// anchor (#5534). The sort is stable, so what is read at one place keeps its order.
|
||||
let mut tags = std::mem::take(&mut self.tags);
|
||||
tags.sort_by_key(|e| e.at);
|
||||
self.tag_index.clear();
|
||||
for e in tags {
|
||||
if e.children.is_empty() {
|
||||
continue;
|
||||
}
|
||||
tree.push(TagGroup::with_children(e.kind, e.children));
|
||||
}
|
||||
tree
|
||||
build_tag_tree(self.doc, tags)
|
||||
}
|
||||
|
||||
/// The watermark text stretched over its box (Word's `v:textpath fitshape`): its advance across
|
||||
|
||||
@@ -31,7 +31,9 @@ impl Exporter<'_> {
|
||||
}
|
||||
None => self.glyphs(s, face, *size, glyphs, paint, (text, ranges)),
|
||||
}
|
||||
if let Some(l) = link {
|
||||
if self.opts.links
|
||||
&& let Some(l) = link
|
||||
{
|
||||
self.link_rect(face, *size, glyphs, l);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,24 +53,22 @@ impl Exporter<'_> {
|
||||
None
|
||||
}
|
||||
|
||||
pub(crate) fn annotations(&self, fit: Fit) -> Vec<Annotation> {
|
||||
pub(super) fn link_target(&self, target: &str) -> Option<Target> {
|
||||
if let Some(name) = target.strip_prefix('#') {
|
||||
self.bookmark(name).map(|(page, x, y)| Target::Destination(XyzDestination::new(page, Point::from_xy(x, y)).into()))
|
||||
} else {
|
||||
// Unsafe targets (javascript:, file:, shares, other schemes) get no link; the text stays.
|
||||
write::uri_target(target)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn annotations(&self, fit: Fit) -> Vec<(Annotation, Option<(usize, usize)>)> {
|
||||
let mut v = Vec::new();
|
||||
for (x0, y0, x1, y1, target) in &self.links {
|
||||
let ((x0, y0), (x1, y1)) = (fit.point(*x0, *y0), fit.point(*x1, *y1));
|
||||
for link in &self.links {
|
||||
let ((x0, y0), (x1, y1)) = (fit.point(link.x0, link.y0), fit.point(link.x1, link.y1));
|
||||
let Some(rect) = krilla::geom::Rect::from_ltrb(x0, y0, x1, y1) else { continue };
|
||||
let t = if let Some(name) = target.strip_prefix('#') {
|
||||
match self.bookmark(name) {
|
||||
Some((page, x, y)) => Target::Destination(XyzDestination::new(page, Point::from_xy(x, y)).into()),
|
||||
None => continue,
|
||||
}
|
||||
} else {
|
||||
// Unsafe targets (javascript:, file:, shares, other schemes) get no link; the text stays.
|
||||
match write::uri_target(target) {
|
||||
Some(t) => t,
|
||||
None => continue,
|
||||
}
|
||||
};
|
||||
v.push(Annotation::new_link(LinkAnnotation::new(rect, t), Some(target.clone())));
|
||||
let Some(t) = self.link_target(&link.target) else { continue };
|
||||
v.push((Annotation::new_link(LinkAnnotation::new(rect, t), Some(link.target.clone())), link.tag));
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
@@ -158,25 +158,41 @@ impl Exporter<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a link's `Link` group is still the last content of its paragraph, so more linked text
|
||||
/// can join it without being read ahead of unlinked text drawn since. Untagged links always continue.
|
||||
fn link_run_continues(&self, tag: Option<(usize, usize)>) -> bool {
|
||||
match tag {
|
||||
None => true,
|
||||
Some((p, c)) => self.tags.get(p).is_some_and(|e| e.children.len() == c + 1),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn link_rect(&mut self, face: &FaceRef, size: f32, glyphs: &[(u32, f32, f32)], link: &str) {
|
||||
let (Some(first), Some(last)) = (glyphs.first(), glyphs.last()) else { return };
|
||||
let adv = face.advance(last.0) as f32 * size / face.upem.max(1.0) as f32;
|
||||
let (x0, x1) = (first.1.min(last.1), first.1.max(last.1) + adv);
|
||||
let (y0, y1) = (first.2 - size * 0.85, first.2 + size * 0.25);
|
||||
if ![x0, x1, y0, y1].iter().all(|v| ok(*v)) {
|
||||
if ![x0, x1, y0, y1].iter().all(|v| ok(*v)) || x0 >= x1 || y0 >= y1 {
|
||||
return;
|
||||
}
|
||||
if self.link_target(link).is_none() {
|
||||
return;
|
||||
}
|
||||
let continues = self.links.last().is_some_and(|prev| self.link_run_continues(prev.tag));
|
||||
if let Some(prev) = self.links.last_mut()
|
||||
&& prev.4 == link
|
||||
&& (prev.1 - y0).abs() < 0.5
|
||||
&& x0 - prev.2 < size
|
||||
&& prev.target == link
|
||||
&& (prev.y0 - y0).abs() < 0.5
|
||||
&& x0 - prev.x1 < size
|
||||
&& continues
|
||||
{
|
||||
prev.0 = prev.0.min(x0);
|
||||
prev.2 = prev.2.max(x1);
|
||||
prev.x0 = prev.x0.min(x0);
|
||||
prev.x1 = prev.x1.max(x1);
|
||||
self.last_link = Some(self.links.len() - 1);
|
||||
return;
|
||||
}
|
||||
if self.links.len() < 10_000 {
|
||||
self.links.push((x0, y0, x1, y1, link.to_string()));
|
||||
self.links.push(super::LinkRect { x0, y0, x1, y1, target: link.to_string(), tag: None });
|
||||
self.last_link = Some(self.links.len() - 1);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
pub mod imposition;
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::num::NonZeroU16;
|
||||
use std::num::{NonZeroU16, NonZeroU32};
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_metafile::{Picture, PlacedItem};
|
||||
@@ -42,7 +42,7 @@ use krilla::outline::{Outline, OutlineNode};
|
||||
use krilla::page::PageSettings;
|
||||
use krilla::paint::{Fill, FillRule, LineCap, LineJoin, Stroke, StrokeDash};
|
||||
use krilla::surface::Surface;
|
||||
use krilla::tagging::{Artifact, ArtifactType, ContentTag, Identifier, Node, SpanTag, Tag, TagGroup, TagKind, TagTree};
|
||||
use krilla::tagging::{Artifact, ArtifactType, ContentTag, Identifier, Node, SpanTag, TableHeaderScope, Tag, TagGroup, TagKind, TagTree};
|
||||
use krilla::text::{Font, GlyphId, KrillaGlyph};
|
||||
use wordcraft_doc::graphic::GraphicKind;
|
||||
use wordcraft_doc::para::{InlineObject, ShapeKind};
|
||||
|
||||
+162
-4
@@ -1,4 +1,4 @@
|
||||
use super::{ArtifactType, Draw, GraphicKind, Node, TagKind};
|
||||
use super::{ArtifactType, DocPath, Document, Draw, GraphicKind, Node, NonZeroU32, StoryRef, TableHeaderScope, Tag, TagGroup, TagKind, TagTree};
|
||||
|
||||
/// A chart's or diagram's alt text: its own, else what it is ("chart", "diagram").
|
||||
pub(crate) fn graphic_alt(alt: &str, kind: GraphicKind) -> &str {
|
||||
@@ -36,6 +36,8 @@ pub(crate) fn figure_alt(alt: &str, kind: Option<GraphicKind>) -> &str {
|
||||
pub(crate) struct TagEntry {
|
||||
pub(crate) kind: TagKind,
|
||||
pub(crate) children: Vec<Node>,
|
||||
/// Paragraph `(story, path)` this entry belongs to, used to nest table cell entries under `Table`/`TR`/`TH` or `TD`.
|
||||
pub(crate) source: Option<(StoryRef, DocPath)>,
|
||||
/// Where it is first read: the page (in the order pages are drawn) and the place there of
|
||||
/// the item it came from (`Page::reading`). The tree is in this order, not the drawing order.
|
||||
pub(crate) at: (usize, usize),
|
||||
@@ -43,13 +45,169 @@ pub(crate) struct TagEntry {
|
||||
|
||||
/// What the content being drawn is, for tagging.
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
pub(crate) enum Role {
|
||||
pub(crate) enum Role<'a> {
|
||||
/// Paragraph content of the structure entry at this index.
|
||||
Para(usize),
|
||||
/// Header/footer, decorations: not part of the structure.
|
||||
Artifact(ArtifactType),
|
||||
/// A floating picture (its own Figure).
|
||||
Figure,
|
||||
/// A figure (its own `Figure`), optionally anchored to `(story, path)`.
|
||||
Figure(Option<(StoryRef, &'a DocPath)>),
|
||||
}
|
||||
|
||||
enum StructNode {
|
||||
Leaf(TagGroup),
|
||||
Table(TableNode),
|
||||
}
|
||||
|
||||
struct TableNode {
|
||||
story: StoryRef,
|
||||
path: DocPath,
|
||||
rows: Vec<RowNode>,
|
||||
}
|
||||
|
||||
struct RowNode {
|
||||
index: usize,
|
||||
cells: Vec<CellNode>,
|
||||
}
|
||||
|
||||
struct CellNode {
|
||||
index: usize,
|
||||
children: Vec<StructNode>,
|
||||
}
|
||||
|
||||
/// Build the PDF structure tree, nesting table cell entries under `Table` -> `TR` -> `TH` / `TD`.
|
||||
pub(crate) fn build_tag_tree(doc: &Document, tags: Vec<TagEntry>) -> TagTree {
|
||||
let mut roots = Vec::new();
|
||||
for e in tags {
|
||||
let group = (!e.children.is_empty()).then(|| TagGroup::with_children(e.kind, e.children));
|
||||
match (e.source, group) {
|
||||
// A blank cell still gets its TD/TH, so the row keeps every column's position.
|
||||
(Some((story, path)), group) if path.0.len() >= 4 => insert_into_nodes(&mut roots, story, &path, group),
|
||||
(_, Some(group)) => roots.push(StructNode::Leaf(group)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut tree = TagTree::new().with_lang(doc.styles.default_chr.lang.clone());
|
||||
for node in roots {
|
||||
tree.push(into_tag_group(doc, node));
|
||||
}
|
||||
tree
|
||||
}
|
||||
|
||||
fn insert_into_nodes(mut nodes: &mut Vec<StructNode>, story: StoryRef, path: &DocPath, group: Option<TagGroup>) {
|
||||
let mut k = 0usize;
|
||||
while k.saturating_add(3) < path.0.len() {
|
||||
let Some(prefix) = path.0.get(..=k) else { break };
|
||||
let Some(&row_raw) = path.0.get(k + 1) else { break };
|
||||
let Some(&cell_raw) = path.0.get(k + 2) else { break };
|
||||
let table_path = DocPath(prefix.to_vec());
|
||||
let row_idx = row_raw as usize;
|
||||
let cell_idx = cell_raw as usize;
|
||||
|
||||
let table_pos = nodes.iter().rposition(|n| matches!(n, StructNode::Table(t) if t.story == story && t.path == table_path));
|
||||
let table_pos = match table_pos {
|
||||
Some(pos) => pos,
|
||||
None => {
|
||||
nodes.push(StructNode::Table(TableNode { story, path: table_path, rows: Vec::new() }));
|
||||
nodes.len() - 1
|
||||
}
|
||||
};
|
||||
let Some(StructNode::Table(table)) = nodes.get_mut(table_pos) else { return };
|
||||
|
||||
let row_pos = match table.rows.binary_search_by_key(&row_idx, |r| r.index) {
|
||||
Ok(pos) => pos,
|
||||
Err(pos) => {
|
||||
table.rows.insert(pos, RowNode { index: row_idx, cells: Vec::new() });
|
||||
pos
|
||||
}
|
||||
};
|
||||
let Some(row) = table.rows.get_mut(row_pos) else { return };
|
||||
|
||||
let cell_pos = match row.cells.binary_search_by_key(&cell_idx, |c| c.index) {
|
||||
Ok(pos) => pos,
|
||||
Err(pos) => {
|
||||
row.cells.insert(pos, CellNode { index: cell_idx, children: Vec::new() });
|
||||
pos
|
||||
}
|
||||
};
|
||||
let Some(cell) = row.cells.get_mut(cell_pos) else { return };
|
||||
|
||||
nodes = &mut cell.children;
|
||||
k = k.saturating_add(3);
|
||||
}
|
||||
if let Some(group) = group {
|
||||
nodes.push(StructNode::Leaf(group));
|
||||
}
|
||||
}
|
||||
|
||||
fn into_tag_group(doc: &Document, node: StructNode) -> TagGroup {
|
||||
match node {
|
||||
StructNode::Leaf(g) => g,
|
||||
StructNode::Table(t) => {
|
||||
let doc_table = doc.table(t.story, &t.path);
|
||||
// Only the unbroken run of header rows at the top of the table are headers, as layout
|
||||
// counts them (`take_while(|r| r.props.header)`); a row marked as a header further down
|
||||
// is a body row, so its cells get TD and not TH.
|
||||
let header_rows = doc_table.map(|dt| dt.rows.iter().take_while(|r| r.props.header).count()).unwrap_or(0);
|
||||
let row_nodes = t
|
||||
.rows
|
||||
.into_iter()
|
||||
.map(|r| {
|
||||
let doc_row = doc_table.and_then(|dt| dt.rows.get(r.index));
|
||||
let is_header = r.index < header_rows;
|
||||
let cell_nodes = r
|
||||
.cells
|
||||
.into_iter()
|
||||
.map(|c| {
|
||||
let doc_cell = doc_row.and_then(|dr| dr.cells.get(c.index));
|
||||
let col_span = doc_cell.and_then(|dc| NonZeroU32::new(dc.span() as u32)).filter(|n| n.get() > 1);
|
||||
let row_span =
|
||||
doc_table.and_then(|dt| cell_row_span(dt, r.index, c.index)).and_then(NonZeroU32::new).filter(|n| n.get() > 1);
|
||||
let tag: TagKind = if is_header {
|
||||
Tag::TH(TableHeaderScope::Column).with_col_span(col_span).with_row_span(row_span).into()
|
||||
} else {
|
||||
Tag::TD.with_col_span(col_span).with_row_span(row_span).into()
|
||||
};
|
||||
let children = c.children.into_iter().map(|ch| Node::Group(into_tag_group(doc, ch))).collect();
|
||||
Node::Group(TagGroup::with_children(tag, children))
|
||||
})
|
||||
.collect();
|
||||
Node::Group(TagGroup::with_children(Tag::TR, cell_nodes))
|
||||
})
|
||||
.collect();
|
||||
TagGroup::with_children(Tag::Table, row_nodes)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn cell_row_span(table: &wordcraft_doc::Table, row_idx: usize, cell_idx: usize) -> Option<u32> {
|
||||
let row = table.rows.get(row_idx)?;
|
||||
let cell = row.cells.get(cell_idx)?;
|
||||
if cell.props.vmerge != wordcraft_doc::props::VMerge::Restart {
|
||||
return None;
|
||||
}
|
||||
let grid_col = row.first_grid().saturating_add(row.cells.get(..cell_idx)?.iter().map(wordcraft_doc::Cell::span).sum::<usize>());
|
||||
let mut span = 1u32;
|
||||
for next_row in table.rows.get(row_idx.saturating_add(1)..)? {
|
||||
let mut g = next_row.first_grid();
|
||||
let mut matched = false;
|
||||
for nc in &next_row.cells {
|
||||
if g == grid_col && nc.props.vmerge == wordcraft_doc::props::VMerge::Continue {
|
||||
matched = true;
|
||||
break;
|
||||
}
|
||||
g = g.saturating_add(nc.span());
|
||||
if g > grid_col {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if matched {
|
||||
span = span.saturating_add(1);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
(span > 1).then_some(span)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -1946,6 +1946,7 @@ fn bookmark_destination_is_the_page_of_its_start() {
|
||||
objects: crate::exporter::ObjectLookup::new(&d),
|
||||
at: (0, 0),
|
||||
links: Vec::new(),
|
||||
last_link: None,
|
||||
bookmarks: std::cell::OnceCell::new(),
|
||||
};
|
||||
let (page, x, y) = ex.bookmark("target").unwrap();
|
||||
@@ -3709,3 +3710,176 @@ fn chart_and_equation_text_keep_their_pdf_bytes() {
|
||||
["B", "o", "d", "y", " ", "t", "e", "x", "R", "v", "n", "u", "2", "0", "4", "+", "1", equation_x].into_iter().map(String::from).collect();
|
||||
assert_eq!(shown, expected, "math face: {}", math_face.family);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tables_are_tagged_with_table_tr_th_and_td() {
|
||||
use wordcraft_doc::{Cell, Row, Table, props::RowProps};
|
||||
let mut d = Document::from_text("A table.");
|
||||
let header = Row {
|
||||
props: RowProps { header: true, ..Default::default() },
|
||||
cells: vec![Cell::with_text("Head"), Cell::with_text("Col2")],
|
||||
..Default::default()
|
||||
};
|
||||
let body = Row { cells: vec![Cell::with_text("Cell10"), Cell::with_text("Cell11")], ..Default::default() };
|
||||
let t = Table { grid: vec![120.0, 120.0], rows: vec![header, body], ..Default::default() };
|
||||
d.body.push(Arc::new(wordcraft_doc::Block::Table(t)));
|
||||
let raw = String::from_utf8_lossy(&export(&d, &PdfOptions { tagged: true, compress: false, ..Default::default() }).unwrap()).into_owned();
|
||||
assert!(raw.contains("/S/Table") || raw.contains("/S /Table"), "missing /S /Table in:\n{raw}");
|
||||
assert!(raw.contains("/S/TR") || raw.contains("/S /TR"), "missing /S /TR in:\n{raw}");
|
||||
assert!(raw.contains("/S/TH") || raw.contains("/S /TH"), "missing /S /TH in:\n{raw}");
|
||||
assert!(raw.contains("/S/TD") || raw.contains("/S /TD"), "missing /S /TD in:\n{raw}");
|
||||
assert!(raw.contains("/Scope/Column") || raw.contains("/Scope /Column"), "missing /Scope /Column on TH");
|
||||
}
|
||||
|
||||
/// Only the run of header rows at the top of the table are headers, as layout counts them: a
|
||||
/// header-flagged row further down is a body row, so its cells are TD and not TH.
|
||||
#[test]
|
||||
fn a_header_row_below_the_top_of_the_table_is_tagged_td() {
|
||||
use wordcraft_doc::{Cell, Row, Table, props::RowProps};
|
||||
let mut d = Document::from_text("A table.");
|
||||
let header = Row {
|
||||
props: RowProps { header: true, ..Default::default() },
|
||||
cells: vec![Cell::with_text("Head"), Cell::with_text("Col2")],
|
||||
..Default::default()
|
||||
};
|
||||
let body = Row { cells: vec![Cell::with_text("Cell10"), Cell::with_text("Cell11")], ..Default::default() };
|
||||
let later_header = Row {
|
||||
props: RowProps { header: true, ..Default::default() },
|
||||
cells: vec![Cell::with_text("Mid"), Cell::with_text("Mid2")],
|
||||
..Default::default()
|
||||
};
|
||||
let t = Table { grid: vec![120.0, 120.0], rows: vec![header, body, later_header], ..Default::default() };
|
||||
d.body.push(Arc::new(wordcraft_doc::Block::Table(t)));
|
||||
let raw = String::from_utf8_lossy(&export(&d, &PdfOptions { tagged: true, compress: false, ..Default::default() }).unwrap()).into_owned();
|
||||
let count = |tag: &str| raw.matches(&format!("/S/{tag}")).count() + raw.matches(&format!("/S /{tag}")).count();
|
||||
assert_eq!(count("TH"), 2, "only the top header row's cells are TH");
|
||||
assert_eq!(count("TD"), 4, "the body row and the later header row are TD");
|
||||
}
|
||||
|
||||
/// A blank cell still gets its TD or TH, so a filled cell after it keeps its column.
|
||||
#[test]
|
||||
fn blank_table_cells_keep_their_td_and_th() {
|
||||
use wordcraft_doc::{Cell, Row, Table, props::RowProps};
|
||||
let mut d = Document::from_text("A table.");
|
||||
let header = Row {
|
||||
props: RowProps { header: true, ..Default::default() },
|
||||
cells: vec![Cell::with_text(""), Cell::with_text("Col2")],
|
||||
..Default::default()
|
||||
};
|
||||
let body = Row { cells: vec![Cell::with_text(""), Cell::with_text("Cell11")], ..Default::default() };
|
||||
let t = Table { grid: vec![120.0, 120.0], rows: vec![header, body], ..Default::default() };
|
||||
d.body.push(Arc::new(wordcraft_doc::Block::Table(t)));
|
||||
let raw = String::from_utf8_lossy(&export(&d, &PdfOptions { tagged: true, compress: false, ..Default::default() }).unwrap()).into_owned();
|
||||
let count = |tag: &str| raw.matches(&format!("/S/{tag}")).count() + raw.matches(&format!("/S /{tag}")).count();
|
||||
assert_eq!(count("TH"), 2, "both header cells, including the blank one");
|
||||
assert_eq!(count("TD"), 2, "both body cells, including the blank one");
|
||||
}
|
||||
|
||||
/// A row whose cells are all blank is still a row: its TR and its cells are in the tree.
|
||||
#[test]
|
||||
fn an_all_blank_row_keeps_its_cells() {
|
||||
use wordcraft_doc::{Cell, Row, Table};
|
||||
let mut d = Document::from_text("A table.");
|
||||
let blank = Row { cells: vec![Cell::with_text(""), Cell::with_text("")], ..Default::default() };
|
||||
let filled = Row { cells: vec![Cell::with_text("A"), Cell::with_text("B")], ..Default::default() };
|
||||
let t = Table { grid: vec![120.0, 120.0], rows: vec![blank, filled], ..Default::default() };
|
||||
d.body.push(Arc::new(wordcraft_doc::Block::Table(t)));
|
||||
let raw = String::from_utf8_lossy(&export(&d, &PdfOptions { tagged: true, compress: false, ..Default::default() }).unwrap()).into_owned();
|
||||
let count = |tag: &str| raw.matches(&format!("/S/{tag}")).count() + raw.matches(&format!("/S /{tag}")).count();
|
||||
assert_eq!(count("TR"), 2, "both rows, including the all-blank one");
|
||||
assert_eq!(count("TD"), 4, "every body cell");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn link_annotations_are_tagged_with_link_and_objr() {
|
||||
use hayro_syntax::object::{Array, Dict, Name, Object};
|
||||
|
||||
let mut p = Paragraph::with_text("Visit ", CharProps::default());
|
||||
let link_props = CharProps { link: Some("https://example.com".into()), ..Default::default() };
|
||||
p.insert_text(p.len(), "Example", &link_props).unwrap();
|
||||
p.insert_text(p.len(), " now", &CharProps::default()).unwrap();
|
||||
let mut d = Document::new();
|
||||
d.core.title = "Link test".into();
|
||||
d.body = vec![para_block(p)];
|
||||
|
||||
let bytes = export(&d, &PdfOptions { compress: false, tagged: true, ..Default::default() }).unwrap();
|
||||
let pdf = hayro_syntax::Pdf::new(bytes).unwrap();
|
||||
let page = &pdf.pages()[0];
|
||||
let annots = page.raw().get::<Array>(b"Annots").expect("page Annots");
|
||||
let annot = annots.iter::<Dict>().next().expect("link annotation");
|
||||
assert!(annot.get::<i32>(b"StructParent").is_some(), "link annotation missing /StructParent");
|
||||
let annot_id = format!("{:?}", annot.obj_id().expect("indirect annotation"));
|
||||
|
||||
let root = pdf.xref().get::<Dict>(pdf.xref().root_id()).unwrap();
|
||||
let struct_tree = root.get::<Dict>(b"StructTreeRoot").expect("StructTreeRoot");
|
||||
|
||||
fn find_links(dict: &Dict, out: &mut Vec<(bool, Option<String>)>) {
|
||||
if dict.get::<Name>(b"S").is_some_and(|s| s.as_ref() == b"Link") {
|
||||
let mut has_mcid = false;
|
||||
let mut objr = None;
|
||||
if let Some(k) = dict.get::<Array>(b"K") {
|
||||
for item in k.iter::<Object>() {
|
||||
match item {
|
||||
Object::Number(_) => has_mcid = true,
|
||||
Object::Dict(d) if d.get::<Name>(b"Type").is_some_and(|t| t.as_ref() == b"OBJR") => {
|
||||
objr = d.get::<Dict>(b"Obj").and_then(|o| o.obj_id()).map(|id| format!("{id:?}"));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push((has_mcid, objr));
|
||||
}
|
||||
if let Some(k) = dict.get::<Array>(b"K") {
|
||||
for item in k.iter::<Object>() {
|
||||
if let Object::Dict(child) = item {
|
||||
find_links(&child, out);
|
||||
}
|
||||
}
|
||||
} else if let Some(child) = dict.get::<Dict>(b"K") {
|
||||
find_links(&child, out);
|
||||
}
|
||||
}
|
||||
|
||||
let mut links = Vec::new();
|
||||
find_links(&struct_tree, &mut links);
|
||||
assert!(!links.is_empty(), "StructTreeRoot has no /Link structure element (annot {annot_id})");
|
||||
assert!(
|
||||
links.iter().any(|(mcid, objr)| *mcid && objr.as_deref() == Some(&annot_id)),
|
||||
"Link element missing MCID or OBJR for {annot_id}: {links:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Linked text split by unlinked text keeps reading order: two Link elements, not one that
|
||||
/// swallows the later run ahead of the text between.
|
||||
#[test]
|
||||
fn separated_link_runs_are_separate_link_elements() {
|
||||
use hayro_syntax::object::{Array, Dict, Name, Object};
|
||||
|
||||
let link_props = CharProps { link: Some("https://example.com".into()), ..Default::default() };
|
||||
let mut p = Paragraph::with_text("A", link_props.clone());
|
||||
p.insert_text(p.len(), ".", &CharProps::default()).unwrap();
|
||||
p.insert_text(p.len(), "B", &link_props).unwrap();
|
||||
let mut d = Document::new();
|
||||
d.body = vec![para_block(p)];
|
||||
|
||||
let bytes = export(&d, &PdfOptions { compress: false, tagged: true, ..Default::default() }).unwrap();
|
||||
let pdf = hayro_syntax::Pdf::new(bytes).unwrap();
|
||||
let root = pdf.xref().get::<Dict>(pdf.xref().root_id()).unwrap();
|
||||
let tree = root.get::<Dict>(b"StructTreeRoot").expect("StructTreeRoot");
|
||||
|
||||
fn count(dict: &Dict) -> usize {
|
||||
let mut n = usize::from(dict.get::<Name>(b"S").is_some_and(|s| s.as_ref() == b"Link"));
|
||||
if let Some(k) = dict.get::<Array>(b"K") {
|
||||
for item in k.iter::<Object>() {
|
||||
if let Object::Dict(c) = item {
|
||||
n += count(&c);
|
||||
}
|
||||
}
|
||||
} else if let Some(c) = dict.get::<Dict>(b"K") {
|
||||
n += count(&c);
|
||||
}
|
||||
n
|
||||
}
|
||||
assert_eq!(count(&tree), 2, "each separated link run needs its own Link element");
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ craft = { workspace = true, features = [
|
||||
"color", "color-ui", "control", "draw", "font-manager", "gpu", "menu", "pages", "print", "review", "table", "text",
|
||||
"text-find", "web-api", "web-host", "window",
|
||||
] }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35" }
|
||||
wordcraft-geom = { workspace = true, features = ["image"] }
|
||||
wordcraft-doc = { workspace = true }
|
||||
wordcraft-fonts = { workspace = true }
|
||||
@@ -76,7 +76,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 = "d73e274a01408ef433a291a667e6014937d72165", features = ["subset"] }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", features = ["subset"] }
|
||||
serde_json = { workspace = true }
|
||||
toml = "1"
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" height="20">
|
||||
<rect x="7.5" y="2.5" width="5" height="9.5" rx="1" fill="none" stroke="currentColor" stroke-width="1.25"/>
|
||||
<path d="M5 9.5 L5 11 L10 15 L15 11 L15 9.5" fill="none" stroke="currentColor" stroke-width="1.25"/>
|
||||
<path d="M10 15 L10 18" fill="none" stroke="currentColor" stroke-width="1.25"/>
|
||||
<rect x="7.5" y="2.5" width="5" height="9.5" rx="2.5" fill="none" stroke="currentColor" stroke-width="1.25"/>
|
||||
<path d="M5 9.5 L5 11 L10 15 L15 11 L15 9.5" fill="none" stroke="currentColor" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M10 15 L10 18" fill="none" stroke="currentColor" stroke-width="1.25" stroke-linecap="round"/>
|
||||
</svg>
|
||||
|
||||
|
Before Width: | Height: | Size: 386 B After Width: | Height: | Size: 458 B |
@@ -363,6 +363,7 @@ impl WordApp {
|
||||
// draws, for itself.
|
||||
self.window_work(ctx);
|
||||
self.drain_inbox();
|
||||
crate::keys::tick_paste_wait(self, ctx);
|
||||
self.paste_arrived(ctx);
|
||||
// Focus hides the title bar's search box: a search left open there has no box to show it, and would keep
|
||||
// Escape from leaving Focus (#5398).
|
||||
|
||||
@@ -348,7 +348,11 @@ impl WordApp {
|
||||
let params = if fired.command.params.is_null() { json!({}) } else { fired.command.params.clone() };
|
||||
let from_key = fired.source == FireSource::Key;
|
||||
|
||||
let (id, params) = if id == "edit.pasteFormat" && from_key { self.paste_format_command(ctx, params) } else { (id, params) };
|
||||
let (id, params) = if id == "edit.pasteFormat" && from_key { self.paste_format_command(ctx, fired.mods, params) } else { (id, params) };
|
||||
if from_key && id != "edit.pasteFormat" {
|
||||
self.canvas.ignore_next_paste = false;
|
||||
self.canvas.paste_wait_since = None;
|
||||
}
|
||||
// An Undo or Redo that is not a focused field's own edit (S-L187 sends that one to the
|
||||
// field) first takes back the gesture under way and every running one (S-L364).
|
||||
if matches!(id, "edit.undo" | "edit.redo") {
|
||||
@@ -368,25 +372,34 @@ impl WordApp {
|
||||
self.canvas.focus_page(ctx);
|
||||
}
|
||||
}
|
||||
self.canvas.paste_event_consumed_same_frame = false;
|
||||
}
|
||||
|
||||
/// Paste Formatting from its key. Mod+Shift+V pastes the formatting Mod+Shift+C (or the Format
|
||||
/// Painter) picked up; with none picked up it pastes the clipboard as text only, as Word for
|
||||
/// Windows does (#1537, #4943). Another key bound to Paste Formatting only pastes formatting.
|
||||
/// The framework fires one command per chord, so nothing waits for a browser paste event.
|
||||
fn paste_format_command(&self, ctx: &egui::Context, params: Value) -> (&'static str, Value) {
|
||||
/// On platforms where a browser paste event follows Mod+Shift+V, pasting formatting arms
|
||||
/// `ignore_next_paste` so that paired paste event is dropped.
|
||||
fn paste_format_command(&mut self, ctx: &egui::Context, fired_mods: craft::keymap::Mods, params: Value) -> (&'static str, Value) {
|
||||
let formatting = self.session.painter.is_some() || self.session.copied_format.is_some();
|
||||
// The command runs a pass after its press, when a quick tap's modifiers are already up: with none held the fire
|
||||
// is Mod+Shift+V's while that chord is still the command's.
|
||||
let mods = ctx.input(|i| i.modifiers);
|
||||
let chord = if mods.any() {
|
||||
mods.command && mods.shift && !mods.alt
|
||||
// `fired.mods` carries the chord's modifiers across every OS window, even after a quick
|
||||
// tap releases the physical keys before `run_fired` runs.
|
||||
let platform = if craft::ui::runtime::windows::os_of(ctx) == craft::host::target::Os::Mac {
|
||||
craft::keymap::Platform::Mac
|
||||
} else {
|
||||
let default = Binding::parse("Mod+Shift+V").ok().map(|binding| binding.trigger.chord);
|
||||
craft::ui::runtime::commands::bindings(ctx, &CommandRef::new("edit.pasteFormat"))
|
||||
.iter()
|
||||
.any(|binding| Some(binding.trigger.chord) == default)
|
||||
craft::keymap::Platform::Windows
|
||||
};
|
||||
let eff = fired_mods.effective(platform);
|
||||
let mod_shift = eff.cmd && eff.shift && !eff.alt && !eff.ctrl;
|
||||
let default = Binding::parse("Mod+Shift+V").ok().map(|binding| binding.trigger.chord);
|
||||
let chord = mod_shift
|
||||
&& craft::ui::runtime::commands::bindings(ctx, &CommandRef::new("edit.pasteFormat"))
|
||||
.iter()
|
||||
.any(|binding| Some(binding.trigger.chord.effective(platform)) == default);
|
||||
if formatting && chord && self.canvas.paste_event_follows_chord && !std::mem::take(&mut self.canvas.paste_event_consumed_same_frame) {
|
||||
self.canvas.ignore_next_paste = true;
|
||||
self.canvas.paste_wait_since = Some(ctx.input(|i| i.time));
|
||||
}
|
||||
if !formatting && chord { ("edit.pasteText", json!({})) } else { ("edit.pasteFormat", params) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,8 +10,13 @@ use super::{
|
||||
};
|
||||
use crate::colors;
|
||||
|
||||
/// The document's own save stamps: zoom, last-modified-by, created, modified and revision.
|
||||
type SaveStamps = (Option<wordcraft_doc::Zoom>, String, String, String, u32);
|
||||
|
||||
impl WordApp {
|
||||
/// `run` for a command a mouse drag on a table sends: the view stays where it is.
|
||||
/// Runs a command from a pointer gesture without automatically scrolling to the caret.
|
||||
/// Table and ruler gestures and picture or shape selection use this when the pointer
|
||||
/// already identifies the target.
|
||||
pub(crate) fn run_keep_view(&mut self, id: &str, params: Value) -> Result<Value, String> {
|
||||
self.canvas.keep_view = true;
|
||||
let r = self.run(id, params);
|
||||
@@ -114,6 +119,42 @@ impl WordApp {
|
||||
r
|
||||
}
|
||||
|
||||
/// File › Export's `copy` (#6131) writes a copy and never the document's own file. A host
|
||||
/// page's Save writes the opened file under its own name and its flag can't say "copy", so a
|
||||
/// copy named like the opened file would overwrite it with unsaved text; and `password`
|
||||
/// changes the document's own later saves. Both are refused before anything is written.
|
||||
fn copy_save(&self, id: &str, name: &str, params: &Value) -> Result<bool, String> {
|
||||
let as_copy = params.get("copy").and_then(Value::as_bool) == Some(true);
|
||||
if !as_copy {
|
||||
return Ok(false);
|
||||
}
|
||||
let opened = self.session.path.as_ref().and_then(|p| p.file_name()).map(|n| n.to_string_lossy().to_string());
|
||||
// Compare file names only: a copy given as a path still lands on the opened file's name.
|
||||
let copy_name = std::path::Path::new(name).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| name.to_string());
|
||||
if opened.as_deref() == Some(copy_name.as_str()) {
|
||||
return Err("a copy can't have the same name as the open document: choose another name".into());
|
||||
}
|
||||
if matches!(id, "file.save" | "file.saveAs") && params.get("password").is_some_and(|pw| !pw.is_null()) {
|
||||
return Err("`password` changes the document's own saves, so it can't come with `copy` (use file.encrypt)".into());
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// A copy (File › Export, #6131) writes its bytes with fresh save stamps; the document's own
|
||||
/// are then put back, so its next Save still goes to the original file.
|
||||
fn restore_copy_stamps(&mut self, as_copy: bool, stamps: &SaveStamps) {
|
||||
if as_copy {
|
||||
let (zoom, by, created, modified, revision) = stamps;
|
||||
(
|
||||
self.session.doc.settings.zoom,
|
||||
self.session.doc.core.last_modified_by,
|
||||
self.session.doc.core.created,
|
||||
self.session.doc.core.modified,
|
||||
self.session.doc.core.revision,
|
||||
) = (*zoom, by.clone(), created.clone(), modified.clone(), *revision);
|
||||
}
|
||||
}
|
||||
|
||||
/// Run a command for a script or an agent (control channel, MCP bridge): never asks first.
|
||||
/// UI-level commands (`ui.*`) are handled here, the rest by the engine.
|
||||
pub fn execute(&mut self, id: &str, params: Value) -> Result<Value, String> {
|
||||
@@ -153,6 +194,9 @@ impl WordApp {
|
||||
// Inspect only the suffix bytes: no full-name allocation or UTF-8 slicing.
|
||||
let has_pdf_suffix = name.as_bytes().last_chunk::<4>().is_some_and(|suffix| suffix.eq_ignore_ascii_case(b".pdf"));
|
||||
let name = if id == "file.exportPdf" && !has_pdf_suffix { format!("{name}.pdf") } else { name };
|
||||
// `copy` (File › Export, #6131) writes a copy: the document keeps its unsaved changes,
|
||||
// its name and its save stamps, as for a PDF.
|
||||
let as_copy = self.copy_save(id, &name, ¶ms)?;
|
||||
// A save with a password encrypts this and later saves (`file.save`'s `password`).
|
||||
if matches!(id, "file.save" | "file.saveAs")
|
||||
&& let Some(pw) = params.get("password").filter(|v| !v.is_null())
|
||||
@@ -172,6 +216,7 @@ impl WordApp {
|
||||
self.session.doc.core.revision,
|
||||
);
|
||||
// A save is a save, download or not: advance the revision and modified stamp (#262).
|
||||
// A copy carries fresh stamps too, but the document's own are put back after.
|
||||
if matches!(id, "file.save" | "file.saveAs") {
|
||||
self.session.stamp_save();
|
||||
}
|
||||
@@ -192,23 +237,26 @@ impl WordApp {
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
self.restore_copy_stamps(as_copy, &before_stamp);
|
||||
// An export is a copy, and so is a save in a format that doesn't keep everything (a
|
||||
// page image, plain text): the document itself still has unsaved changes.
|
||||
let marked_saved = matches!(id, "file.save" | "file.saveAs") && keeps_everything(&name);
|
||||
let marked_saved = matches!(id, "file.save" | "file.saveAs") && !as_copy && keeps_everything(&name);
|
||||
// The ticket's answer may be a failure: what the save stamped is put back then (`settle_saves`).
|
||||
let undo_stamp: Option<Box<dyn FnOnce(&mut wordcraft_engine::Session)>> = matches!(id, "file.save" | "file.saveAs").then(|| {
|
||||
let dirty = dirty_before;
|
||||
Box::new(move |session: &mut wordcraft_engine::Session| {
|
||||
(
|
||||
session.doc.settings.zoom,
|
||||
session.doc.core.last_modified_by,
|
||||
session.doc.core.created,
|
||||
session.doc.core.modified,
|
||||
session.doc.core.revision,
|
||||
) = before_stamp;
|
||||
session.dirty = dirty;
|
||||
}) as Box<dyn FnOnce(&mut wordcraft_engine::Session)>
|
||||
});
|
||||
// A copy already restored its stamps above, so settling it leaves the document's own stamps alone.
|
||||
let undo_stamp: Option<Box<dyn FnOnce(&mut wordcraft_engine::Session)>> =
|
||||
(matches!(id, "file.save" | "file.saveAs") && !as_copy).then(|| {
|
||||
let dirty = dirty_before;
|
||||
Box::new(move |session: &mut wordcraft_engine::Session| {
|
||||
(
|
||||
session.doc.settings.zoom,
|
||||
session.doc.core.last_modified_by,
|
||||
session.doc.core.created,
|
||||
session.doc.core.modified,
|
||||
session.doc.core.revision,
|
||||
) = before_stamp;
|
||||
session.dirty = dirty;
|
||||
}) as Box<dyn FnOnce(&mut wordcraft_engine::Session)>
|
||||
});
|
||||
// Save As tells the host page the document is now this file, which it only is when the
|
||||
// save marks it saved. A Save under a name the page never sent (an untitled document,
|
||||
// an imported .doc saved as .docx) is a new file too, never an overwrite.
|
||||
@@ -398,7 +446,7 @@ impl WordApp {
|
||||
self.canvas.read_first_visible = None;
|
||||
}
|
||||
// Drawing leaves the caret where it was: following it would pull the view off the ink.
|
||||
// A mouse drag on a table (`run_keep_view`) does the same (#1738). A caret in an empty
|
||||
// Pointer gestures using `run_keep_view` also keep the view in place. A caret in an empty
|
||||
// story (a footer just made) also spans the whole story: it isn't a selection of it, and
|
||||
// the view follows it. Saving, exporting, printing, the document's properties and File ›
|
||||
// Options move neither the caret nor the text, so the view stays where the user is
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use craft::host::{PickId, Picked};
|
||||
use craft::platform::open::{DroppedFile, Intake};
|
||||
use craft::quit::{CloseAnswer, CloseGuard, CloseScope, GuardStep};
|
||||
use craft::ui::dialog::{DialogId, DialogResult, UnsavedChangesDialog};
|
||||
use craft::ui::dialog::{DialogId, DialogResult, HostedUnsavedChangesDialog, UnsavedChangesDialog};
|
||||
use craft::ui::shell::embed::CloseDecision;
|
||||
|
||||
use super::{AutoSaveBlock, PromptSave, Value, WordApp, file_dialogs, i18n, json, keeps_everything, panes, printing};
|
||||
@@ -151,7 +151,7 @@ impl WordApp {
|
||||
dialog = dialog.reason(reason);
|
||||
}
|
||||
// PLAN: assumed `WordApp::dialog_host: DialogHost`, the shown window's
|
||||
let id = self.dialog_host.open(dialog);
|
||||
let id = self.dialog_host.open(HostedUnsavedChangesDialog::new(dialog));
|
||||
if let Some(closing) = self.closing.as_mut() {
|
||||
closing.prompt = Some(id);
|
||||
closing.window = self.windows.shown();
|
||||
@@ -246,7 +246,7 @@ impl WordApp {
|
||||
let ctx = self.ctx.clone().unwrap_or_default();
|
||||
if let Some(host) = self.window_dialog_host_mut(window) {
|
||||
host.cancel_by_id(&ctx, id);
|
||||
let _ = host.take_by_id::<UnsavedChangesDialog>(id);
|
||||
let _ = host.take_by_id::<HostedUnsavedChangesDialog>(id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -262,7 +262,7 @@ impl WordApp {
|
||||
/// from `logic`.
|
||||
pub(crate) fn pump_close_prompt(&mut self) {
|
||||
let Some((window, id)) = self.closing.as_ref().and_then(|c| c.prompt.map(|id| (c.window, id))) else { return };
|
||||
let Some(result) = self.window_dialog_host_mut(window).and_then(|host| host.take_by_id::<UnsavedChangesDialog>(id)) else { return };
|
||||
let Some(result) = self.window_dialog_host_mut(window).and_then(|host| host.take_by_id::<HostedUnsavedChangesDialog>(id)) else { return };
|
||||
if let Some(ctx) = self.ctx.as_ref() {
|
||||
crate::dialogs::chrome::forget_nudge(ctx, id);
|
||||
}
|
||||
@@ -285,6 +285,16 @@ impl WordApp {
|
||||
if self.raise_closing().is_some() {
|
||||
return CloseDecision::Hold;
|
||||
}
|
||||
// Nothing is open, so nothing to ask about (also under a windowless root, whose last document window going is
|
||||
// what asks).
|
||||
if self.session.documents().is_empty() {
|
||||
return CloseDecision::Close;
|
||||
}
|
||||
// A windowless root has no window of its own: its close is a quit (the OS quit, or the last document window
|
||||
// going), never one window's close.
|
||||
if self.ctx.as_ref().is_some_and(craft::ui::runtime::windows::windowless_root) {
|
||||
return if self.close_requested() { CloseDecision::Close } else { CloseDecision::Hold };
|
||||
}
|
||||
if self.closes_a_window() {
|
||||
// The root window's close button closes that window alone (File › Close in it, which asks
|
||||
// about unsaved changes first); the framework leaves the root's window open on `Hold`, and
|
||||
@@ -544,6 +554,16 @@ impl WordApp {
|
||||
if self.closes_only_its_window("file.close", params) && self.close_window_only() {
|
||||
return Ok(json!({"closed": true, "window": true}));
|
||||
}
|
||||
if params.get("save").and_then(Value::as_bool) == Some(true) {
|
||||
// A comment still being typed refuses before anything is written.
|
||||
if let Some(e) = crate::control::close_refused(self, "file.close", params) {
|
||||
return Err(e.into());
|
||||
}
|
||||
// Automation's `save: true`: write the document, then close it. Never a prompt (spec rule 8).
|
||||
if let Some(pending) = self.save_for_close()? {
|
||||
return Ok(pending);
|
||||
}
|
||||
}
|
||||
if let Some(e) = crate::control::close_refused(self, "file.close", params) {
|
||||
return Err(e.into());
|
||||
}
|
||||
@@ -578,6 +598,24 @@ impl WordApp {
|
||||
Ok(json!({"closed": true}))
|
||||
}
|
||||
|
||||
/// `file.close` with `save: true`: save the shown document if it has unsaved work. `Some` is
|
||||
/// the reply when the save finishes later (the browser's picker). A document with no file
|
||||
/// to write has nowhere to save without asking, so that is an error, not a prompt.
|
||||
fn save_for_close(&mut self) -> Result<Option<Value>, String> {
|
||||
if !self.document_unsaved() {
|
||||
return Ok(None);
|
||||
}
|
||||
if self.session.path.is_none() || self.legacy_word_path() {
|
||||
return Err("the document has no file to save to: use file.saveAs first, or pass {\"force\": true} to discard it".into());
|
||||
}
|
||||
match self.save_for_prompt()? {
|
||||
PromptSave::Saved => Ok(None),
|
||||
// lean: only the browser picker saves later and it has no control channel, so the close is not resumed.
|
||||
PromptSave::Later => Ok(Some(json!({"pending": "save"}))),
|
||||
PromptSave::NotSaved => Err("the document was not saved, so it stays open".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// These paths have readers but no writer, so an interactive save needs another format.
|
||||
pub(super) fn legacy_word_path(&self) -> bool {
|
||||
self.session
|
||||
|
||||
@@ -16,12 +16,18 @@ use crate::i18n::Lang;
|
||||
// PLAN(chrome-w12): build.rs embeds the craft faces into `craft_fonts.rs`
|
||||
pub static CRAFT_FONTS: &[EmbeddedFace] = include!(concat!(env!("OUT_DIR"), "/craft_fonts.rs"));
|
||||
|
||||
/// The interface fonts for `lang`: the embedded craft faces, ordered by the language's scripts,
|
||||
/// and installed system fonts loaded on demand where the platform has them.
|
||||
/// The interface fonts for `lang`: WordCraft's own Inter and the embedded craft faces, ordered by the language's
|
||||
/// scripts, and installed system fonts loaded on demand where the platform has them.
|
||||
pub fn ui_fonts(lang: Lang) -> UiFonts<'static> {
|
||||
ui_fonts_with_optional_faces(lang, CRAFT_FONTS)
|
||||
}
|
||||
|
||||
/// [`ui_fonts`] with `faces` as the optional craft-fonts faces. Tests pass none, so the faces a CI build embeds
|
||||
/// can't hide a character the interface's own faces lack.
|
||||
pub(crate) fn ui_fonts_with_optional_faces(lang: Lang, faces: &[EmbeddedFace]) -> UiFonts<'static> {
|
||||
let codes: Vec<&str> = Lang::all().map(Lang::code).collect();
|
||||
let os_locale = wordcraft_engine::system_locale();
|
||||
let fonts = UiFonts::new(&I18nScripts).craft_faces(CRAFT_FONTS).languages(&codes).ui_language(lang.code());
|
||||
let fonts = UiFonts::new(&I18nScripts).craft_faces(&own_inter()).craft_faces(faces).languages(&codes).ui_language(lang.code());
|
||||
let fonts = match os_locale {
|
||||
Some(locale) => fonts.os_locale(locale),
|
||||
None => fonts,
|
||||
@@ -31,6 +37,21 @@ pub fn ui_fonts(lang: Lang) -> UiFonts<'static> {
|
||||
fonts
|
||||
}
|
||||
|
||||
/// WordCraft's own Inter Regular and SemiBold, from the bytes the document fonts embed. The suite's interface face is
|
||||
/// the same Inter release cut to Latin, Greek and Cyrillic; tagged with those scripts, these come right after the
|
||||
/// suite's faces and draw the rest of Inter (○ ✓ ★, the macOS key symbols) in the same design and row height, as the
|
||||
/// interface did before it moved onto the shared font stack (#7101).
|
||||
fn own_inter() -> [EmbeddedFace; 2] {
|
||||
wordcraft_fonts::bundled_inter().map(|(style, bytes)| EmbeddedFace {
|
||||
family: "Inter",
|
||||
style,
|
||||
scripts: &["Latn", "Grek", "Cyrl"],
|
||||
index: 0,
|
||||
bytes,
|
||||
role: None,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
/// One character of each script the app ships, to find the document fonts that cover it.
|
||||
const FALLBACK_SAMPLES: [char; 6] = ['ع', 'א', 'ก', 'ა', 'ա', '汉'];
|
||||
@@ -116,12 +137,12 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Symbols written as text in the interface code must exist in the interface fonts; a missing
|
||||
/// glyph draws as an empty box, as the panes' "✕" close button once did. Letters are the
|
||||
/// catalogs' business (see the i18n font tests).
|
||||
/// Symbols written as text in the interface code must exist in the interface fonts, also in a build without the
|
||||
/// optional craft-fonts faces; a missing glyph draws as an empty box, as the panes' "✕" close button once did.
|
||||
/// Letters are the catalogs' business (see the i18n font tests).
|
||||
#[test]
|
||||
fn interface_symbols_have_glyphs() {
|
||||
let stack = ui_fonts(Lang::EN).stack();
|
||||
let stack = ui_fonts_with_optional_faces(Lang::EN, &[]).stack();
|
||||
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
|
||||
let mut symbols = BTreeSet::new();
|
||||
// The i18n module's literals are catalog and pseudo-locale test text, not interface text.
|
||||
@@ -154,9 +175,11 @@ mod tests {
|
||||
symbols.retain(|(c, file)| !exempt(*c, file));
|
||||
let files: Vec<(char, String)> = symbols.into_iter().collect();
|
||||
let texts: Vec<(String, String)> = files.iter().map(|(c, f)| (c.to_string(), f.clone())).collect();
|
||||
let samples = texts.iter().map(|(t, f)| Sample::new("en", f, t));
|
||||
let missing = missing_glyphs(&stack, &FontRef::proportional(), samples, false);
|
||||
assert!(missing.is_empty(), "symbols without a glyph: {missing:#?}");
|
||||
for family in [FontRef::proportional(), FontRef::named(craft::ui::fonts::SEMIBOLD)] {
|
||||
let samples = texts.iter().map(|(t, f)| Sample::new("en", f, t));
|
||||
let missing = missing_glyphs(&stack, &family, samples, false);
|
||||
assert!(missing.is_empty(), "symbols without a glyph in {family:?}: {missing:#?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An installed Arabic font is asked for only when Arabic text needs one (and no embedded
|
||||
|
||||
@@ -77,6 +77,10 @@ impl WordApp {
|
||||
if !ClipboardHandle::of(ctx).arrived() {
|
||||
return;
|
||||
}
|
||||
if std::mem::take(&mut self.canvas.ignore_next_paste) {
|
||||
self.canvas.paste_wait_since = None;
|
||||
return;
|
||||
}
|
||||
// PLAN(canvas-w9): cv.A10 `CanvasState::focused(&self, &egui::Context) -> bool`
|
||||
if paste_target(self.canvas.focused(ctx), self.ui.backstage, self.modal_open()) {
|
||||
let _ = self.run("edit.paste", json!({}));
|
||||
|
||||
@@ -941,3 +941,21 @@ fn clicking_beside_the_back_arrow_does_not_close_the_file_page() {
|
||||
h.run_steps(4);
|
||||
assert!(h.state().ui.backstage, "clicking beside the arrow leaves the File page open");
|
||||
}
|
||||
|
||||
/// #7171: in a window too short for the settings column its scroll bar shows, and the buttons stop where the bar's lane
|
||||
/// starts instead of running under it. The column also ends short of the preview.
|
||||
#[test]
|
||||
fn print_settings_buttons_stay_clear_of_the_bar_and_the_preview() {
|
||||
let mut a = new_app();
|
||||
a.run("text.insert", json!({"text": "Some text"})).unwrap();
|
||||
a.run("ui.backstage", json!({"value": true, "page": "print"})).unwrap();
|
||||
let mut h = harness(a, egui::vec2(700.0, 500.0));
|
||||
h.run_steps(6);
|
||||
let column = h.query_all_by_label("Print").map(|n| n.rect()).max_by(|a, b| a.height().total_cmp(&b.height())).expect("the settings column");
|
||||
let pane = h.query_all_by_label("Sheet 1 of 1").map(|n| n.rect()).max_by(|a, b| a.height().total_cmp(&b.height())).expect("the preview");
|
||||
assert!(pane.min.x >= column.max.x + 8.0, "a gap between the column and the preview: {column:?} {pane:?}");
|
||||
for name in ["Save these pages as PDF…", "PDF document (*.pdf)"] {
|
||||
let button = h.get_by_label(name).rect();
|
||||
assert!(button.min.x >= column.min.x && button.max.x <= column.max.x - 4.0, "{name} leaves the bar's lane: {button:?} {column:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -152,8 +152,8 @@ pub struct CanvasState {
|
||||
/// revision: finding out walks every paragraph, too slow for every frame (#811).
|
||||
markup_facts: Cell<Option<((u64, u64), [bool; 3])>>,
|
||||
pub scroll_to_caret: bool,
|
||||
/// Set while a command runs for a mouse drag on a table: the pointer is already
|
||||
/// on the target, so the view stays put instead of following the caret (#1738).
|
||||
/// Set while a pointer-triggered command runs through `WordApp::run_keep_view`
|
||||
/// to suppress automatic scrolling to the caret.
|
||||
pub keep_view: bool,
|
||||
/// A heading navigation click aligns its page against the navigation pane, not just visible.
|
||||
pub(crate) nav_to_caret: bool,
|
||||
@@ -262,6 +262,17 @@ pub struct CanvasState {
|
||||
/// Snapshot of `session.doc` for `(document_id, rev)`, shared via `Arc::clone` across
|
||||
/// unchanged frames instead of cloning the full `Document` every pass.
|
||||
doc_snapshot: Option<((u64, u64), Arc<wordcraft_doc::Document>)>,
|
||||
/// On the web, Mod+Shift+V pasted formatting from its key press: the browser's paste event
|
||||
/// that follows is the same keystroke and pastes nothing (#5616). Any other key press, pointer
|
||||
/// press, focus change, or wait past `PASTE_WAIT` clears it.
|
||||
pub(crate) ignore_next_paste: bool,
|
||||
/// Input time (seconds) when `ignore_next_paste` was armed.
|
||||
pub(crate) paste_wait_since: Option<f64>,
|
||||
/// Whether the platform sends a paste event after Mod+Shift+V's key (true on the web).
|
||||
pub(crate) paste_event_follows_chord: bool,
|
||||
/// The paired browser paste arrived and was dropped in the same frame as Mod+Shift+V, before
|
||||
/// `run_fired` runs in the next frame.
|
||||
pub(crate) paste_event_consumed_same_frame: bool,
|
||||
}
|
||||
|
||||
type TablePreviewKey = ((String, serde_json::Value, u64, u64, wordcraft_engine::Selection), Arc<DocLayout>);
|
||||
@@ -474,6 +485,10 @@ impl Default for CanvasState {
|
||||
preview_scroll: None,
|
||||
table_preview_layout: None,
|
||||
doc_snapshot: None,
|
||||
ignore_next_paste: false,
|
||||
paste_wait_since: None,
|
||||
paste_event_follows_chord: cfg!(target_arch = "wasm32"),
|
||||
paste_event_consumed_same_frame: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -151,12 +151,11 @@ fn rows(app: &mut WordApp, ui: &mut Ui) {
|
||||
let _ = Menu::submenu_row(ui, tl!("Synonyms").to_string(), |ui, _cx| {
|
||||
for w in syn.iter().filter_map(|x| x.as_str()) {
|
||||
if MenuItem::new(w.to_string()).show(ui).ran {
|
||||
let _ = app.run("select.word", json!({}));
|
||||
let (a, b) = app.session.sel.ordered();
|
||||
let trimmed = app.session.doc.para_at(&a).and_then(|p| p.text.get(a.off..b.off)).map(|t| t.trim_end().len()).unwrap_or(0);
|
||||
let end = wordcraft_doc::Pos { off: a.off + trimmed, ..b };
|
||||
app.session.set_selection(wordcraft_engine::Selection { anchor: a, focus: end });
|
||||
let _ = app.run("text.insert", json!({"text": w, "raw": true}));
|
||||
// The word the synonyms were looked up for: quotes around it stay (#6517).
|
||||
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}));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -7,10 +7,29 @@ use super::{Pos2, WordApp};
|
||||
/// coordinates) while any of it is inside the window (`top` .. `top + height`, `top` the layout's y at the window's
|
||||
/// top edge), else the page at the window's top: the first whose shown band ends below it (with Hide White Space the
|
||||
/// rects overlap in the hidden margins, and the next page's text already shows there), the last page past the end.
|
||||
/// A page whose shown part at the top is no more than the gap to the page below it (the next row down) does not count: Go To leaves the
|
||||
/// pages' margin above a page, which is more than that gap, so a sliver of the page above still shows (#7149).
|
||||
pub(super) fn viewed_page(caret: Option<(usize, f64, f64)>, top: f64, layout: &PagedLayout, height: f64) -> usize {
|
||||
match caret {
|
||||
Some((page, from, to)) if to >= top && from <= top + height => page,
|
||||
_ => layout.rects.iter().zip(&layout.bands).position(|(r, band)| r.y0 + band.1 > top).unwrap_or(layout.rects.len().saturating_sub(1)),
|
||||
_ => (0..layout.rects.len())
|
||||
.position(|i| {
|
||||
let end = layout.rects[i].y0 + layout.bands.get(i).map_or(0.0, |band| band.1);
|
||||
// The gap to the first later page whose shown part starts at or below this one's end: the page below,
|
||||
// whatever the column (an incomplete last row, a Two Up cover) and with Hide White Space (a seam).
|
||||
let below = |j: &usize| layout.rects.get(*j).is_some_and(|r| r.y0 + layout.bands.get(*j).map_or(0.0, |b| b.0) >= end);
|
||||
// Measured from the bottom of the row (the tallest page between this one and that page): pages of different
|
||||
// heights share a row, and the next row starts below the tallest.
|
||||
let gap = ((i + 1)..layout.rects.len()).find(below).and_then(|j| layout.rects.get(j).map(|next| (j, next))).map_or(0.0, |(j, _)| {
|
||||
let row_end = (i..j).map(|k| layout.rects[k].y0 + layout.bands.get(k).map_or(0.0, |b| b.1)).fold(end, f64::max);
|
||||
// The next row's real top: its shorter pages are centred lower, so not `next`'s own top.
|
||||
let shown = |k: usize| layout.rects[k].y0 + layout.bands.get(k).map_or(0.0, |b| b.0);
|
||||
let next_top = (j..(j + layout.columns.max(1)).min(layout.rects.len())).map(shown).fold(shown(j), f64::min);
|
||||
(next_top - row_end).max(0.0)
|
||||
});
|
||||
end > top + gap
|
||||
})
|
||||
.unwrap_or(layout.rects.len().saturating_sub(1)),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -518,6 +518,24 @@ fn the_page_in_view_follows_the_caret_while_it_is_on_screen() {
|
||||
assert_eq!(viewed_page(caret(2, 90.0), scrolled(330.0), &layout, 100.0), 3, "a caret just above the window is not in view");
|
||||
}
|
||||
|
||||
/// Two Up centres the shorter page of a spread: the next spread's shorter first page starts lower than its row, and
|
||||
/// the gap to the page above is measured to the row's top, so a visible sliver of page 0 still counts (#7149).
|
||||
#[test]
|
||||
fn the_page_in_view_measures_to_the_next_spreads_top() {
|
||||
use craft::behavior::kurbo::Size;
|
||||
use craft::pages::layout::{LayoutOptions, PageDisplay, PageSpacing, place_pages};
|
||||
// Heights 100,100 | 100,200: the taller page of the second spread sits higher than its shorter neighbour.
|
||||
let sizes = [Size::new(80.0, 100.0), Size::new(80.0, 100.0), Size::new(80.0, 100.0), Size::new(80.0, 200.0)];
|
||||
let spacing = PageSpacing { gap: 10.0, margin: 0.0, side: 0.0, white_space_pad: 0.0, seam: 1.0 };
|
||||
let options = LayoutOptions { display: PageDisplay::TwoUp, cover: false, ..LayoutOptions::WORD };
|
||||
let layout = place_pages(&sizes, 1.0, Size::new(400.0, 400.0), &options, &spacing);
|
||||
assert!(layout.rects[2].y0 > layout.rects[3].y0, "the shorter page is centred below the row's top");
|
||||
let row_end = layout.rects[0].y1;
|
||||
let at = |shown: f64| row_end - shown;
|
||||
assert_eq!(viewed_page(None, at(spacing.gap * 2.0), &layout, 100.0), 0, "more than the gap of the first spread shows");
|
||||
assert_eq!(viewed_page(None, at(spacing.gap / 2.0), &layout, 100.0), 2, "less than the gap is a sliver");
|
||||
}
|
||||
|
||||
/// #856: the left margin beside body text is Word's selection bar. A click selects the line,
|
||||
/// a double-click the paragraph, a triple-click (or Ctrl/⌘+click) the document; dragging
|
||||
/// selects whole lines and Shift+click extends by lines.
|
||||
@@ -2604,6 +2622,72 @@ fn hostile_numbers_are_ignored() {
|
||||
assert!(h.state().canvas.view.offset.0.is_finite() && h.state().canvas.view.offset.1.is_finite());
|
||||
}
|
||||
|
||||
/// `viewed_page` with the sliver of the page above that Go To leaves at the top of the window: it is not the page in view.
|
||||
#[test]
|
||||
fn a_sliver_of_the_page_above_is_not_the_page_in_view() {
|
||||
let rects: Vec<craft::behavior::kurbo::Rect> =
|
||||
(0..4).map(|i| craft::behavior::kurbo::Rect::new(0.0, f64::from(i) * 110.0, 80.0, f64::from(i) * 110.0 + 100.0)).collect();
|
||||
let layout = craft::pages::layout::PagedLayout { rects, size: Default::default(), columns: 1, bands: vec![(0.0, 100.0); 4] };
|
||||
// The gap between pages is 10; page 2 ends at 320. A window top 4 above its end shows 4 of it: a sliver.
|
||||
assert_eq!(viewed_page(None, 316.0, &layout, 100.0), 3, "4 points of page 2 is a sliver");
|
||||
assert_eq!(viewed_page(None, 310.0, &layout, 100.0), 3, "as much as the gap is still a sliver");
|
||||
assert_eq!(viewed_page(None, 300.0, &layout, 100.0), 2, "20 points of page 2 is the page in view");
|
||||
}
|
||||
|
||||
/// In Columns and Two Up the pages are stored row by row: the gap to measure is the one to the page below, not to the
|
||||
/// page beside.
|
||||
#[test]
|
||||
fn a_sliver_of_a_row_above_is_not_the_page_in_view_with_columns() {
|
||||
let rects: Vec<craft::behavior::kurbo::Rect> = [(0.0, 0.0), (90.0, 0.0), (0.0, 110.0), (90.0, 110.0)]
|
||||
.iter()
|
||||
.map(|&(x, y)| craft::behavior::kurbo::Rect::new(x, y, x + 80.0, y + 100.0))
|
||||
.collect();
|
||||
let layout = craft::pages::layout::PagedLayout { rects, size: Default::default(), columns: 2, bands: vec![(0.0, 100.0); 4] };
|
||||
// The first row ends at 100 and the next starts at 110: a window top at 96 shows 4 points of it, a sliver.
|
||||
assert_eq!(viewed_page(None, 96.0, &layout, 100.0), 2, "4 points of the row above is a sliver");
|
||||
assert_eq!(viewed_page(None, 80.0, &layout, 100.0), 0, "20 points of the first row is the page in view");
|
||||
}
|
||||
|
||||
/// A last row that is not full has no page below the one above it: the gap is still the one to the next row.
|
||||
#[test]
|
||||
fn a_sliver_of_a_row_above_is_not_the_page_in_view_with_an_incomplete_last_row() {
|
||||
let rects: Vec<craft::behavior::kurbo::Rect> =
|
||||
[(0.0, 0.0), (90.0, 0.0), (0.0, 110.0)].iter().map(|&(x, y)| craft::behavior::kurbo::Rect::new(x, y, x + 80.0, y + 100.0)).collect();
|
||||
let layout = craft::pages::layout::PagedLayout { rects, size: Default::default(), columns: 2, bands: vec![(0.0, 100.0); 3] };
|
||||
assert_eq!(viewed_page(None, 96.0, &layout, 100.0), 2, "4 points of the row above is a sliver");
|
||||
assert_eq!(viewed_page(None, 80.0, &layout, 100.0), 0, "20 points of the first row is the page in view");
|
||||
}
|
||||
|
||||
/// Pages of different heights share a row and the next row starts below the tallest: the gap is measured from the row's bottom.
|
||||
#[test]
|
||||
fn a_shorter_page_in_a_taller_row_is_still_the_page_in_view() {
|
||||
let rects: Vec<craft::behavior::kurbo::Rect> = [(0.0, 0.0, 100.0), (90.0, 0.0, 200.0), (0.0, 210.0, 100.0), (90.0, 210.0, 100.0)]
|
||||
.iter()
|
||||
.map(|&(x, y, h)| craft::behavior::kurbo::Rect::new(x, y, x + 80.0, y + h))
|
||||
.collect();
|
||||
let layout = craft::pages::layout::PagedLayout {
|
||||
rects,
|
||||
size: Default::default(),
|
||||
columns: 2,
|
||||
bands: vec![(0.0, 100.0), (0.0, 200.0), (0.0, 100.0), (0.0, 100.0)],
|
||||
};
|
||||
assert_eq!(viewed_page(None, 50.0, &layout, 100.0), 0, "the short page is fully visible, the row gap is 10 not 110");
|
||||
assert_eq!(viewed_page(None, 196.0, &layout, 100.0), 2, "4 points of the tall page's row is a sliver");
|
||||
}
|
||||
|
||||
/// Two Up with a cover: page 0 is a row of its own, so there is no page `columns` after it.
|
||||
#[test]
|
||||
fn a_sliver_of_the_cover_is_not_the_page_in_view() {
|
||||
let rects: Vec<craft::behavior::kurbo::Rect> = [(90.0, 0.0), (0.0, 110.0), (90.0, 110.0), (0.0, 220.0)]
|
||||
.iter()
|
||||
.map(|&(x, y)| craft::behavior::kurbo::Rect::new(x, y, x + 80.0, y + 100.0))
|
||||
.collect();
|
||||
let layout = craft::pages::layout::PagedLayout { rects, size: Default::default(), columns: 2, bands: vec![(0.0, 100.0); 4] };
|
||||
assert_eq!(viewed_page(None, 96.0, &layout, 100.0), 1, "4 points of the cover is a sliver");
|
||||
assert_eq!(viewed_page(None, 80.0, &layout, 100.0), 0, "20 points of the cover is the page in view");
|
||||
assert_eq!(viewed_page(None, 206.0, &layout, 100.0), 3, "4 points of the spread is a sliver");
|
||||
}
|
||||
|
||||
/// A window in the background shows no caret and asks for no frames to blink one (#7674). The page keeps the keyboard
|
||||
/// focus, so the caret blinks again once the window is active again.
|
||||
#[test]
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
//! - `ui.clickText {page, x, y}`: click at a page position (points from the page's top-left)
|
||||
//! - `ui.dialog.set`, `ui.dialog.confirm`, `ui.dialog.cancel`: the open dialogs' fields and answers
|
||||
//! - `ui.screenshot {path?, region?}`: PNG of the window (or of `region` `[x0, y0, x1, y1]` in points); `ui.render {path?, page?, scale?}`: page PNG
|
||||
//! (without `path`, both reply with the PNG as base64 `png`)
|
||||
//! (without `path`, the reply carries the PNG as base64: `base64` for a screenshot, `png` for a render)
|
||||
//! - `ui.resize`, `ui.focus`, `ui.closeWindow`, `ui.clipboard`, `ui.replayAt`, `ui.accessTree`
|
||||
//! - `ui.parity`: feature catalog parity
|
||||
//!
|
||||
|
||||
@@ -5,7 +5,7 @@ use craft::automation::control::{ControlRequest, Reply};
|
||||
use craft::automation::dialogs;
|
||||
use craft::automation::synthetic::input_method;
|
||||
use craft::ui::runtime::commands::{ClipItem, ClipboardHandle};
|
||||
use craft::ui::runtime::windows::{WindowAction, WindowHost};
|
||||
use craft::ui::runtime::windows::{WindowAction, WindowHost, windowless_root};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::screenshots::render_png;
|
||||
@@ -81,6 +81,13 @@ pub(crate) fn close_refused(app: &WordApp, id: &str, params: &Value) -> Option<&
|
||||
// The document the command closes: `file.close` the shown one, `file.closeDocument` the one
|
||||
// its `id` names (the active one by default) (#3274).
|
||||
let target = match id {
|
||||
// `save: true` is saved, then closed, by `file.close` itself (spec rule 8); a comment
|
||||
// still being typed is not saved by that, so it still refuses.
|
||||
"file.close" if params.get("save").and_then(Value::as_bool) == Some(true) => {
|
||||
let force = params.get("force").and_then(Value::as_bool) == Some(true);
|
||||
let target = app.session.document_id();
|
||||
return (!force && app.document_has_comment_drafts(target)).then_some(COMMENT_UNSAVED);
|
||||
}
|
||||
"file.close" => app.session.document_id(),
|
||||
"file.closeDocument" => match params.get("id") {
|
||||
None | Some(Value::Null) => app.session.document_id(),
|
||||
@@ -89,7 +96,8 @@ pub(crate) fn close_refused(app: &WordApp, id: &str, params: &Value) -> Option<&
|
||||
},
|
||||
_ => return None,
|
||||
};
|
||||
close_refused_for(app, target, params)
|
||||
let refusal = close_refused_for(app, target, params);
|
||||
if id == "file.close" && refusal == Some(UNSAVED) { Some(UNSAVED_CLOSE) } else { refusal }
|
||||
}
|
||||
|
||||
/// The refusal for closing the document `target` with unsaved work in it: the same work the
|
||||
@@ -109,6 +117,9 @@ fn close_refused_for(app: &WordApp, target: u64, params: &Value) -> Option<&'sta
|
||||
}
|
||||
|
||||
const UNSAVED: &str = "the document has unsaved changes: save it first, or pass {\"force\": true} to discard them and close";
|
||||
/// `file.close` also takes `save` (spec rule 8).
|
||||
const UNSAVED_CLOSE: &str =
|
||||
"unsaved changes: pass save or force ({\"save\": true} writes the document, then closes; {\"force\": true} closes without saving)";
|
||||
const COMMENT_UNSAVED: &str = "a comment is still being edited: finish it first, or pass {\"force\": true} to discard it";
|
||||
|
||||
/// Quitting closes every open document, so unsaved work needs the same explicit `force` as
|
||||
@@ -406,7 +417,25 @@ fn handle_request(app: &mut WordApp, ctx: &egui::Context, req: &ControlRequest)
|
||||
ok(json!({}))
|
||||
}
|
||||
// Close the active window through the same guard as its OS close button.
|
||||
"ui.closeWindow" => ok(json!({"requested": WindowHost::of(ctx).act(app.active_viewport(), WindowAction::Close)})),
|
||||
// `window` names another window by its key; none means the active one (spec rule 8).
|
||||
"ui.closeWindow" => {
|
||||
let viewport = match p.get("window").filter(|w| !w.is_null()) {
|
||||
None => app.active_viewport(),
|
||||
Some(w) => match w.as_u64().and_then(|key| app.window_viewport(key)) {
|
||||
Some(v) => v,
|
||||
None => return err("`window` is not an open window: use a key from view.switchWindows"),
|
||||
},
|
||||
};
|
||||
// Spec rule 4: a close while a Save prompt is up only raises that prompt, so nothing was requested.
|
||||
if app.raise_closing().is_some() {
|
||||
return ok(json!({"requested": false, "reason": "a Save prompt is already open: answer it first"}));
|
||||
}
|
||||
// A windowless root is no window: closing it would end the app, not close a window.
|
||||
if viewport == egui::ViewportId::ROOT && windowless_root(ctx) {
|
||||
return err("no document window is open");
|
||||
}
|
||||
ok(json!({"requested": WindowHost::of(ctx).act(viewport, WindowAction::Close)}))
|
||||
}
|
||||
"ui.clipboard" => clipboard(ctx, p),
|
||||
"ui.replayAt" => {
|
||||
let Some(at) = p.get("at").and_then(Value::as_f64) else { return err("missing `at`") };
|
||||
|
||||
@@ -365,3 +365,28 @@ fn a_script_opens_the_dialog_a_launcher_command_asks_for() {
|
||||
assert!(r["result"]["icons"].is_array(), "{r}");
|
||||
assert!(b.dialog_host.open_dialogs().is_empty(), "a script's Insert Icon without an id opens no picker");
|
||||
}
|
||||
|
||||
/// Every method the Methods table of `docs/control-protocol.md` lists is one the control channel answers: none falls
|
||||
/// through to the commands as an unknown id. The input methods moved to the framework's names in #7101, and the table
|
||||
/// kept `ui.press`, `ui.drag` and `ui.text`.
|
||||
#[test]
|
||||
fn every_method_the_protocol_doc_lists_is_answered() {
|
||||
let doc = include_str!("../../../../docs/control-protocol.md");
|
||||
// `lines`, so a checkout with CRLF line endings (Windows) reads the table too.
|
||||
let methods: Vec<&str> = doc
|
||||
.lines()
|
||||
.skip_while(|line| *line != "## Methods")
|
||||
.skip_while(|line| !line.starts_with('|'))
|
||||
.take_while(|line| line.starts_with('|'))
|
||||
.filter_map(|row| row.strip_prefix("| `")?.split(" |").next())
|
||||
.flat_map(|cell| cell.split(" / "))
|
||||
.map(|name| name.trim_matches('`'))
|
||||
.collect();
|
||||
assert!(methods.contains(&"engine.execute"), "the Methods table: {methods:?}");
|
||||
let ctx = installed();
|
||||
for method in methods {
|
||||
let r = call(&mut app(), &ctx, method, json!({}));
|
||||
let unknown = wordcraft_engine::CmdError::Unknown(method.to_string()).to_string();
|
||||
assert_ne!(r["error"].as_str(), Some(unknown.as_str()), "the doc lists `{method}`, which the control channel doesn't answer");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,6 +81,7 @@ fn settle(app: &mut WordApp, _ctx: &egui::Context, id: DialogId) -> Settle {
|
||||
let result = match answer {
|
||||
HyperlinkAnswer::Set { link, text, .. } => {
|
||||
let places = link_places(app).map(|(_, refs)| refs).unwrap_or_default();
|
||||
let text = text.filter(|t| *t != tl!("<<Selection in document>>"));
|
||||
match link_params(&link.target, text.as_deref(), &places) {
|
||||
Some(params) => app.run("insert.link", params).map(|_| ()).map_err(Label::from),
|
||||
None => Err(Label::from(tl!("That place is no longer in the document."))),
|
||||
@@ -94,11 +95,21 @@ fn settle(app: &mut WordApp, _ctx: &egui::Context, id: DialogId) -> Settle {
|
||||
Settle::Keep
|
||||
}
|
||||
|
||||
/// The text Text to display shows: the selected text, or a placeholder when the selection is not
|
||||
/// plain text in one line of one paragraph (#8286). `insert.link` keeps such a selection as it is,
|
||||
/// so the placeholder is never written. lean: still editable, craft-libs has no read-only field.
|
||||
fn display_text(app: &WordApp) -> String {
|
||||
if wordcraft_engine::cmd::insert::selection_is_one_line(&app.session) {
|
||||
app.session.selected_text()
|
||||
} else {
|
||||
tl!("<<Selection in document>>").to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens Insert › Link on the selected text.
|
||||
pub(crate) fn open(app: &mut WordApp, _name: &str, _params: &Value, parent: Option<DialogId>) -> Option<DialogId> {
|
||||
let (groups, _) = link_places(app)?;
|
||||
let dialog =
|
||||
HyperlinkDialog::new(CurrentLink::None, Some(app.session.selected_text())).place_groups(groups).parts(HyperlinkParts::NoScreenTip).held_ok();
|
||||
let dialog = HyperlinkDialog::new(CurrentLink::None, Some(display_text(app))).place_groups(groups).parts(HyperlinkParts::NoScreenTip).held_ok();
|
||||
Some(open_with(app, parent, Keyed::new("link", dialog), DialogHooks { prepare: None, settle }))
|
||||
}
|
||||
|
||||
|
||||
@@ -2364,9 +2364,12 @@ fn modal_dialog_with_open_popup_does_not_shake_on_inside_click_but_shakes_on_out
|
||||
#[test]
|
||||
fn bare_fields_and_groups_draw_their_captions() {
|
||||
use egui::accesskit::Role;
|
||||
for (dialog, captions) in
|
||||
[("envelopes", &["Delivery address", "Return address", "Envelope size"][..]), ("dropCap", &["Position", "Lines to drop"][..])]
|
||||
{
|
||||
for (dialog, captions) in [
|
||||
("envelopes", &["Delivery address", "Return address", "Envelope size"][..]),
|
||||
("dropCap", &["Position", "Lines to drop"][..]),
|
||||
("mergeRecords", &["To:"][..]),
|
||||
("printRecords", &["To:"][..]),
|
||||
] {
|
||||
let mut h = app_harness(app_with("Lanterns"));
|
||||
h.state_mut().run("ui.dialog", json!({"name": dialog})).unwrap();
|
||||
h.run_steps(6);
|
||||
|
||||
@@ -321,9 +321,11 @@ impl WordApp {
|
||||
}
|
||||
// Word XML even over a Word 2003 XML file, which a save by path would keep.
|
||||
let format = if ext == "xml" { wordcraft_engine::cmd::file::FORMAT_FLAT_OPC } else { crate::print_page::EXPORT_WORD_2003 };
|
||||
self.run("file.saveAs", json!({"path": path, "format": format}))
|
||||
// An export is a copy: the document keeps its own file and changes (#6131).
|
||||
self.run("file.saveAs", json!({"path": path, "format": format, "copy": true}))
|
||||
} else {
|
||||
self.run("file.saveAs", json!({"path": path}))
|
||||
// An export is a copy: the document keeps its own file and changes (#6131).
|
||||
self.run("file.saveAs", json!({"path": path, "copy": true}))
|
||||
};
|
||||
match &r {
|
||||
Ok(_) => {
|
||||
|
||||
@@ -167,6 +167,19 @@ fn imported_word_close_waits_for_save_as_and_keeps_failed_or_cancelled_drafts()
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// Spec rules 5 and 6: cancelling the Save As a quit's Save opened cancels the quit.
|
||||
#[test]
|
||||
fn cancelling_save_as_cancels_the_quit() {
|
||||
let (mut a, files) = async_app();
|
||||
a.run("text.insert", json!({"text": "Draft"})).unwrap();
|
||||
assert!(!a.quit());
|
||||
assert_eq!(a.run("ui.saveChanges", json!({"answer": "save"})).unwrap()["pending"], "saveAs");
|
||||
answer(&files, None);
|
||||
assert_eq!(a.poll_file_dialog().unwrap().unwrap()["done"], false);
|
||||
assert!(a.closing.is_none() && !a.quit_requested && a.session.dirty, "nothing closes, nothing is lost");
|
||||
assert!(!a.quit(), "the next quit asks again");
|
||||
}
|
||||
|
||||
/// A late Save As answer belongs to the imported document that opened the picker: once that
|
||||
/// document is closed, it writes nothing.
|
||||
#[test]
|
||||
@@ -993,3 +1006,51 @@ fn entries_expose_names_selection_and_picking() {
|
||||
let answer = h.state_mut().dialog_host.take::<FileChooser>();
|
||||
assert_eq!(answer, Some(DialogResult::Ok(Answer::Paths(vec![PathBuf::from("/d/chapter.docx")]))));
|
||||
}
|
||||
|
||||
/// #6131: File › Export to DOCX, ODT or RTF writes a copy. It ran a plain Save As, which made
|
||||
/// the copy the document's file and cleared its unsaved changes, so the next Save updated the
|
||||
/// copy and the original kept its old text.
|
||||
#[test]
|
||||
fn export_writes_a_copy_and_keeps_the_documents_file() {
|
||||
let dir = scratch("export-copy");
|
||||
for ext in ["docx", "odt", "rtf"] {
|
||||
let original = dir.join(format!("a-{ext}.docx"));
|
||||
let (mut a, _) = async_app();
|
||||
a.run("text.insert", json!({"text": "first"})).unwrap();
|
||||
a.run("file.save", json!({"path": original.to_string_lossy()})).unwrap();
|
||||
a.run("text.insert", json!({"text": " edited"})).unwrap();
|
||||
let copy = dir.join(format!("copy.{ext}"));
|
||||
a.finish_pick(AfterPick::Export { ext: ext.into() }, Some(copy.to_string_lossy().into_owned())).unwrap();
|
||||
assert_eq!(saved_text(©), "first edited", "{ext}: the copy has the edits");
|
||||
assert_eq!(a.session.path.as_deref(), Some(original.as_path()), "{ext}: the document keeps its file");
|
||||
assert!(a.session.dirty, "{ext}: the document keeps its unsaved changes");
|
||||
a.run("file.save", json!({})).unwrap();
|
||||
assert_eq!(saved_text(&original), "first edited", "{ext}: Save still writes the original");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// #6131, browser: exporting a DOCX, ODT or RTF copy downloads it and leaves the document's
|
||||
/// unsaved changes and save stamps alone.
|
||||
#[test]
|
||||
fn web_export_downloads_a_copy_and_keeps_unsaved_changes() {
|
||||
let files = Arc::new(ScriptedFiles::new().in_browser().saving_suggested());
|
||||
let mut a = app_over(&files, wordcraft_doc::Document::new());
|
||||
typed(&mut a);
|
||||
for ext in ["docx", "odt", "rtf"] {
|
||||
let revision = a.session.doc.core.revision;
|
||||
let name = format!("copy.{ext}");
|
||||
let result = a.finish_pick(AfterPick::Export { ext: ext.into() }, Some(name.clone())).unwrap();
|
||||
assert_eq!(result["downloaded"], name, "{ext}");
|
||||
let request = files.requests().pop().unwrap();
|
||||
assert_eq!(request.file_name.as_deref(), Some(name.as_str()), "{ext}");
|
||||
assert!(!request.save_as, "{ext}: a copy is never Save As");
|
||||
let bytes = files.file(std::path::Path::new(&name)).unwrap();
|
||||
let back = wordcraft_engine::io::open_bytes(&name, &bytes).unwrap();
|
||||
assert_eq!(back.plain_text(wordcraft_doc::StoryRef::Body), UNSAVED, "{ext}: the copy has the text");
|
||||
a.settle_saves();
|
||||
assert!(a.session.dirty, "{ext}: the document keeps its unsaved changes");
|
||||
assert!(a.session.path.is_none(), "{ext}: the document keeps no file of its own");
|
||||
assert_eq!(a.session.doc.core.revision, revision, "{ext}: the document's save stamps are untouched");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -636,4 +636,90 @@ mod tests {
|
||||
});
|
||||
assert!(!shapes.is_empty(), "{KEY} icon must paint");
|
||||
}
|
||||
|
||||
/// #7450: the Dictate microphone icon parses cleanly on a `0 0 20 20` viewBox, keeps a
|
||||
/// rounded capsule (`rx >= width / 2`) clear of the U-stand cradle, and renders at 16–22 pt.
|
||||
#[test]
|
||||
fn dictate_icon_geometry_and_rendering() {
|
||||
use craft::theme::{Contrast, Mode};
|
||||
use craft::ui::testing::{Frames, style};
|
||||
|
||||
let (_, bytes) = WORDCRAFT_ICONS.icons.iter().find(|(name, _)| *name == "dictate").expect("dictate is registered");
|
||||
let svg = std::str::from_utf8(bytes).expect("an SVG document is text");
|
||||
|
||||
let tree = craft::ui::primitives::svg_tree::parse(bytes).expect("dictate.svg must parse as a valid SVG document");
|
||||
let size = tree.size();
|
||||
assert_eq!(size.width(), 20.0, "icon viewBox width must be 20");
|
||||
assert_eq!(size.height(), 20.0, "icon viewBox height must be 20");
|
||||
|
||||
fn attr_str<'a>(tag: &'a str, name: &str) -> &'a str {
|
||||
let elem = tag.split('>').next().unwrap_or(tag);
|
||||
let needle = format!("{name}=\"");
|
||||
let start = elem
|
||||
.match_indices(&needle)
|
||||
.find(|&(idx, _)| idx == 0 || elem.as_bytes()[idx - 1].is_ascii_whitespace())
|
||||
.map(|(idx, _)| idx + needle.len())
|
||||
.unwrap_or_else(|| panic!("missing {name} on {elem}"));
|
||||
&elem[start..elem[start..].find('"').map_or(elem.len(), |i| start + i)]
|
||||
}
|
||||
let attr = |tag: &str, name: &str| -> f32 {
|
||||
let val = attr_str(tag, name);
|
||||
val.parse::<f32>().unwrap_or_else(|_| panic!("non-numeric {name}: {val}"))
|
||||
};
|
||||
|
||||
let root = svg.split("<svg").nth(1).expect("dictate.svg must contain a root <svg> element");
|
||||
assert_eq!(attr_str(root, "viewBox"), "0 0 20 20", "root SVG viewBox must be 0 0 20 20");
|
||||
|
||||
let rect = svg.split("<rect").nth(1).expect("dictate.svg must contain a <rect> capsule");
|
||||
let cap_x = attr(rect, "x");
|
||||
let cap_y = attr(rect, "y");
|
||||
let width = attr(rect, "width");
|
||||
let height = attr(rect, "height");
|
||||
let rx = attr(rect, "rx");
|
||||
let cap_stroke = attr(rect, "stroke-width");
|
||||
let cradle = svg.split("<path").nth(1).expect("dictate.svg must contain a cradle <path>");
|
||||
let cradle_stroke = attr(cradle, "stroke-width");
|
||||
let half_strokes = (cap_stroke + cradle_stroke) / 2.0;
|
||||
|
||||
assert!(rx >= width / 2.0, "capsule corner radius ({rx}) must be at least half the width ({width})");
|
||||
assert!(cap_y + height < 15.0, "capsule bottom ({}) must stay clear of the cradle bottom (15.0)", cap_y + height);
|
||||
assert!(cap_x > 5.0 && cap_x + width < 15.0, "capsule x-span ({}..{}) must stay inside the cradle arms (5..15)", cap_x, cap_x + width);
|
||||
|
||||
fn dist_point_to_seg(p: (f32, f32), a: (f32, f32), b: (f32, f32)) -> f32 {
|
||||
let (vx, vy) = (b.0 - a.0, b.1 - a.1);
|
||||
let len_sq = vx * vx + vy * vy;
|
||||
let t = if len_sq > 0.0 { (((p.0 - a.0) * vx + (p.1 - a.1) * vy) / len_sq).clamp(0.0, 1.0) } else { 0.0 };
|
||||
let (dx, dy) = (p.0 - (a.0 + t * vx), p.1 - (a.1 + t * vy));
|
||||
(dx * dx + dy * dy).sqrt()
|
||||
}
|
||||
let cradle_segs = [((5.0_f32, 9.5_f32), (5.0, 11.0)), ((5.0, 11.0), (10.0, 15.0)), ((10.0, 15.0), (15.0, 11.0)), ((15.0, 11.0), (15.0, 9.5))];
|
||||
let mut cap_points = vec![(cap_x, 9.5_f32), (cap_x + width, 9.5_f32), (cap_x + width / 2.0, cap_y + height)];
|
||||
let (arc_cx, arc_cy, arc_r) = (cap_x + width / 2.0, cap_y + height - rx, rx);
|
||||
for step in 0..=8 {
|
||||
let angle = std::f32::consts::PI * (step as f32) / 8.0;
|
||||
cap_points.push((arc_cx - arc_r * angle.cos(), arc_cy + arc_r * angle.sin()));
|
||||
}
|
||||
let min_clearance =
|
||||
cap_points.iter().flat_map(|&p| cradle_segs.iter().map(move |&(a, b)| dist_point_to_seg(p, a, b))).fold(f32::INFINITY, f32::min);
|
||||
assert!(min_clearance > half_strokes, "capsule outline clearance ({min_clearance:.2}) must exceed combined half-strokes ({half_strokes:.2})");
|
||||
|
||||
register();
|
||||
let tokens = style::tokens(Mode::Light, Contrast::Standard);
|
||||
let mut frames = Frames::new();
|
||||
for pt in [16.0_f32, 19.0, 20.0, 22.0] {
|
||||
let target = Rect::from_min_size(Pos2::ZERO, egui::vec2(pt, pt));
|
||||
let icon = IconSpec::svg(IconId::new("dictate"));
|
||||
let (shapes, _) = style::paint_frame(&mut frames, &tokens, craft::i18n::Direction::Ltr, craft::ui::style::Ink::OnPanel, |draw| {
|
||||
draw.icon(target, &icon)
|
||||
});
|
||||
assert!(!shapes.is_empty(), "dictate icon must paint at {pt} pt");
|
||||
let bounds = shapes.iter().map(|s| s.visual_bounding_rect()).fold(Rect::NOTHING, |acc, r| acc.union(r));
|
||||
assert!(bounds.is_positive(), "dictate icon must have positive rendered bounds at {pt} pt, got {bounds:?}");
|
||||
assert!(target.expand(1.0).contains_rect(bounds), "dictate icon at {pt} pt overflowed target {target:?}: {bounds:?}");
|
||||
assert!(
|
||||
bounds.width() >= pt * 0.5 && bounds.height() >= pt * 0.5 && bounds.width() <= 22.5 && bounds.height() <= 22.5,
|
||||
"dictate icon rendered size at {pt} pt out of 16-22 pt bounds: {bounds:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ mod canvas;
|
||||
mod ime;
|
||||
mod shortcuts;
|
||||
|
||||
pub(crate) use canvas::{page_input, window_cancel};
|
||||
pub(crate) use canvas::{page_input, tick_paste_wait, window_cancel};
|
||||
pub(crate) use ime::report_editor;
|
||||
#[cfg(test)]
|
||||
use ime::{ImeProof, MAX_IME_COMMIT_BYTES, MAX_IME_PREEDIT_BYTES, classify_ime_proof};
|
||||
|
||||
@@ -75,6 +75,13 @@ pub fn page_input(app: &mut WordApp, inputs: &[EditorInput], pass: &ToolPass, ct
|
||||
if stale_composition(app, e, &mut batch) {
|
||||
continue;
|
||||
}
|
||||
if ignored_paste(app, ctx, e) {
|
||||
continue;
|
||||
}
|
||||
if is_key_input(e) || matches!(e, EditorInput::Text(_)) {
|
||||
app.canvas.ignore_next_paste = false;
|
||||
app.canvas.paste_wait_since = None;
|
||||
}
|
||||
if is_key_input(e) {
|
||||
app.canvas.ime_join_text = None;
|
||||
// A key between a deletion and its text means that text is fresh input, not the
|
||||
@@ -105,6 +112,64 @@ pub fn page_input(app: &mut WordApp, inputs: &[EditorInput], pass: &ToolPass, ct
|
||||
}
|
||||
}
|
||||
|
||||
/// How long the browser paste event paired with Mod+Shift+V is waited for (#5616).
|
||||
const PASTE_WAIT: f64 = 1.0;
|
||||
|
||||
/// Ends the wait for the browser paste event paired with Mod+Shift+V on a pointer press,
|
||||
/// focus change, or after `PASTE_WAIT` without one (#5616). Key and typing order against a
|
||||
/// queued paste is handled in `page_input` (after `craft` extracts `Event::Paste` into
|
||||
/// `EditorInput::Edit(EditCommand::Paste)`) and non-paste key commands clear it in `run_fired`.
|
||||
pub(crate) fn tick_paste_wait(app: &mut WordApp, ctx: &egui::Context) {
|
||||
if !app.canvas.ignore_next_paste {
|
||||
app.canvas.paste_wait_since = None;
|
||||
return;
|
||||
}
|
||||
let (now, clear) = ctx.input(|i| {
|
||||
let clear = i.events.iter().any(|e| matches!(e, egui::Event::PointerButton { pressed: true, .. } | egui::Event::WindowFocused(_)));
|
||||
(i.time, clear)
|
||||
});
|
||||
if clear || app.canvas.paste_wait_since.is_some_and(|t| now - t > PASTE_WAIT) {
|
||||
app.canvas.ignore_next_paste = false;
|
||||
app.canvas.paste_wait_since = None;
|
||||
}
|
||||
}
|
||||
|
||||
fn mod_shift_v_pressed_this_frame(ctx: &egui::Context) -> bool {
|
||||
let mac = craft::ui::runtime::windows::os_of(ctx) == craft::host::target::Os::Mac;
|
||||
let chord_pressed = ctx.input(|i| {
|
||||
i.events.iter().any(|ev| {
|
||||
matches!(ev, egui::Event::Key { key: Key::V, pressed: true, modifiers, .. } if modifiers.command && modifiers.shift && !modifiers.alt && (!mac || !modifiers.ctrl))
|
||||
})
|
||||
});
|
||||
if !chord_pressed {
|
||||
return false;
|
||||
}
|
||||
craft::keymap::Chord::parse("Mod+Shift+V").ok().is_some_and(|chord| {
|
||||
craft::ui::runtime::commands::holder(ctx, &chord) == Some(craft::ui::runtime::commands::CommandRef::new("edit.pasteFormat"))
|
||||
})
|
||||
}
|
||||
|
||||
/// The browser's paste event that follows a Mod+Shift+V that pasted formatting is the same
|
||||
/// keystroke: ignored before an equation or document paste can take it (#5616).
|
||||
fn ignored_paste(app: &mut WordApp, ctx: &egui::Context, e: &EditorInput) -> bool {
|
||||
if !matches!(e, EditorInput::Edit(EditCommand::Paste)) {
|
||||
return false;
|
||||
}
|
||||
if std::mem::take(&mut app.canvas.ignore_next_paste) {
|
||||
app.canvas.paste_wait_since = None;
|
||||
return true;
|
||||
}
|
||||
if app.canvas.paste_event_follows_chord
|
||||
&& !app.canvas.paste_event_consumed_same_frame
|
||||
&& (app.session.painter.is_some() || app.session.copied_format.is_some())
|
||||
&& mod_shift_v_pressed_this_frame(ctx)
|
||||
{
|
||||
app.canvas.paste_event_consumed_same_frame = true;
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Whether the input is a key's, not text or an input method's.
|
||||
fn is_key_input(e: &EditorInput) -> bool {
|
||||
matches!(
|
||||
|
||||
@@ -349,6 +349,41 @@ fn an_unrelated_keys_modifiers_do_not_steer_a_later_paste() {
|
||||
}
|
||||
}
|
||||
|
||||
/// #5616: the browser paste event after a formatting paste is dropped before an open equation
|
||||
/// can type it (while the same paste without Mod+Shift+V first reaches the equation).
|
||||
#[test]
|
||||
fn the_ignored_paste_event_never_reaches_an_open_equation() {
|
||||
// Control: without Mod+Shift+V first, the paste reaches the open equation.
|
||||
let mut control = app_harness(copied_bold_app());
|
||||
control.state_mut().canvas.paste_event_follows_chord = true;
|
||||
offer(&control, vec![ClipItem::Text("zzz".into())]);
|
||||
run(&mut control, "insert.equation", json!({"linear": "abc"}));
|
||||
mods_frame(&mut control, mod_held(), vec![egui::Event::Paste("zzz".into())]);
|
||||
assert_eq!(linear(&mut control), "abczzz", "control: Paste reaches an open equation without Mod+Shift+V first");
|
||||
|
||||
// Same-frame and delayed browser paste after Mod+Shift+V (Paste Formatting) are both ignored.
|
||||
for same_frame in [false, true] {
|
||||
let mut h = app_harness(copied_bold_app());
|
||||
h.state_mut().canvas.paste_event_follows_chord = true;
|
||||
offer(&h, vec![ClipItem::Text("zzz".into())]);
|
||||
run(&mut h, "insert.equation", json!({"linear": "abc"}));
|
||||
let chord = Modifiers { shift: true, ..mod_held() };
|
||||
let before = h.state().session.math.clone();
|
||||
assert!(before.is_some());
|
||||
if same_frame {
|
||||
batch_frame(&mut h, vec![key_event(Key::V, true, chord), egui::Event::Paste("zzz".into())]);
|
||||
crate::test_harness::frame(&mut h);
|
||||
} else {
|
||||
mods_frame(&mut h, chord, vec![key_event(Key::V, true, chord)]);
|
||||
mods_frame(&mut h, Modifiers::NONE, vec![key_event(Key::V, false, Modifiers::NONE)]);
|
||||
mods_frame(&mut h, mod_held(), vec![egui::Event::Paste("zzz".into())]);
|
||||
}
|
||||
assert_eq!(h.state().session.math, before, "same_frame={same_frame}: Paste Formatting keeps the equation open");
|
||||
assert_eq!(linear(&mut h), "abc", "same_frame={same_frame}: the ignored paste typed nothing into the equation");
|
||||
assert_eq!(body(h.state()), "source abc", "same_frame={same_frame}: the ignored paste did not paste into the body");
|
||||
}
|
||||
}
|
||||
|
||||
/// Paste Formatting on a chord the user bound pastes the copied formatting once.
|
||||
#[test]
|
||||
fn paste_formatting_on_another_key_pastes_the_copied_formatting() {
|
||||
@@ -362,6 +397,41 @@ fn paste_formatting_on_another_key_pastes_the_copied_formatting() {
|
||||
assert!(is_bold(&mut h), "the formatting was pasted onto the selection");
|
||||
}
|
||||
|
||||
/// F4 bound alongside Mod+Shift+V neither falls back to plain-text paste nor arms browser paste
|
||||
/// suppression when its modifiers are released.
|
||||
#[test]
|
||||
fn paste_formatting_on_f4_alongside_mod_shift_v_leaves_later_paste_alone() {
|
||||
let mut app = copied_bold_app();
|
||||
app.session.keymap_mut().insert(craft::keymap::CommandRef::new("edit.pasteFormat").key(), vec!["Mod+Shift+V".to_string(), "F4".to_string()]);
|
||||
let mut h = app_harness(app);
|
||||
h.state_mut().canvas.paste_event_follows_chord = true;
|
||||
mods_frame(&mut h, Modifiers::NONE, vec![key_event(Key::F4, true, Modifiers::NONE)]);
|
||||
mods_frame(&mut h, Modifiers::NONE, vec![key_event(Key::F4, false, Modifiers::NONE)]);
|
||||
assert!(is_bold(&mut h), "F4 pasted formatting");
|
||||
assert!(!h.state().canvas.ignore_next_paste, "F4 does not arm browser paste suppression even while Mod+Shift+V is bound");
|
||||
offer(&h, vec![ClipItem::Text("!".into())]);
|
||||
batch_frame(&mut h, vec![egui::Event::Paste("!".into())]);
|
||||
crate::test_harness::frame(&mut h);
|
||||
assert_eq!(body(h.state()), "source !", "a standalone paste right after F4 is not swallowed");
|
||||
}
|
||||
|
||||
/// A delayed browser paste followed immediately by typing in the same frame after Mod+Shift+V
|
||||
/// still suppresses the paired paste before typing runs.
|
||||
#[test]
|
||||
fn delayed_ignored_paste_followed_by_typing_in_same_frame_drops_only_paste() {
|
||||
let mut h = app_harness(copied_bold_app());
|
||||
h.state_mut().canvas.paste_event_follows_chord = true;
|
||||
offer(&h, vec![ClipItem::Text("zzz".into())]);
|
||||
let chord = Modifiers { shift: true, ..mod_held() };
|
||||
mods_frame(&mut h, chord, vec![key_event(Key::V, true, chord)]);
|
||||
mods_frame(&mut h, Modifiers::NONE, vec![key_event(Key::V, false, Modifiers::NONE)]);
|
||||
assert!(h.state().canvas.ignore_next_paste);
|
||||
|
||||
batch_frame(&mut h, vec![egui::Event::Paste("zzz".into()), key_event(Key::A, true, Modifiers::NONE), egui::Event::Text("a".into())]);
|
||||
crate::test_harness::frame(&mut h);
|
||||
assert_eq!(body(h.state()), "source a", "paired paste dropped, subsequent typing kept");
|
||||
}
|
||||
|
||||
/// A press or release of `key` with `modifiers`.
|
||||
fn key_event(key: Key, pressed: bool, modifiers: Modifiers) -> egui::Event {
|
||||
egui::Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers }
|
||||
|
||||
@@ -281,7 +281,9 @@ pub(crate) fn shapes(ui: &mut Ui, cx: &mut BodyCx<'_>, app: &mut WordApp) {
|
||||
.select(SelectMode::None)
|
||||
.activate(ActivateOn::Click)
|
||||
.card_columns(SHAPE_COLUMNS)
|
||||
.content_cells()
|
||||
// about 33 pt cells, as before the port (#7828): a medium thumbnail at 1.2x.
|
||||
.thumb_size(ThumbSize::Medium)
|
||||
.zoom(GridZoom::Fixed(1.2))
|
||||
// Every shape shows, as in production; the menu's body is the one scroll.
|
||||
.natural_height(true)
|
||||
.caption(CaptionPlace::None)
|
||||
|
||||
@@ -71,7 +71,11 @@ pub(super) fn insert(row: &mut RibbonRow<'_>, app: &mut WordApp) {
|
||||
|ui, cx| {
|
||||
let out = TableSizePicker::new(crate::tl!("Insert Table")).show(ui);
|
||||
if let Some((rows, cols)) = out.picked {
|
||||
let _ = app.run("insert.table", json!({"rows": rows, "cols": cols}));
|
||||
// The new table's first cell has the caret: the page takes the keyboard so typing goes into it,
|
||||
// as after a WordArt style pick. The closing menu would hand focus back to the Table button.
|
||||
if app.run("insert.table", json!({"rows": rows, "cols": cols})).is_ok() {
|
||||
app.canvas.focus_page(ui.ctx());
|
||||
}
|
||||
app.canvas.table_preview = None;
|
||||
cx.request_close();
|
||||
} else {
|
||||
@@ -378,6 +382,8 @@ fn symbol_grid(ui: &mut Ui, cx: &mut BodyCx<'_>, app: &mut WordApp) {
|
||||
let params = if font.is_empty() { json!({"char": c}) } else { json!({"char": c, "font": font}) };
|
||||
if app.run("insert.symbol", params).is_ok() {
|
||||
crate::dialogs_insert::remember_symbol(app, c, font);
|
||||
// The page takes the keyboard so typing goes on after the symbol, as after a pick on the Table grid.
|
||||
app.canvas.focus_page(ui.ctx());
|
||||
cx.request_close();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1103,6 +1103,28 @@ fn bullets_dropdown_renders_compact_bullet_tiles() {
|
||||
assert!((rect.width() - rect.height()).abs() <= 2.0, "bullet tile should be square: {}x{}", rect.width(), rect.height());
|
||||
}
|
||||
|
||||
/// The Bullet Library and the Symbol drop-down draw their symbols with the interface's own faces, under kittest's
|
||||
/// strict missing-glyph policy: neither the optional craft-fonts faces nor installed fonts may supply them.
|
||||
#[test]
|
||||
fn the_bullet_and_symbol_menus_draw_their_symbols_without_optional_or_installed_fonts() {
|
||||
use egui::accesskit::Role;
|
||||
|
||||
for (tab, menu, symbols) in [("Home", "Bullets options", ["○", "▪", "◆", "✓"]), ("Insert", "Symbol", ["✓", "★", "♥", "©"])] {
|
||||
let app = WordApp::new(Session::new(wordcraft_doc::Document::from_text("Sample")), crate::Services::default());
|
||||
let mut h = tab_harness(app, tab);
|
||||
crate::app::fonts::ui_fonts_with_optional_faces(crate::i18n::Lang::EN, &[])
|
||||
.system_fonts(craft::ui::fonts::SystemFonts::Off)
|
||||
.stack()
|
||||
.install(&h.ctx);
|
||||
// Bullets is a split button whose arrow node ("Bullets options") opens the menu; Symbol has one node.
|
||||
h.query_all(By::new().role(Role::Button).label(menu)).last().expect("the menu's button").click();
|
||||
crate::test_harness::frames(&mut h, 3);
|
||||
for symbol in symbols {
|
||||
assert!(h.query_all_by_label(symbol).next().is_some(), "{menu} shows {symbol}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// #7310: unimplemented stub ribbon buttons (Dictate, Ink to Math, Translate, Block Authors)
|
||||
/// resolve disabled in the ribbon UI and are known to the command catalog without warnings.
|
||||
#[test]
|
||||
@@ -1128,6 +1150,44 @@ fn unimplemented_stub_ribbon_buttons_are_disabled() {
|
||||
.find(|n| n.accesskit_node().label().is_some_and(|l| l.split_whitespace().collect::<Vec<_>>().join(" ") == expected_label))
|
||||
.unwrap_or_else(|| panic!("{tab}: ribbon button '{expected_label}' should exist"));
|
||||
assert!(button.accesskit_node().is_disabled(), "{tab}: stub button {:?} ({id}) must be disabled", button.accesskit_node().label());
|
||||
if expected_label == "Dictate" {
|
||||
fn push_icon_rects(shape: &egui::Shape, clip: egui::Rect, btn_rect: egui::Rect, out: &mut Vec<egui::Rect>) {
|
||||
match shape {
|
||||
egui::Shape::Vec(items) => {
|
||||
for item in items {
|
||||
push_icon_rects(item, clip, btn_rect, out);
|
||||
}
|
||||
}
|
||||
egui::Shape::Text(_) | egui::Shape::Noop => {}
|
||||
other => {
|
||||
let r = other.visual_bounding_rect().intersect(clip);
|
||||
if r.is_positive()
|
||||
&& btn_rect.expand(1.0).contains_rect(r)
|
||||
&& r.width() < btn_rect.width() * 0.9
|
||||
&& r.height() < btn_rect.height() * 0.9
|
||||
{
|
||||
out.push(r);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let btn_rect = button.rect();
|
||||
let mut icon_rects = Vec::new();
|
||||
for c in &h.output().shapes {
|
||||
push_icon_rects(&c.shape, c.clip_rect, btn_rect, &mut icon_rects);
|
||||
}
|
||||
let icon_rect = icon_rects
|
||||
.into_iter()
|
||||
.reduce(|a, b| a.union(b))
|
||||
.unwrap_or_else(|| panic!("Dictate button ({btn_rect:?}) must paint a bounded icon shape"));
|
||||
assert!(
|
||||
icon_rect.width() >= 16.0 && icon_rect.height() >= 16.0,
|
||||
"Dictate ribbon icon must render at >= 16 pt, got {}x{} ({icon_rect:?})",
|
||||
icon_rect.width(),
|
||||
icon_rect.height()
|
||||
);
|
||||
assert!((icon_rect.width() - icon_rect.height()).abs() <= 2.0, "Dictate icon should be square: {icon_rect:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1539,7 +1539,11 @@ fn prompt_message(a: &WordApp) -> Option<String> {
|
||||
fn prompt(a: &WordApp) -> Option<&'static str> {
|
||||
// The close operation is the app's, the question is the drawn window's: a prompt asked in the window of a document
|
||||
// that another window replaced is no longer the question this window asks.
|
||||
if a.closing.as_ref().and_then(|c| c.prompt).is_some_and(|id| a.dialog_host.get_by_id::<craft::ui::dialog::UnsavedChangesDialog>(id).is_some()) {
|
||||
if a.closing
|
||||
.as_ref()
|
||||
.and_then(|c| c.prompt)
|
||||
.is_some_and(|id| a.dialog_host.get_by_id::<craft::ui::dialog::HostedUnsavedChangesDialog>(id).is_some())
|
||||
{
|
||||
return Some("saveChanges");
|
||||
}
|
||||
let (key, _) = open_dialog(a)?;
|
||||
@@ -2648,6 +2652,26 @@ fn host_save_as_a_copy_format_is_not_save_as() {
|
||||
assert_eq!(a.session.path.as_deref(), Some(std::path::Path::new("report.docx")));
|
||||
}
|
||||
|
||||
/// A copy named like the opened file can't go to the host page, whose Save would overwrite the
|
||||
/// opened file with it (#6131 review). The bridge strips any directory from `path`, so a path
|
||||
/// whose file name matches the opened document is refused too.
|
||||
#[test]
|
||||
fn host_copy_with_the_opened_name_is_refused() {
|
||||
let (mut a, got) = host_app(false);
|
||||
host_open(&mut a, "report.docx");
|
||||
for path in ["report.docx", "./report.docx", "/tmp/report.docx"] {
|
||||
let e = a.execute("file.saveAs", json!({"path": path, "copy": true})).unwrap_err();
|
||||
assert!(e.contains("same name"), "{path}: {e}");
|
||||
}
|
||||
assert!(got.borrow().is_empty(), "nothing reached the host");
|
||||
assert!(a.session.dirty);
|
||||
a.execute("file.saveAs", json!({"path": "other.docx", "copy": true})).unwrap();
|
||||
a.settle_saves();
|
||||
assert_eq!(got.borrow().first().map(|(n, s, _)| (n.as_str(), *s)), Some(("other.docx", false)));
|
||||
assert_eq!(a.session.path.as_deref(), Some(std::path::Path::new("report.docx")));
|
||||
assert!(a.session.dirty);
|
||||
}
|
||||
|
||||
/// The page not getting the file is a failed save: the document keeps its changes.
|
||||
#[test]
|
||||
fn a_host_save_that_fails_leaves_the_document_unsaved() {
|
||||
|
||||
@@ -160,3 +160,39 @@ fn citations_provider_menu_has_zotero_checked() {
|
||||
let checked = items.first().map(|n| n.accesskit_node().toggled().is_some() || n.accesskit_node().is_selected().is_some());
|
||||
assert_eq!(checked, Some(true), "and it is marked as the chosen one");
|
||||
}
|
||||
|
||||
/// A size picked on Insert › Table's grid, with the pointer or the keys, hands the keyboard to the new table, so
|
||||
/// what is typed next goes into its first cell. The menu's close gave focus back to the Table button, and the typing
|
||||
/// was lost.
|
||||
#[test]
|
||||
fn typing_after_a_table_grid_pick_goes_into_the_new_table() {
|
||||
use egui::accesskit::Role;
|
||||
for by_keys in [false, true] {
|
||||
let how = if by_keys { "keys" } else { "pointer" };
|
||||
let mut a = app();
|
||||
a.ui.mini_toolbar = false;
|
||||
a.run("ui.tab", json!({"tab": "Insert"})).unwrap();
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1920.0, 900.0)).build_eframe(|_| a);
|
||||
h.run_steps(2);
|
||||
if by_keys {
|
||||
// Enter on the focused Table button opens the grid on 1 × 1; the arrows move to 2 × 2 and Enter picks it.
|
||||
h.get_by_role_and_label(Role::Button, "Table").focus();
|
||||
h.run_steps(3);
|
||||
for key in [egui::Key::Enter, egui::Key::ArrowRight, egui::Key::ArrowDown, egui::Key::Enter] {
|
||||
h.key_press(key);
|
||||
h.run_steps(3);
|
||||
}
|
||||
} else {
|
||||
h.get_by_role_and_label(Role::Button, "Table").click();
|
||||
h.run_steps(3);
|
||||
h.get_by_role_and_label(Role::GridCell, "2x2 Table").click();
|
||||
h.run_steps(3);
|
||||
}
|
||||
assert!(h.state().session.sel.focus.path.cell().is_some(), "{how}: the caret is in the new table");
|
||||
assert!(h.state().canvas.focused(&h.ctx), "{how}: the page has the keyboard after the pick");
|
||||
h.event(egui::Event::Text("Copper".into()));
|
||||
h.run_steps(2);
|
||||
let s = &h.state().session;
|
||||
assert_eq!(s.doc.para_at(&s.sel.focus).unwrap().text, "Copper", "{how}: the typing went into the first cell");
|
||||
}
|
||||
}
|
||||
|
||||
+108
-22
@@ -30,7 +30,8 @@
|
||||
use craft::ui::contract::{BodyCx, Props as _, ShowContainer as _, SizeLimits};
|
||||
// PLAN: assumed `craft::ui::runtime::env::WindowKey` is the facade path of ui-contract's `runtime/env/shell.rs` `WindowKey`.
|
||||
use craft::ui::runtime::env::WindowKey;
|
||||
use craft::ui::runtime::windows::{WindowAction, WindowHost};
|
||||
use craft::ui::runtime::memory::SaveKey;
|
||||
use craft::ui::runtime::windows::{WindowAction, WindowHost, windowless_root};
|
||||
use craft::ui::shell::DocumentWindow;
|
||||
use craft::ui::style::StyleCx;
|
||||
use craft::window::{Document, WindowId, WindowList, WindowMenu};
|
||||
@@ -112,6 +113,11 @@ pub struct Windows {
|
||||
/// Whether the root OS window had focus in the last pass; a [`DocumentWindow`] reports its own gain
|
||||
/// (`focus_gained`), the root's is read from the window host's facts.
|
||||
root_focused: bool,
|
||||
/// Whether the root entry's window got its first placement (windowless root only: the root has
|
||||
/// no OS window to take the saved place, so the first document window does).
|
||||
root_placed: bool,
|
||||
/// Documents whose window could not open: they get no new window, or every frame would retry.
|
||||
failed_open: Vec<u64>,
|
||||
}
|
||||
|
||||
impl Windows {
|
||||
@@ -119,7 +125,16 @@ impl Windows {
|
||||
pub(crate) fn new(doc: u64) -> Windows {
|
||||
let mut list = WindowList::new();
|
||||
let id = list.open(Window::new(doc, None, None, false));
|
||||
Windows { native: cfg!(not(target_arch = "wasm32")), list, root: id, shown: id, arranged: arrange::State::default(), root_focused: false }
|
||||
Windows {
|
||||
native: cfg!(not(target_arch = "wasm32")),
|
||||
list,
|
||||
root: id,
|
||||
shown: id,
|
||||
arranged: arrange::State::default(),
|
||||
root_focused: false,
|
||||
root_placed: false,
|
||||
failed_open: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether documents get native windows of their own.
|
||||
@@ -192,7 +207,7 @@ impl Windows {
|
||||
/// The viewport window `id` draws in, while its OS window is open: the root's for the root
|
||||
/// entry, else the one the window host names for the window's container.
|
||||
fn viewport_of(&self, ctx: &egui::Context, id: WindowId) -> Option<ViewportId> {
|
||||
if id == self.root {
|
||||
if id == self.root && !windowless_root(ctx) {
|
||||
return Some(ViewportId::ROOT);
|
||||
}
|
||||
WindowHost::of(ctx).viewport_of(window_container_id(id))
|
||||
@@ -212,11 +227,21 @@ impl WordApp {
|
||||
|
||||
/// The egui viewport of the active window, the one focused last: control input,
|
||||
/// `ui.screenshot` and `ui.resize` are its. The root viewport when the windows don't have
|
||||
/// viewports of their own (the web app, embedded viewports) or the window has none yet.
|
||||
/// viewports of their own (the web app, embedded viewports). With a windowless root it is always a
|
||||
/// document viewport (the root has no window to draw, screenshot or take input), the first open one
|
||||
/// when the active window has none yet; the root only before any document window exists.
|
||||
pub fn active_viewport(&self) -> ViewportId {
|
||||
let Some(ctx) = self.ctx.as_ref().filter(|ctx| self.windows.native && WindowHost::of(ctx).opens_windows()) else { return ViewportId::ROOT };
|
||||
let id = self.windows.list.active().unwrap_or(self.windows.shown);
|
||||
self.windows.viewport_of(ctx, id).unwrap_or(ViewportId::ROOT)
|
||||
let own = self.windows.viewport_of(ctx, id);
|
||||
if windowless_root(ctx) { own.or_else(|| self.windows.viewports(ctx).first().copied()) } else { own }.unwrap_or(ViewportId::ROOT)
|
||||
}
|
||||
|
||||
/// The viewport of the window with key `key` (the number `view.switchWindows` and the window
|
||||
/// menu give): `None` when there is no such window or its OS window isn't open yet.
|
||||
pub fn window_viewport(&self, key: u64) -> Option<ViewportId> {
|
||||
let ctx = self.ctx.as_ref().filter(|ctx| self.windows.native && WindowHost::of(ctx).opens_windows())?;
|
||||
self.windows.viewport(ctx, key)
|
||||
}
|
||||
|
||||
/// Whether a close request for the root viewport closes only the window drawn there: true
|
||||
@@ -382,7 +407,12 @@ impl WordApp {
|
||||
let behind = self.windows.list.active();
|
||||
let active = self.session.document_id();
|
||||
for d in self.session.documents() {
|
||||
if d.id == active || Some(d.id) == self.no_document || d.id == self.shown_document || self.windows.of_doc(d.id).is_some() {
|
||||
if d.id == active
|
||||
|| Some(d.id) == self.no_document
|
||||
|| d.id == self.shown_document
|
||||
|| self.windows.of_doc(d.id).is_some()
|
||||
|| self.windows.failed_open.contains(&d.id)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
self.windows.list.open(Window::new(d.id, Some(Box::new(WindowUi::new(d.id))), None, true));
|
||||
@@ -462,7 +492,9 @@ impl WordApp {
|
||||
w.requests.push(req.clone());
|
||||
}
|
||||
if let Some(ctx) = &self.ctx {
|
||||
ctx.request_repaint_of(self.windows.viewport(ctx, key).unwrap_or(ViewportId::ROOT));
|
||||
ctx.request_repaint_of(
|
||||
self.windows.viewport(ctx, key).or_else(|| self.windows.viewports(ctx).first().copied()).unwrap_or(ViewportId::ROOT),
|
||||
);
|
||||
}
|
||||
true
|
||||
}
|
||||
@@ -535,22 +567,28 @@ impl WordApp {
|
||||
self.after_windows();
|
||||
return;
|
||||
}
|
||||
let raise_root = self.windows.list.get_mut(self.windows.root).is_some_and(|w| std::mem::take(&mut w.raise));
|
||||
if raise_root {
|
||||
WindowHost::of(&ctx).act(ViewportId::ROOT, WindowAction::Focus);
|
||||
}
|
||||
self.draw_entry(ui, self.windows.root.get());
|
||||
let root = self.windows.root;
|
||||
// The root window gaining OS focus makes its entry the active one, as a child's `focus_gained` does.
|
||||
let root_focused = WindowHost::of(&ctx).facts(ViewportId::ROOT).is_some_and(|facts| facts.focused);
|
||||
if root_focused && !std::mem::replace(&mut self.windows.root_focused, root_focused) {
|
||||
self.windows.list.focus(root);
|
||||
// A windowless root has no window: its entry is a document window like the others. With a
|
||||
// visible root (X11) the root window draws the root entry itself.
|
||||
let windowless = windowless_root(&ctx);
|
||||
if !windowless {
|
||||
let raise_root = self.windows.list.get_mut(root).is_some_and(|w| std::mem::take(&mut w.raise));
|
||||
if raise_root {
|
||||
WindowHost::of(&ctx).act(ViewportId::ROOT, WindowAction::Focus);
|
||||
}
|
||||
self.draw_entry(ui, root.get());
|
||||
// The root window gaining OS focus makes its entry the active one, as a child's `focus_gained` does.
|
||||
let root_focused = WindowHost::of(&ctx).facts(ViewportId::ROOT).is_some_and(|facts| facts.focused);
|
||||
if root_focused && !std::mem::replace(&mut self.windows.root_focused, root_focused) {
|
||||
self.windows.list.focus(root);
|
||||
}
|
||||
self.windows.root_focused = root_focused;
|
||||
}
|
||||
self.windows.root_focused = root_focused;
|
||||
let menu = self.window_menu();
|
||||
let step = StyleCx::with_root(&ctx, |cx| cx.tokens.size.window.cascade);
|
||||
let ids: Vec<WindowId> = self.windows.list.ids().filter(|&id| id != root).collect();
|
||||
let ids: Vec<WindowId> = self.windows.list.ids().filter(|&id| windowless || id != root).collect();
|
||||
let mut closes = Vec::new();
|
||||
let mut failed = Vec::new();
|
||||
for id in ids {
|
||||
let Some(w) = self.windows.list.get_mut(id) else { continue };
|
||||
let (raise, place) = (std::mem::take(&mut w.raise), std::mem::take(&mut w.place));
|
||||
@@ -560,17 +598,36 @@ impl WordApp {
|
||||
if raise {
|
||||
window = window.raise();
|
||||
}
|
||||
let main = windowless && id == root;
|
||||
if main {
|
||||
// Every frame, so the place is saved as the user moves or sizes the window.
|
||||
window = window.remember(SaveKey::new("wordcraft.main_window"));
|
||||
}
|
||||
if place && let Some(rect) = self.cascade_from(ui, id, step) {
|
||||
window = window.first_placed(rect);
|
||||
} else if main && !std::mem::replace(&mut self.windows.root_placed, true) {
|
||||
// The first window takes the place the root window had: the saved one, else the default size.
|
||||
let default = egui::Rect::from_min_size(egui::pos2(80.0, 60.0), egui::vec2(1440.0, 920.0));
|
||||
window = window.first_placed(default);
|
||||
}
|
||||
let out = window.show(ui, |ui, cx| self.draw_window(ui, cx, id)).output;
|
||||
let mut drawn = false;
|
||||
let out = window
|
||||
.show(ui, |ui, cx| {
|
||||
drawn = true;
|
||||
self.draw_window(ui, cx, id)
|
||||
})
|
||||
.output;
|
||||
if out.focus_gained {
|
||||
self.windows.list.focus(id);
|
||||
}
|
||||
if out.close_requested.is_some() {
|
||||
closes.push(id);
|
||||
// Asked to close without ever drawing: the window could not be opened.
|
||||
if drawn { closes.push(id) } else { failed.push(id) }
|
||||
}
|
||||
}
|
||||
for id in failed {
|
||||
self.window_failed_to_open(id);
|
||||
}
|
||||
self.window_events(&closes);
|
||||
self.after_windows();
|
||||
}
|
||||
@@ -623,13 +680,42 @@ impl WordApp {
|
||||
/// host asks about ([`WordApp::close_requested`]).
|
||||
fn window_events(&mut self, closes: &[WindowId]) {
|
||||
for &id in closes {
|
||||
if self.quit_requested || self.windows.list.len() <= 1 || !self.windows.list.contains(id) {
|
||||
if self.quit_requested || !self.windows.list.contains(id) {
|
||||
continue;
|
||||
}
|
||||
self.close_window(id.get());
|
||||
if self.windows.list.len() > 1 {
|
||||
self.close_window(id.get());
|
||||
} else if self.ctx.as_ref().is_some_and(windowless_root) {
|
||||
// The only window has no root to take its close: it asks as a quit does, which
|
||||
// ends the app once every document is answered for.
|
||||
if self.raise_closing().is_none()
|
||||
&& self.close_requested()
|
||||
&& let Some(ctx) = &self.ctx
|
||||
{
|
||||
WindowHost::of(ctx).act(ViewportId::ROOT, WindowAction::Close);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Window `id` was asked to close before it drew: the OS refused it (no window or surface). Its
|
||||
/// entry goes without a Save prompt and the person is told; the document stays open. With no
|
||||
/// other window the app has nothing to show and ends.
|
||||
fn window_failed_to_open(&mut self, id: WindowId) {
|
||||
let Some(doc) = self.windows.list.get(id).map(|w| w.doc) else { return };
|
||||
let name = self.session.documents().into_iter().find(|d| d.id == doc).map(|d| d.title).unwrap_or_default();
|
||||
log::error!("window for document {doc} could not be opened");
|
||||
if self.windows.list.len() <= 1 {
|
||||
// lean: no window to tell the person in; the log has it. Quit rather than run with nothing.
|
||||
self.quit_requested = true;
|
||||
return;
|
||||
}
|
||||
self.windows.failed_open.push(doc);
|
||||
self.windows.list.close(id);
|
||||
self.settle_windows();
|
||||
self.status(crate::i18n::fmt(tl!("A window for “{name}” could not be opened, so that document has no window."), &[("name", &name)]));
|
||||
}
|
||||
|
||||
/// The close button of window `key` (not the last one): File › Close in that window, which
|
||||
/// asks about unsaved changes first.
|
||||
pub(crate) fn close_window(&mut self, key: u64) {
|
||||
|
||||
@@ -32,6 +32,19 @@ impl Rig {
|
||||
Rig { kit: Kit::new(), focused: None, closing: Vec::new(), commands: Vec::new(), drawn: Vec::new(), builders: Vec::new() }
|
||||
}
|
||||
|
||||
fn with_clipboard() -> Rig {
|
||||
let spec = craft::ui::InstallSpec::new(craft::host::target::ShellInfo::default(), Arc::new(craft::ui::testing::windows::FakeSystem::new()))
|
||||
.clipboard(craft::platform::clipboard::Clipboard::new(craft::platform::clipboard::MemoryClipboard::default()));
|
||||
Rig { kit: Kit::with(spec), focused: None, closing: Vec::new(), commands: Vec::new(), drawn: Vec::new(), builders: Vec::new() }
|
||||
}
|
||||
|
||||
/// A rig whose root is a windowless logical root: every document window is a child.
|
||||
fn windowless() -> Rig {
|
||||
let spec = craft::ui::InstallSpec::new(craft::host::target::ShellInfo::default(), Arc::new(craft::ui::testing::windows::FakeSystem::new()))
|
||||
.windowless_root();
|
||||
Rig { kit: Kit::with(spec), focused: None, closing: Vec::new(), commands: Vec::new(), drawn: Vec::new(), builders: Vec::new() }
|
||||
}
|
||||
|
||||
fn ctx(&self) -> egui::Context {
|
||||
self.kit.ctx.clone()
|
||||
}
|
||||
@@ -48,6 +61,11 @@ impl Rig {
|
||||
|
||||
/// One frame of every window.
|
||||
fn frame(&mut self, a: &mut WordApp) {
|
||||
self.frame_events(a, Vec::new(), Vec::new());
|
||||
}
|
||||
|
||||
/// One frame of every window with explicit root and child input events.
|
||||
fn frame_events(&mut self, a: &mut WordApp, root: Vec<egui::Event>, child: Vec<egui::Event>) {
|
||||
self.kit.root_info(self.info(false));
|
||||
self.kit.child_info(self.info(true));
|
||||
if let Some(focused) = self.focused {
|
||||
@@ -58,7 +76,7 @@ impl Rig {
|
||||
}
|
||||
// PLAN: assumed `embed::before_input(ctx, |out| app.frame_input(out))` (sh.A2) from app-hub.
|
||||
craft::ui::shell::embed::before_input(&self.kit.ctx, |out| a.frame_input(out));
|
||||
let out = self.kit.frame(Vec::new(), Vec::new(), |ui| {
|
||||
let out = self.kit.frame(root, child, |ui| {
|
||||
a.logic(ui.ctx());
|
||||
// The root window's close request goes through the app's close decision, as the host's frame runs it.
|
||||
craft::ui::shell::embed::logic(ui.ctx(), || a.close_decision());
|
||||
@@ -339,7 +357,7 @@ fn parked_prompt_answer(answer: craft::quit::CloseAnswer, name: &str, saved_text
|
||||
rig.frame(&mut a);
|
||||
assert!(a.enter_window(first), "the recorded prompt owner remains open");
|
||||
let id = a.closing.as_ref().unwrap().prompt.unwrap();
|
||||
a.dialog_host.get_mut_by_id::<craft::ui::dialog::UnsavedChangesDialog>(id).unwrap().set_answer(answer);
|
||||
a.dialog_host.get_mut_by_id::<craft::ui::dialog::HostedUnsavedChangesDialog>(id).unwrap().set_answer(answer);
|
||||
assert!(a.dialog_host.confirm_by_id(&rig.ctx(), id));
|
||||
a.show_window(second);
|
||||
rig.frames(&mut a, 3);
|
||||
@@ -1054,3 +1072,204 @@ fn root_viewport_receives_promoted_windows_title_after_root_closes() {
|
||||
let idle_titles = rig.commands.iter().filter(|(v, c)| *v == ViewportId::ROOT && matches!(c, ViewportCommand::Title(_))).count();
|
||||
assert_eq!(idle_titles, 0, "idle frame after promotion sends no duplicate title");
|
||||
}
|
||||
|
||||
/// Mod+Shift+V with nothing copied pastes the clipboard as text in desktop windows other than
|
||||
/// the first, even when quickly tapped so modifiers release before `run_fired`.
|
||||
#[test]
|
||||
fn mod_shift_v_with_nothing_copied_pastes_text_in_second_window() {
|
||||
use craft::ui::runtime::commands::{ClipItem, ClipboardHandle};
|
||||
|
||||
let mut rig = Rig::with_clipboard();
|
||||
let mut a = app("First");
|
||||
rig.frames(&mut a, 2);
|
||||
|
||||
a.run("file.new", json!({})).unwrap();
|
||||
rig.frames(&mut a, 2);
|
||||
let child = a.active_viewport();
|
||||
assert_ne!(child, ViewportId::ROOT);
|
||||
rig.focus(child);
|
||||
rig.frames(&mut a, 2);
|
||||
assert_eq!(text(&a), "");
|
||||
|
||||
let _ = ClipboardHandle::of(&rig.ctx()).offer(&[ClipItem::Text("pasted".into())]).expect("clipboard takes offer");
|
||||
let chord = if cfg!(target_os = "macos") {
|
||||
egui::Modifiers { mac_cmd: true, command: true, shift: true, ..Default::default() }
|
||||
} else {
|
||||
egui::Modifiers { ctrl: true, command: true, shift: true, ..Default::default() }
|
||||
};
|
||||
let press_and_release = vec![
|
||||
egui::Event::ModifiersChanged(chord),
|
||||
egui::Event::Key { key: egui::Key::V, physical_key: Some(egui::Key::V), pressed: true, repeat: false, modifiers: chord },
|
||||
egui::Event::Key { key: egui::Key::V, physical_key: Some(egui::Key::V), pressed: false, repeat: false, modifiers: egui::Modifiers::NONE },
|
||||
egui::Event::ModifiersChanged(egui::Modifiers::NONE),
|
||||
];
|
||||
rig.frame_events(&mut a, Vec::new(), press_and_release);
|
||||
rig.frame(&mut a);
|
||||
assert_eq!(text(&a), "pasted", "Mod+Shift+V with nothing copied pastes text in the second OS window");
|
||||
}
|
||||
|
||||
/// A control-channel request, answered as the channel answers it.
|
||||
fn ctl(a: &mut WordApp, rig: &Rig, method: &str, params: serde_json::Value) -> serde_json::Value {
|
||||
let (req, _) = ControlRequest::new(method, params);
|
||||
match crate::control::handle(a, &rig.ctx(), &req) {
|
||||
Reply::Done(v) => v,
|
||||
_ => json!({"ok": false, "error": "not a reply"}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Spec rule 8: `file.close` on unsaved work needs `save` (write, then close) or `force`; a
|
||||
/// document with no file can't be saved without asking, so `save` refuses it.
|
||||
#[test]
|
||||
fn file_close_over_control_needs_save_or_force_and_save_writes_first() {
|
||||
let path = docx_on_disk("close-save", "First");
|
||||
let mut rig = Rig::new();
|
||||
let mut a = app("First");
|
||||
a.run("file.save", json!({"path": path.to_string_lossy()})).unwrap();
|
||||
a.run("file.autosave", json!({"value": false})).unwrap();
|
||||
a.run("text.insert", json!({"text": " edited"})).unwrap();
|
||||
let first = a.session.document_id();
|
||||
a.run("file.new", json!({})).unwrap();
|
||||
a.run("text.insert", json!({"text": "Draft"})).unwrap();
|
||||
let draft = a.session.document_id();
|
||||
rig.frames(&mut a, 2);
|
||||
a.show_window(a.windows.of_doc(first).unwrap());
|
||||
let r = ctl(&mut a, &rig, "engine.execute", json!({"command": "file.close"}));
|
||||
assert_eq!(r["ok"], false);
|
||||
assert!(r["error"].as_str().unwrap().contains("pass save or force"), "{r}");
|
||||
assert!(a.session.is_open(first) && a.closing.is_none(), "refused: nothing closes and nothing asks");
|
||||
let r = ctl(&mut a, &rig, "engine.execute", json!({"command": "file.close", "params": {"save": true}}));
|
||||
assert_eq!(r["ok"], true, "{r}");
|
||||
assert!(!a.session.is_open(first) && a.closing.is_none());
|
||||
let mut saved = Session::new(wordcraft_doc::Document::new());
|
||||
saved.run("file.open", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
assert_eq!(saved.doc.plain_text(StoryRef::Body).trim(), "First edited");
|
||||
std::fs::remove_dir_all(path.parent().unwrap()).ok();
|
||||
|
||||
let r = ctl(&mut a, &rig, "engine.execute", json!({"command": "file.close", "params": {"save": true}}));
|
||||
assert_eq!(r["ok"], false, "a never-saved document has nowhere to save: {r}");
|
||||
assert!(a.session.is_open(draft) && a.closing.is_none());
|
||||
let r = ctl(&mut a, &rig, "engine.execute", json!({"command": "file.close", "params": {"force": true}}));
|
||||
assert_eq!(r["ok"], true, "{r}");
|
||||
assert!(!a.session.is_open(draft));
|
||||
}
|
||||
|
||||
/// Spec rule 8: `ui.closeWindow` closes the active window, or the one `window` names.
|
||||
#[test]
|
||||
fn ui_closewindow_closes_the_active_window_or_the_one_named() {
|
||||
let mut rig = Rig::new();
|
||||
let mut a = app("One");
|
||||
rig.frames(&mut a, 2);
|
||||
a.run("file.new", json!({})).unwrap();
|
||||
rig.frames(&mut a, 2);
|
||||
let middle = a.windows.shown();
|
||||
let middle_vp = a.active_viewport();
|
||||
a.run("file.new", json!({})).unwrap();
|
||||
rig.frames(&mut a, 2);
|
||||
let active_vp = a.active_viewport();
|
||||
assert_ne!(middle_vp, active_vp);
|
||||
let r = ctl(&mut a, &rig, "ui.closeWindow", json!({"window": middle}));
|
||||
assert_eq!(r["ok"], true, "{r}");
|
||||
rig.frame(&mut a);
|
||||
assert!(rig.sent(middle_vp, &ViewportCommand::Close) && !rig.sent(active_vp, &ViewportCommand::Close), "only the named window");
|
||||
ctl(&mut a, &rig, "ui.closeWindow", json!({}));
|
||||
rig.frame(&mut a);
|
||||
assert!(rig.sent(active_vp, &ViewportCommand::Close), "no `window`: the active one");
|
||||
assert_eq!(ctl(&mut a, &rig, "ui.closeWindow", json!({"window": 9999}))["ok"], false);
|
||||
}
|
||||
|
||||
/// Spec rule 3: clicking another window while the Save prompt is up brings the prompt back
|
||||
/// (existing focus handling already does; this pins it).
|
||||
#[test]
|
||||
fn clicking_another_window_while_a_prompt_is_up_raises_the_prompt() {
|
||||
let mut rig = Rig::new();
|
||||
let mut a = app("First");
|
||||
rig.frames(&mut a, 2);
|
||||
let first = a.windows.shown();
|
||||
a.run("file.new", json!({})).unwrap();
|
||||
a.run("text.insert", json!({"text": "Second"})).unwrap();
|
||||
rig.frames(&mut a, 2);
|
||||
let child = a.active_viewport();
|
||||
a.close_window(first);
|
||||
rig.frame(&mut a);
|
||||
let owner = a.closing.as_ref().unwrap().window;
|
||||
assert_eq!(owner, first);
|
||||
rig.focus(child);
|
||||
let mut raised = false;
|
||||
for _ in 0..3 {
|
||||
rig.frame(&mut a);
|
||||
raised |= rig.sent(ViewportId::ROOT, &ViewportCommand::Focus);
|
||||
}
|
||||
assert!(raised, "the prompt's window comes to the front");
|
||||
assert_eq!(a.closing.as_ref().map(|c| c.window), Some(first), "still the one prompt, still its window's");
|
||||
}
|
||||
|
||||
/// Spec rule 6: Quit asks about each unsaved document in turn; Cancel on the second stops the
|
||||
/// quit and leaves the remaining windows as they were. A following quit then asks again.
|
||||
#[test]
|
||||
fn quit_with_three_modified_documents_asks_three_times_and_cancel_keeps_two() {
|
||||
let mut rig = Rig::new();
|
||||
let mut a = app("One");
|
||||
rig.frames(&mut a, 2);
|
||||
for t in ["Two", "Three"] {
|
||||
a.run("file.new", json!({})).unwrap();
|
||||
a.run("text.insert", json!({"text": t})).unwrap();
|
||||
rig.frames(&mut a, 2);
|
||||
}
|
||||
assert_eq!(a.window_count(), 3);
|
||||
assert!(!a.quit());
|
||||
assert_eq!(prompt(&a).as_deref(), Some("saveChanges"));
|
||||
a.run("ui.saveChanges", json!({"answer": "dontSave"})).unwrap();
|
||||
assert_eq!(prompt(&a).as_deref(), Some("saveChanges"), "the second asks");
|
||||
a.run("ui.saveChanges", json!({"answer": "cancel"})).unwrap();
|
||||
assert!(!a.quit_requested && a.closing.is_none());
|
||||
rig.frames(&mut a, 2);
|
||||
assert_eq!((a.window_count(), a.session.documents().len()), (2, 2), "Cancel keeps the two that are left");
|
||||
assert!(!a.quit(), "the next quit asks again");
|
||||
a.run("ui.saveChanges", json!({"answer": "dontSave"})).unwrap();
|
||||
a.run("ui.saveChanges", json!({"answer": "dontSave"})).unwrap();
|
||||
assert!(a.quit_requested);
|
||||
}
|
||||
|
||||
/// Spec rule 1 with the windowless root: the first window is a child like the rest, nothing draws in the root, and
|
||||
/// closing the first of two windows closes that window's document and leaves the other as it was.
|
||||
#[test]
|
||||
fn windowless_root_draws_every_document_in_a_child_and_closes_exactly_the_requested_one() {
|
||||
let mut rig = Rig::windowless();
|
||||
let mut a = app("First");
|
||||
let first_doc = a.session.document_id();
|
||||
rig.frames(&mut a, 2);
|
||||
a.run("file.new", json!({})).unwrap();
|
||||
a.run("text.insert", json!({"text": "Second"})).unwrap();
|
||||
let second_doc = a.session.document_id();
|
||||
rig.frames(&mut a, 3);
|
||||
let viewports = a.windows.viewports(&rig.ctx());
|
||||
assert_eq!(viewports.len(), 2);
|
||||
assert!(!viewports.contains(&ViewportId::ROOT), "the root is no document window");
|
||||
assert_ne!(a.active_viewport(), ViewportId::ROOT);
|
||||
let first_vp = viewports[0];
|
||||
rig.close(first_vp);
|
||||
rig.frames(&mut a, 2);
|
||||
assert_eq!(a.closing.as_ref().unwrap().guard.current(), Some(&first_doc), "the window closed is the one asked about");
|
||||
a.run("ui.saveChanges", json!({"answer": "dontSave"})).unwrap();
|
||||
rig.frames(&mut a, 2);
|
||||
assert!(!a.session.is_open(first_doc) && a.session.is_open(second_doc));
|
||||
assert_eq!(text(&a), "Second");
|
||||
assert_eq!(a.window_count(), 1);
|
||||
}
|
||||
|
||||
/// `ui.closeWindow` says so when nothing was asked: a Save prompt is already up (spec rule 4).
|
||||
#[test]
|
||||
fn ui_closewindow_reports_not_requested_while_a_prompt_is_up() {
|
||||
let mut rig = Rig::new();
|
||||
let mut a = app("One");
|
||||
rig.frames(&mut a, 2);
|
||||
a.run("file.new", json!({})).unwrap();
|
||||
a.run("text.insert", json!({"text": "Two"})).unwrap();
|
||||
rig.frames(&mut a, 2);
|
||||
let first = a.windows.root_key();
|
||||
a.close_window(first);
|
||||
rig.frame(&mut a);
|
||||
assert!(a.closing.is_some());
|
||||
let r = ctl(&mut a, &rig, "ui.closeWindow", json!({}));
|
||||
assert_eq!(r["result"]["requested"], false, "{r}");
|
||||
}
|
||||
|
||||
@@ -500,3 +500,92 @@ checker verifies the pairing (CT-MISMATCH, Error, observed — this row).
|
||||
The corpus was regenerated; MANIFEST.md carries the fixed hashes.
|
||||
|
||||
The remaining nine stress files have not yet been shown to this consumer.
|
||||
|
||||
## Corpus probes — DrawingML geometry coordinate typing (#8231)
|
||||
|
||||
A real-world corpus document (`d60c276dc845`) containing a `wps` custom-geometry
|
||||
shape (`a:custGeom`) inside `mc:AlternateContent` whose four `a:arcTo` elements
|
||||
carried decimal `wR`/`hR` values was refused by Word for Windows (census) and
|
||||
fell into the open-failure class on Word for Mac. Rounding only those eight
|
||||
values to integers caused the full original document to open cleanly.
|
||||
|
||||
Follow-up probes derived from `d60c276dc845` (whose only decimals are the eight
|
||||
`a:arcTo` radii) were measured in fresh instances of **Word for Mac 16.114.4
|
||||
(2026-12-02)** (modal open-error alert / 0 documents opened on refusal):
|
||||
|
||||
| Form | Example | Word for Mac 16.114.4 |
|
||||
|---|---|---|
|
||||
| Plain decimal fraction | `407.666666666667` | REFUSES (original finding) |
|
||||
| Integer | `407` | OPENS |
|
||||
| Sign-prefixed fraction | `-407.666666666667` | REFUSES |
|
||||
| Space-padded fraction | `" 407.666666666667 "` | REFUSES |
|
||||
| Zero fraction | `407.0` | REFUSES |
|
||||
| Strict-namespace `arcTo` (`http://purl.oclc.org/ooxml/drawingml/main`) in a Transitional package | — | REFUSES |
|
||||
|
||||
Context probes derived from `d60c276dc845` (one variable per probe; controls: original refuses, integer opens) were measured in **Word for Mac 16.114.4**:
|
||||
|
||||
| Context | Fractional radii in `custGeom` |
|
||||
|---|---|
|
||||
| Selected `mc:Choice` (first Supported, `Requires="wps"`; corpus document context) | REFUSES |
|
||||
| Selected `mc:Choice` with no `Requires` attribute (`r1`) | REFUSES |
|
||||
| Second, unselected `mc:Choice` (after Supported `mc:Choice`) | OPENS |
|
||||
| `mc:Fallback` while a Supported `mc:Choice` precedes it | OPENS |
|
||||
| `mc:Fallback` behind a foreign-namespace `mc:Choice` (`q1b`) | CONFOUNDED (Word refuses the MCE construction; geometry attribution unmeasurable) |
|
||||
| Strict package (`http://purl.oclc.org/ooxml/...` namespaces, `conformance="strict"`) | OPENS |
|
||||
| Outside any `mc:AlternateContent` (bare `w:drawing`, Transitional; `r2`) | REFUSES |
|
||||
|
||||
`DML-COORDINATE` is graded `Error` with `Observed` evidence only when ALL three
|
||||
conditions hold:
|
||||
|
||||
1. **Transitional part profile**: the part's root element namespace resolves to
|
||||
a non-Strict URI (not under `http://purl.oclc.org/ooxml/`). Strict parts and
|
||||
parts whose root namespace cannot be resolved by the scanner (for example,
|
||||
entity-obscured `xmlns`, undeclared prefix, or no namespace binding) never
|
||||
emit `Error`.
|
||||
2. **Supported-selected branch**: outside every `mc:AlternateContent`, or inside
|
||||
the Supported-selected branch of every enclosing `mc:AlternateContent`. Each
|
||||
`mc:Choice` evaluates to one of three states:
|
||||
- **Supported**: `Requires` is absent (measured `r1`), or every
|
||||
whitespace-delimited prefix resolves by exact URI equality to the closed
|
||||
allowlist of Word MCE capability URIs (`w`, anchored on `wps`, plus Word's
|
||||
shipped 2010/2012 WordprocessingML and DrawingML capability URIs).
|
||||
- **Unresolved**: any `Requires` prefix resolves to an unlisted URI, fails to
|
||||
resolve (undeclared, malformed, or entity-obscured), or `Requires` is empty
|
||||
or entity-obscured. An Unresolved `Choice` makes the whole enclosing
|
||||
`mc:AlternateContent`'s selection uncertain; no branch in it (that Choice,
|
||||
later Choices, or `mc:Fallback`) may be treated as selected.
|
||||
- **Unsupported**: reserved for capabilities a Word measurement proves Word
|
||||
rejects without confounding MCE rejection; currently unpopulated (no
|
||||
capability is populated by inference).
|
||||
`mc:Fallback` is treated as selected only when `mc:AlternateContent` contains
|
||||
no `Choice` at all; a `mc:Fallback` behind any `Choice` (`Supported`,
|
||||
`Unresolved`, or `Unsupported`) is never treated as selected.
|
||||
3. **Measured fractional geometry**: raw (undecoded, unnormalized) XML attribute
|
||||
values matching `[ ]*-?[0-9]+\.[0-9]+[ ]*` with an `i64`-representable signed
|
||||
whole part in `wR`/`hR` on `a:arcTo` in either the Transitional
|
||||
(`http://schemas.openxmlformats.org/drawingml/2006/main`) or Strict
|
||||
(`http://purl.oclc.org/ooxml/drawingml/main`) DrawingML namespace.
|
||||
|
||||
Every other invalid geometry finding is graded `Warning` and does not fail a
|
||||
package. **Warning grade precedence** for measured fractional radii:
|
||||
|
||||
1. **Strict parts and definitively unselected enclosing `mc:AlternateContent`
|
||||
branches** (for example, a second `mc:Choice` or `mc:Fallback` after a
|
||||
Supported `mc:Choice`) report `Warning` with `Observed` evidence (Word
|
||||
toleration is measured).
|
||||
2. **Unresolved part profiles and unresolved `AlternateContent` selections**
|
||||
report `Warning` with `MsDocumented` evidence only in a non-Strict part with
|
||||
no definitively unselected enclosing branch.
|
||||
|
||||
Unmeasured schema-typed sibling attributes
|
||||
(`ST_AdjCoordinate`, `ST_AdjAngle`, `ST_PositiveCoordinate`) and all unmeasured
|
||||
invalid numeric lexical classes (`+`-prefixed fractions, non-space whitespace
|
||||
padding such as `\t`/`\r`/`\n`, character-reference or entity-encoded
|
||||
spellings, empty or whitespace-only values, lone signs, lone dots,
|
||||
leading/trailing dots, scientific/exponent notation, integers outside their
|
||||
schema type's bounds (`ST_PositiveCoordinate`: `0..=27273042316900`,
|
||||
`ST_CoordinateUnqualified`: `-27273042329600..=27273042316900`, `ST_Angle`:
|
||||
`-2147483648..=2147483647`), out-of-`i64`-range whole parts, and non-integer
|
||||
path dimensions) are graded `Warning`
|
||||
with `MsDocumented` evidence and do not fail a package. In-range integers, guide names,
|
||||
and unit-qualified coordinate measures are preserved.
|
||||
|
||||
@@ -48,6 +48,8 @@ Recorded reader pairs (exact shapes in the policy):
|
||||
| Helper | Rules/conclusion | Collections/accessors | Intentional scope | Incompleteness causes | Fallback | Unknown package identity |
|
||||
|---|---|---|---|---|---|---|
|
||||
| lib.rs::ran | - | field.checks*1 | report accumulator and emission budgets; no input definition collection | per-rule findings, total findings, or coverage-note budget | preserve emitted evidence and record truncation/Incomplete; never supplies definition absence | independent |
|
||||
| lib.rs::ran_dml_coordinate | DML-COORDINATE | - | report applicability for custom geometry | custom geometry may be absent from the scanned XML prefix | record the rule once when the scanner reaches custom geometry | independent |
|
||||
| lib.rs::add_dml_coordinate_error | DML-COORDINATE | - | document-wide measured DML-COORDINATE error count and capped emission | per-rule finding cap | count every measured error across all XML parts and emit at most cap + 1 times so truncation is noted once | independent |
|
||||
| lib.rs::allow | - | field.coverage*2,field.incomplete*1,field.rule_counts*1 | report accumulator and emission budgets; no input definition collection | per-rule findings, total findings, or coverage-note budget | preserve emitted evidence and record truncation/Incomplete; never supplies definition absence | independent |
|
||||
| lib.rs::add | - | field.findings*1 | report accumulator and emission budgets; no input definition collection | per-rule findings, total findings, or coverage-note budget | preserve emitted evidence and record truncation/Incomplete; never supplies definition absence | independent |
|
||||
| lib.rs::add_graded | - | field.findings*1 | report accumulator and emission budgets; no input definition collection | per-rule findings, total findings, or coverage-note budget | preserve emitted evidence and record truncation/Incomplete; never supplies definition absence | independent |
|
||||
@@ -74,7 +76,9 @@ Recorded reader pairs (exact shapes in the policy):
|
||||
| lib.rs::listing_complete | - | access.is_complete*2,field.listings*2,field.parts*1,field.special_notes*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
|
||||
| lib.rs::category_complete | - | access.is_complete*1,field.parts*1,type.Observed*1,type.Vec*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
|
||||
| lib.rs::xml_source_complete | - | field.parts*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
|
||||
| lib.rs::check_xml | HEADERSOURCE-PRESENT,MATH-PLACEMENT,PROTECTION-PASSWORD,STRUCT-END-P,XML-INVALID-CHAR,XML-MALFORMED,XML-UNDECLARED-PREFIX | access.prefix*1,access.retain_budget*1,field.comment_para_ids*1,field.content_part_exemptions*2,field.content_parts*2,field.entries*1,field.ink_content_parts*2,field.note_listings*1,field.refs*5,field.special_notes*1,field.unknown_prefixes*1,type.BTreeMap*1,type.HashMap*2,type.HashSet*2,type.Vec*13 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
|
||||
| lib.rs::check_xml | DML-COORDINATE,HEADERSOURCE-PRESENT,MATH-PLACEMENT,PROTECTION-PASSWORD,STRUCT-END-P,XML-INVALID-CHAR,XML-MALFORMED,XML-UNDECLARED-PREFIX | access.prefix*1,access.retain_budget*1,field.comment_para_ids*1,field.content_part_exemptions*2,field.content_parts*2,field.dml_coordinate_warnings*1,field.entries*1,field.ink_content_parts*2,field.note_listings*1,field.refs*5,field.special_notes*1,field.unknown_prefixes*1,type.BTreeMap*1,type.HashMap*2,type.HashSet*2,type.Vec*15 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
|
||||
| lib.rs::append_dml_coordinate_warnings | - | type.Vec*2 | bounded deferred DML-COORDINATE warnings across XML parts | per-rule finding cap | retain up to one warning past the cap to exercise truncation after measured errors | independent |
|
||||
| lib.rs::flush_dml_coordinate_warnings | DML-COORDINATE | type.Observed*1,type.Vec*1 | deferred DML-COORDINATE warnings emitted after all XML parts | per-rule finding cap | emit measured errors ahead of warnings and trigger truncation at most once | independent |
|
||||
| lib.rs::store_relationship_observations | - | access.invalidate*2,access.project*3,field.content*3,field.exemptions*3,field.references*2,type.BTreeMap*1,type.HashSet*1,type.Vec*6 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
|
||||
| lib.rs::store_note_observations | - | access.invalidate*3,access.push_bounded*3,field.listings*4,field.special_notes*2,type.BTreeMap*1,type.HashMap*1,type.Vec*3 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
|
||||
| lib.rs::append_note_items | - | type.Vec*6 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
|
||||
@@ -193,7 +197,7 @@ Recorded reader pairs (exact shapes in the policy):
|
||||
| scan.rs::close | - | field.frames*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
|
||||
| scan.rs::declared_encoding | - | field.bytes*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
|
||||
| scan.rs::decode_utf16_strict | - | type.Vec*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
|
||||
| scan.rs::scan_part | STRUCT-TC-NO-P | access.into_complete_set*2,access.invalidate*2,field.alt_stack*2,field.content_part_exemptions*2,field.content_parts*2,field.declared*8,field.frames*10,field.note_listings*1,field.note_listings_e*1,field.note_listings_f*1,field.para_ids*1,field.special_notes*2,field.unknown_prefixes*2,parser.parse_doctype_entities*1,type.BTreeMap*1,type.HashMap*1,type.HashSet*1,type.Observed*1,type.Vec*9 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
|
||||
| scan.rs::scan_part | STRUCT-TC-NO-P | access.into_complete_set*2,access.invalidate*2,field.alt_stack*2,field.content_part_exemptions*2,field.content_parts*2,field.declared*8,field.frames*10,field.note_listings*1,field.note_listings_e*1,field.note_listings_f*1,field.para_ids*1,field.special_notes*2,field.unknown_prefixes*2,parser.parse_doctype_entities*1,type.BTreeMap*1,type.HashMap*1,type.HashSet*1,type.Observed*1,type.Vec*10 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
|
||||
| scan.rs::own_declarations | - | type.Vec*2 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
|
||||
| scan.rs::open_attributes | - | type.Vec*2 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
|
||||
| scan.rs::enter_alt | - | field.alt_stack*1,field.frames*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
|
||||
@@ -206,9 +210,14 @@ Recorded reader pairs (exact shapes in the policy):
|
||||
| scan.rs::check_protection | PROTECTION-PASSWORD | type.Vec*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
|
||||
| scan.rs::record_note_pr | - | field.frames*2,field.note_listings_e*1,field.note_listings_f*1,field.special_notes*2 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
|
||||
| scan.rs::check_header_source | HEADERSOURCE-PRESENT | field.frames*2,field.withheld*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
|
||||
| scan.rs::in_custom_geometry | - | field.frames*1 | custom geometry ancestry of the current XML event | XML event/depth budget | use ancestry of events already scanned | independent |
|
||||
| scan.rs::prefix_requires_state | - | type.Vec*1 | namespace scope for one mc:Choice Requires prefix | XML event/depth budget; entity-obscured xmlns declaration | treat unlisted, undeclared, malformed, or entity-obscured prefix bindings as unresolved rather than supported or unsupported | independent |
|
||||
| scan.rs::choice_requires_state | - | type.Vec*1 | mc:Choice Requires attribute evaluation in current namespace scope | XML event/depth budget; entity-obscured Requires or xmlns declaration | withhold Error by returning Unresolved when Requires or any prefix binding is unlisted, empty, undeclared, or unreadable | independent |
|
||||
| scan.rs::dml_branch_selection | - | field.alt_stack*1 | enclosing mc:AlternateContent branch selection for the current XML event | XML event/depth budget | evaluate enclosing AlternateContent frames already scanned | independent |
|
||||
| scan.rs::check_dml_coordinates | DML-COORDINATE | field.dml_coordinate_warnings*2,field.frames*1 | source-local custom geometry attribute values | source unavailable or malformed; XML event/depth budget | measured decimal-fraction spellings ([ ]*-?[0-9]+\\.[0-9]+[ ]* raw XML source) in a:arcTo wR/hR (Transitional or Strict DrawingML namespace) receive Error with Observed evidence only when the part profile is Transitional and every enclosing AlternateContent is Supported-selected (bare drawing, Supported Choice, or choice-less Fallback); Warning grade precedence: Strict parts and definitively unselected enclosing AlternateContent branches report Warning with Observed evidence, while unresolved part profiles and unresolved AlternateContent selections report Warning with MsDocumented evidence only in a non-Strict part with no definitively unselected enclosing branch; other invalid schema-typed custom geometry attributes and unmeasured or unresolvable lexical classes receive Warning with MsDocumented evidence; measured Errors are emitted ahead of Warnings; report invalid values in the scanned prefix | independent |
|
||||
| scan.rs::record | - | field.reps*3 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
|
||||
| scan.rs::check_para_ids | PARAID-VALUE | field.alt_stack*1,field.para_ids*3 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
|
||||
| scan.rs::assign_alt_branch | - | field.alt_stack*1,field.frames*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
|
||||
| scan.rs::assign_alt_branch | - | field.alt_stack*1,field.declared*1,field.frames*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
|
||||
| scan.rs::restore_branch | - | field.alt_stack*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
|
||||
| scan.rs::on_empty | STRUCT-TC-NO-P | - | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
|
||||
| scan.rs::record_ids | - | field.docpr*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
|
||||
|
||||
+340
-2
@@ -434,6 +434,48 @@ pub(crate) const PROTECTION_PASSWORD: RuleSpec =
|
||||
/// Batch b6 (Word for the web, 2026-11-07): corruption banner, view-only
|
||||
/// — observed.
|
||||
pub(crate) const HEADERSOURCE_PRESENT: RuleSpec = RuleSpec { id: "HEADERSOURCE-PRESENT", severity: Severity::Error, evidence: Evidence::Observed };
|
||||
/// `DML-COORDINATE`: an invalid numeric literal in an integer-typed DrawingML
|
||||
/// custom geometry coordinate or angle attribute (`ST_PositiveCoordinate`,
|
||||
/// `ST_AdjCoordinate`, `ST_AdjAngle`).
|
||||
/// Observed (#8231): Word for Windows (census) and Word for Mac 16.114.4
|
||||
/// (2026-12-02, fresh instances) on probes derived from `d60c276dc845`
|
||||
/// refused decimal-fraction `wR`/`hR` values on `a:arcTo` across all five
|
||||
/// refusal forms — plain (`407.666666666667`), minus-sign-prefixed
|
||||
/// (`-407.666666666667`), ASCII-space-padded (`" 407.666666666667 "`),
|
||||
/// zero-fraction (`407.0`), and Strict-namespace `arcTo`
|
||||
/// (`http://purl.oclc.org/ooxml/drawingml/main`) in a Transitional package —
|
||||
/// while opening the integer twin (`407`) cleanly.
|
||||
/// Follow-up context probes (Word for Mac 16.114.4) narrowed refusal further:
|
||||
/// Word refuses fractional radii in the selected `mc:Choice` (first Supported
|
||||
/// Choice, including a Choice with no `Requires` attribute — probe `r1`) or
|
||||
/// outside any `mc:AlternateContent` (bare `w:drawing` — probe `r2`), while
|
||||
/// opening fractional radii in an unselected second `mc:Choice`, in
|
||||
/// `mc:Fallback` when a Supported Choice precedes it, or in a Strict part
|
||||
/// (`http://purl.oclc.org/ooxml/...` root namespace). The foreign-namespace
|
||||
/// `mc:Fallback` probe is confounded (Word refuses that file for its MCE
|
||||
/// construction rather than measurably for the geometry), so `mc:Fallback` is
|
||||
/// treated as selected only when `mc:AlternateContent` contains no `Choice` at
|
||||
/// all.
|
||||
/// Error requires ALL of: Transitional part profile (root namespace resolved to
|
||||
/// a non-Strict URI) + Supported-selected branch at every enclosing level (bare
|
||||
/// drawing, Supported `mc:Choice`, or choice-less `mc:Fallback`, with `Requires`
|
||||
/// evaluated against a closed exact-URI allowlist of Word MCE capabilities
|
||||
/// including `w` and `wps`) + measured fractional geometry (raw XML attribute
|
||||
/// values matching `[ ]*-?[0-9]+\.[0-9]+[ ]*` with an `i64`-representable whole
|
||||
/// part in `a:arcTo` `wR`/`hR` in Transitional or Strict DrawingML namespace).
|
||||
/// Every other invalid geometry finding is graded Warning via
|
||||
/// [`Acc::add_graded`]. Warning grade precedence for measured fractional radii:
|
||||
/// Strict parts and definitively unselected enclosing `mc:AlternateContent`
|
||||
/// branches report `Warning` / `Observed`; unresolved part profiles and
|
||||
/// unresolved `AlternateContent` selections (including any `Choice` with an
|
||||
/// unlisted, undeclared, empty, or entity-obscured `Requires`, or a `Fallback`
|
||||
/// behind any `Choice`) report `Warning` / `MsDocumented` only in a non-Strict
|
||||
/// part with no definitively unselected enclosing branch. Unmeasured sibling
|
||||
/// attributes and unmeasured invalid lexical classes (`+`-prefixed fractions,
|
||||
/// non-space padding, entity/character-reference encodings, exponent forms,
|
||||
/// leading/trailing dots, empty/whitespace-only, out-of-schema-range integers,
|
||||
/// or out-of-`i64`-range whole parts) emit `Warning` / `MsDocumented`.
|
||||
pub(crate) const DML_COORDINATE: RuleSpec = RuleSpec { id: "DML-COORDINATE", severity: Severity::Error, evidence: Evidence::Observed };
|
||||
/// `CONTENTPART-TYPE`: a `w:contentPart` element whose relationship target's
|
||||
/// effective content type is not `text/xml`. MS-OI29500 Part 1 §17.3.3.2
|
||||
/// note (a): "Word will fail to load the document if the content part's
|
||||
@@ -522,6 +564,7 @@ pub(crate) const RULES: &[RuleSpec] = &[
|
||||
NOTE_PR_DANGLING,
|
||||
PROTECTION_PASSWORD,
|
||||
HEADERSOURCE_PRESENT,
|
||||
DML_COORDINATE,
|
||||
CONTENTPART_TYPE,
|
||||
REL_DUP_ID,
|
||||
REL_DANGLING,
|
||||
@@ -569,6 +612,9 @@ pub(crate) struct Acc {
|
||||
findings: Vec<Finding>,
|
||||
coverage: Vec<String>,
|
||||
checks: Vec<&'static str>,
|
||||
dml_coordinate_checked: bool,
|
||||
/// Document-wide count of measured `DML-COORDINATE` Error findings seen across all XML parts.
|
||||
dml_coordinate_errors: usize,
|
||||
incomplete: bool,
|
||||
limits: Limits,
|
||||
rule_counts: HashMap<&'static str, usize>,
|
||||
@@ -597,6 +643,40 @@ impl Acc {
|
||||
self.checks.push(rule);
|
||||
}
|
||||
|
||||
/// Record that a custom geometry scope was reached, once per package.
|
||||
fn ran_dml_coordinate(&mut self) {
|
||||
observation_contract! {
|
||||
rules: "DML-COORDINATE";
|
||||
collections: "-";
|
||||
scope: "report applicability for custom geometry";
|
||||
loss: "custom geometry may be absent from the scanned XML prefix";
|
||||
fallback: "record the rule once when the scanner reaches custom geometry";
|
||||
package_loss: "independent";
|
||||
}
|
||||
if !self.dml_coordinate_checked {
|
||||
self.ran(DML_COORDINATE.id);
|
||||
self.dml_coordinate_checked = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Count a measured `DML-COORDINATE` Error across the whole document and emit it via
|
||||
/// [`Acc::add`] at most `findings_per_rule + 1` times so repeated overflow Errors cannot
|
||||
/// append duplicate truncation coverage notes.
|
||||
pub(crate) fn add_dml_coordinate_error(&mut self, part: String, message: String) {
|
||||
observation_contract! {
|
||||
rules: "DML-COORDINATE";
|
||||
collections: "-";
|
||||
scope: "document-wide measured DML-COORDINATE error count and capped emission";
|
||||
loss: "per-rule finding cap";
|
||||
fallback: "count every measured error across all XML parts and emit at most cap + 1 times so truncation is noted once";
|
||||
package_loss: "independent";
|
||||
}
|
||||
self.dml_coordinate_errors = self.dml_coordinate_errors.saturating_add(1);
|
||||
if self.dml_coordinate_errors <= self.limits.findings_per_rule.saturating_add(1) {
|
||||
self.add(DML_COORDINATE.id, Some(part), message);
|
||||
}
|
||||
}
|
||||
|
||||
/// Record that the archive holds an entry whose identity could not be recovered. Absence
|
||||
/// conclusions are suppressed from here on (see [`contracts_generated::PACKAGE_ABSENCE_RULES`]).
|
||||
pub(crate) fn set_unknown_unreadable(&mut self) {
|
||||
@@ -1467,8 +1547,8 @@ fn xml_source_complete(xml: &XmlScan, entry: &package::Entry) -> bool {
|
||||
/// Scan all XML parts for well-formedness, undeclared prefixes, illegal characters, and extract story facts.
|
||||
fn check_xml(pkg: &Package, acc: &mut Acc) -> XmlScan {
|
||||
observation_contract! {
|
||||
rules: "HEADERSOURCE-PRESENT,MATH-PLACEMENT,PROTECTION-PASSWORD,STRUCT-END-P,XML-INVALID-CHAR,XML-MALFORMED,XML-UNDECLARED-PREFIX";
|
||||
collections: "access.prefix*1,access.retain_budget*1,field.comment_para_ids*1,field.content_part_exemptions*2,field.content_parts*2,field.entries*1,field.ink_content_parts*2,field.note_listings*1,field.refs*5,field.special_notes*1,field.unknown_prefixes*1,type.BTreeMap*1,type.HashMap*2,type.HashSet*2,type.Vec*13";
|
||||
rules: "DML-COORDINATE,HEADERSOURCE-PRESENT,MATH-PLACEMENT,PROTECTION-PASSWORD,STRUCT-END-P,XML-INVALID-CHAR,XML-MALFORMED,XML-UNDECLARED-PREFIX";
|
||||
collections: "access.prefix*1,access.retain_budget*1,field.comment_para_ids*1,field.content_part_exemptions*2,field.content_parts*2,field.dml_coordinate_warnings*1,field.entries*1,field.ink_content_parts*2,field.note_listings*1,field.refs*5,field.special_notes*1,field.unknown_prefixes*1,type.BTreeMap*1,type.HashMap*2,type.HashSet*2,type.Vec*15";
|
||||
scope: "source-local bounded extraction; no implicit document owner";
|
||||
loss: "source unavailable or malformed; XML event/depth budget; category allocation cap";
|
||||
fallback: "retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set";
|
||||
@@ -1510,6 +1590,7 @@ fn check_xml(pkg: &Package, acc: &mut Acc) -> XmlScan {
|
||||
let mut pooled_refs = 0usize;
|
||||
let mut refs_pooled_capped = false;
|
||||
let mut refs_pooled_part: Option<String> = None;
|
||||
let mut dml_coordinate_warnings: Vec<DeferredDmlWarning> = Vec::new();
|
||||
for e in pkg.entries.iter().filter(|e| !e.is_dir) {
|
||||
if !package::is_xml_part(pkg, &e.name) {
|
||||
continue;
|
||||
@@ -1542,6 +1623,8 @@ fn check_xml(pkg: &Package, acc: &mut Acc) -> XmlScan {
|
||||
let Some(text) = &e.decoded else { continue };
|
||||
let mut scanned = scan::scan_part(&e.name, text, role, acc);
|
||||
|
||||
append_dml_coordinate_warnings(&mut dml_coordinate_warnings, &e.name, scanned.dml_coordinate_warnings, acc.limits.findings_per_rule);
|
||||
|
||||
*note_incomplete_parts.entry(l.clone()).or_default() |= scanned.note_loss;
|
||||
if append_note_items(&mut note_listings, &mut special_notes, &e.name, scanned.note_listings, scanned.special_notes, acc.limits.facts) {
|
||||
*note_incomplete_parts.entry(l.clone()).or_default() |= scan::NOTE_ALL;
|
||||
@@ -1634,6 +1717,7 @@ fn check_xml(pkg: &Package, acc: &mut Acc) -> XmlScan {
|
||||
acc.add("XML-INVALID-CHAR", Some(e.name.clone()), format!("{} contains {desc}, which is illegal in XML 1.0", e.name));
|
||||
}
|
||||
}
|
||||
flush_dml_coordinate_warnings(dml_coordinate_warnings, acc);
|
||||
if pooled_capped {
|
||||
let part = facts_pooled_part.as_deref().unwrap_or("an unknown part");
|
||||
acc.note(format!("the pooled story facts exceeded {} entries at {part}; later facts were not recorded", acc.limits.facts));
|
||||
@@ -1666,6 +1750,47 @@ fn check_xml(pkg: &Package, acc: &mut Acc) -> XmlScan {
|
||||
XmlScan { graph, parts, compat }
|
||||
}
|
||||
|
||||
type DeferredDmlWarning = (String, scan::DmlWarnEvidence, String);
|
||||
|
||||
/// Buffer deferred `DML-COORDINATE` Warnings across XML parts up to one past the finding cap
|
||||
/// so Warnings can be emitted after all parts have been scanned without crowding out Errors.
|
||||
fn append_dml_coordinate_warnings(out: &mut Vec<DeferredDmlWarning>, part: &str, part_warnings: Vec<(scan::DmlWarnEvidence, String)>, cap: usize) {
|
||||
observation_contract! {
|
||||
rules: "-";
|
||||
collections: "type.Vec*2";
|
||||
scope: "bounded deferred DML-COORDINATE warnings across XML parts";
|
||||
loss: "per-rule finding cap";
|
||||
fallback: "retain up to one warning past the cap to exercise truncation after measured errors";
|
||||
package_loss: "independent";
|
||||
}
|
||||
|
||||
let budget = cap.saturating_add(1).saturating_sub(out.len());
|
||||
out.extend(part_warnings.into_iter().take(budget).map(|(evidence, message)| (part.to_string(), evidence, message)));
|
||||
}
|
||||
|
||||
/// Emit deferred `DML-COORDINATE` Warnings after all XML parts have been scanned, keeping at
|
||||
/// most one overflow Warning when measured Errors have not already exceeded the cap.
|
||||
fn flush_dml_coordinate_warnings(deferred: Vec<DeferredDmlWarning>, acc: &mut Acc) {
|
||||
observation_contract! {
|
||||
rules: "DML-COORDINATE";
|
||||
collections: "type.Observed*1,type.Vec*1";
|
||||
scope: "deferred DML-COORDINATE warnings emitted after all XML parts";
|
||||
loss: "per-rule finding cap";
|
||||
fallback: "emit measured errors ahead of warnings and trigger truncation at most once";
|
||||
package_loss: "independent";
|
||||
}
|
||||
|
||||
let errors_seen = acc.dml_coordinate_errors;
|
||||
let remaining = if errors_seen > acc.limits.findings_per_rule { 0 } else { (acc.limits.findings_per_rule - errors_seen).saturating_add(1) };
|
||||
for (part, evidence, message) in deferred.into_iter().take(remaining) {
|
||||
let evidence = match evidence {
|
||||
scan::DmlWarnEvidence::ObservedContext => Evidence::Observed,
|
||||
scan::DmlWarnEvidence::Unmeasured => Evidence::MsDocumented,
|
||||
};
|
||||
acc.add_graded(DML_COORDINATE.id, Severity::Warning, evidence, Some(part), message);
|
||||
}
|
||||
}
|
||||
|
||||
/// Attach each relationship fact collection's loss to its contributing source.
|
||||
fn store_relationship_observations(
|
||||
parts: &mut std::collections::BTreeMap<PartId, PartFacts>,
|
||||
@@ -6974,6 +7099,219 @@ mod budget_tests {
|
||||
assert!(mixed.findings.iter().any(|f| f.rule == "MEDIA-MAGIC" && f.severity == Severity::Warning));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dml_coordinate_budget_keeps_errors_ahead_of_warnings_across_orderings_and_parts() {
|
||||
let wrap_doc = |arcs: &str| {
|
||||
format!(
|
||||
r#"<?xml version="1.0"?><w:document xmlns:w="{NS_W}" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><w:body><w:p><w:r><a:custGeom><a:pathLst><a:path w="100" h="100">{arcs}</a:path></a:pathLst></a:custGeom></w:r></w:p></w:body></w:document>"#
|
||||
)
|
||||
.into_bytes()
|
||||
};
|
||||
let wrap_hdr = |arcs: &str| {
|
||||
format!(
|
||||
r#"<?xml version="1.0"?><w:hdr xmlns:w="{NS_W}" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><w:p><w:r><a:custGeom><a:pathLst><a:path w="100" h="100">{arcs}</a:path></a:pathLst></a:custGeom></w:r></w:p></w:hdr>"#
|
||||
)
|
||||
.into_bytes()
|
||||
};
|
||||
let zip_doc = |arcs: &str| {
|
||||
tiny_zip(&[
|
||||
("[Content_Types].xml", content_types()),
|
||||
("_rels/.rels", package_rels()),
|
||||
("word/document.xml", wrap_doc(arcs)),
|
||||
("word/_rels/document.xml.rels", doc_rels()),
|
||||
])
|
||||
};
|
||||
let warn_arc = r#"<a:arcTo wR="+12.5" hR="+12.5" stAng="0" swAng="cd4"/>"#;
|
||||
let err_arc = r#"<a:arcTo wR="12.5" hR="12.5" stAng="0" swAng="cd4"/>"#;
|
||||
let limits = Limits { findings_per_rule: 4, ..Limits::default() };
|
||||
|
||||
// Warnings-first, Errors-first, and interleaved orderings all keep both measured Errors
|
||||
// ahead of Warnings and bound total DML-COORDINATE findings to the cap.
|
||||
for (label, arcs) in [
|
||||
("warnings then error", format!("{warn_arc}{warn_arc}{warn_arc}{err_arc}")),
|
||||
("error then warnings", format!("{err_arc}{warn_arc}{warn_arc}{warn_arc}")),
|
||||
("interleaved", format!("{warn_arc}{err_arc}{warn_arc}{warn_arc}")),
|
||||
] {
|
||||
let report = validate_bytes_limited(&zip_doc(&arcs), limits);
|
||||
assert_eq!(report.verdict, Verdict::Fail, "{label}: {report:?}");
|
||||
let dml: Vec<_> = report.findings.iter().filter(|f| f.rule == "DML-COORDINATE").collect();
|
||||
assert_eq!(dml.len(), 4, "{label}: {dml:?}");
|
||||
assert_eq!(dml.iter().filter(|f| f.severity == Severity::Error && f.evidence == Evidence::Observed).count(), 2, "{label}: {dml:?}");
|
||||
assert_eq!(dml.iter().filter(|f| f.severity == Severity::Warning && f.evidence == Evidence::MsDocumented).count(), 2, "{label}: {dml:?}");
|
||||
assert_eq!(
|
||||
report.coverage_notes.iter().filter(|n| n.starts_with("more than 4 DML-COORDINATE")).count(),
|
||||
1,
|
||||
"{label}: {:?}",
|
||||
report.coverage_notes
|
||||
);
|
||||
}
|
||||
|
||||
// Cross-part: Warnings in word/document.xml exceed the cap before a measured Error in word/header1.xml.
|
||||
let cross_part = tiny_zip(&[
|
||||
("[Content_Types].xml", content_types()),
|
||||
("_rels/.rels", package_rels()),
|
||||
("word/document.xml", wrap_doc(&format!("{warn_arc}{warn_arc}{warn_arc}"))),
|
||||
("word/_rels/document.xml.rels", doc_rels()),
|
||||
("word/header1.xml", wrap_hdr(err_arc)),
|
||||
]);
|
||||
let cross_report = validate_bytes_limited(&cross_part, limits);
|
||||
assert_eq!(cross_report.verdict, Verdict::Fail, "{cross_report:?}");
|
||||
let cross_dml: Vec<_> = cross_report.findings.iter().filter(|f| f.rule == "DML-COORDINATE").collect();
|
||||
assert_eq!(cross_dml.len(), 4, "{cross_dml:?}");
|
||||
assert_eq!(
|
||||
cross_dml
|
||||
.iter()
|
||||
.filter(|f| f.part.as_deref() == Some("word/header1.xml") && f.severity == Severity::Error && f.evidence == Evidence::Observed)
|
||||
.count(),
|
||||
2,
|
||||
"{cross_dml:?}"
|
||||
);
|
||||
assert_eq!(cross_report.coverage_notes.iter().filter(|n| n.starts_with("more than 4 DML-COORDINATE")).count(), 1);
|
||||
|
||||
// Warnings-only overflow still yields Incomplete with bounded Warnings and one truncation note.
|
||||
let warn_only = validate_bytes_limited(&zip_doc(&format!("{warn_arc}{warn_arc}{warn_arc}")), limits);
|
||||
assert_eq!(warn_only.verdict, Verdict::Incomplete, "{warn_only:?}");
|
||||
let warn_dml: Vec<_> = warn_only.findings.iter().filter(|f| f.rule == "DML-COORDINATE").collect();
|
||||
assert_eq!(warn_dml.len(), 4, "{warn_dml:?}");
|
||||
assert!(warn_dml.iter().all(|f| f.severity == Severity::Warning));
|
||||
assert_eq!(warn_only.coverage_notes.iter().filter(|n| n.starts_with("more than 4 DML-COORDINATE")).count(), 1);
|
||||
|
||||
// Errors-only overflow with extra Warnings retains only Errors up to the cap and emits
|
||||
// exactly one truncation coverage note.
|
||||
let err_overflow = validate_bytes_limited(&zip_doc(&format!("{warn_arc}{err_arc}{warn_arc}{err_arc}{err_arc}")), limits);
|
||||
assert_eq!(err_overflow.verdict, Verdict::Fail, "{err_overflow:?}");
|
||||
let err_dml: Vec<_> = err_overflow.findings.iter().filter(|f| f.rule == "DML-COORDINATE").collect();
|
||||
assert_eq!(err_dml.len(), 4, "{err_dml:?}");
|
||||
assert!(err_dml.iter().all(|f| f.severity == Severity::Error && f.evidence == Evidence::Observed));
|
||||
assert_eq!(
|
||||
err_overflow.coverage_notes.iter().filter(|n| n.starts_with("more than 4 DML-COORDINATE")).count(),
|
||||
1,
|
||||
"single-part overflow errors must not duplicate truncation notes: {:?}",
|
||||
err_overflow.coverage_notes
|
||||
);
|
||||
|
||||
// Cross-part error overflow: cap 4, six measured Errors across two parts (2+4, 4+2, and
|
||||
// 6+2 with extra Warnings) must retain four Errors, emit exactly one DML-COORDINATE
|
||||
// truncation coverage note, and Fail.
|
||||
for (label, doc_arcs, hdr_arcs) in [
|
||||
("2+4 errors across two parts", err_arc.to_string(), format!("{err_arc}{err_arc}")),
|
||||
("4+2 errors across two parts", format!("{err_arc}{err_arc}"), err_arc.to_string()),
|
||||
("6+2 errors plus warnings across two parts", format!("{warn_arc}{err_arc}{err_arc}{err_arc}"), format!("{err_arc}{warn_arc}")),
|
||||
] {
|
||||
let two_part = tiny_zip(&[
|
||||
("[Content_Types].xml", content_types()),
|
||||
("_rels/.rels", package_rels()),
|
||||
("word/document.xml", wrap_doc(&doc_arcs)),
|
||||
("word/_rels/document.xml.rels", doc_rels()),
|
||||
("word/header1.xml", wrap_hdr(&hdr_arcs)),
|
||||
]);
|
||||
let report = validate_bytes_limited(&two_part, limits);
|
||||
assert_eq!(report.verdict, Verdict::Fail, "{label}: {report:?}");
|
||||
let dml: Vec<_> = report.findings.iter().filter(|f| f.rule == "DML-COORDINATE").collect();
|
||||
assert_eq!(dml.len(), 4, "{label}: {dml:?}");
|
||||
assert!(dml.iter().all(|f| f.severity == Severity::Error && f.evidence == Evidence::Observed), "{label}: {dml:?}");
|
||||
assert_eq!(
|
||||
report.coverage_notes.iter().filter(|n| n.starts_with("more than 4 DML-COORDINATE")).count(),
|
||||
1,
|
||||
"{label}: duplicate truncation notes: {:?}",
|
||||
report.coverage_notes
|
||||
);
|
||||
}
|
||||
|
||||
// Exact cap (2 Warnings + 2 Errors == 4) records all 4 with no truncation note.
|
||||
let exact = validate_bytes_limited(&zip_doc(&format!("{warn_arc}{err_arc}")), limits);
|
||||
assert_eq!(exact.verdict, Verdict::Fail, "{exact:?}");
|
||||
let exact_dml: Vec<_> = exact.findings.iter().filter(|f| f.rule == "DML-COORDINATE").collect();
|
||||
assert_eq!(exact_dml.len(), 4, "{exact_dml:?}");
|
||||
assert!(exact.coverage_notes.is_empty(), "{:?}", exact.coverage_notes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dml_coordinate_deferred_unselected_branch_warnings_preserve_observed_evidence_and_error_priority() {
|
||||
let wrap_doc = |body: &str| {
|
||||
format!(
|
||||
r#"<?xml version="1.0"?><w:document xmlns:w="{NS_W}" xmlns:mc="{NS_MC}" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"><w:body><w:p><w:r>{body}</w:r></w:p></w:body></w:document>"#
|
||||
)
|
||||
.into_bytes()
|
||||
};
|
||||
let wrap_hdr = |body: &str| {
|
||||
format!(
|
||||
r#"<?xml version="1.0"?><w:hdr xmlns:w="{NS_W}" xmlns:mc="{NS_MC}" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"><w:p><w:r>{body}</w:r></w:p></w:hdr>"#
|
||||
)
|
||||
.into_bytes()
|
||||
};
|
||||
let geom = |arcs: &str| format!(r#"<a:custGeom><a:pathLst><a:path w="100" h="100">{arcs}</a:path></a:pathLst></a:custGeom>"#);
|
||||
let frac_arc = r#"<a:arcTo wR="12.5" hR="12.5" stAng="0" swAng="cd4"/>"#;
|
||||
let plus_arc = r#"<a:arcTo wR="+12.5" hR="+12.5" stAng="0" swAng="cd4"/>"#;
|
||||
let ok_arc = r#"<a:arcTo wR="12" hR="12" stAng="0" swAng="cd4"/>"#;
|
||||
let limits = Limits { findings_per_rule: 4, ..Limits::default() };
|
||||
|
||||
// Unselected-branch Warnings (Fallback after satisfiable Choice) exceed cap in document.xml,
|
||||
// while a selected-branch Error sits later in header1.xml. Measured Errors must survive
|
||||
// ahead of unselected-branch Warnings, and retained unselected-branch Warnings must keep
|
||||
// Evidence::Observed while emitting a single truncation note.
|
||||
let unselected_six = format!(
|
||||
r#"<mc:AlternateContent><mc:Choice Requires="wps">{}</mc:Choice><mc:Fallback>{}</mc:Fallback></mc:AlternateContent>"#,
|
||||
geom(ok_arc),
|
||||
geom(&format!("{frac_arc}{frac_arc}{frac_arc}"))
|
||||
);
|
||||
let selected_two =
|
||||
format!(r#"<mc:AlternateContent><mc:Choice Requires="wps">{}</mc:Choice><mc:Fallback/></mc:AlternateContent>"#, geom(frac_arc));
|
||||
let cross_part = tiny_zip(&[
|
||||
("[Content_Types].xml", content_types()),
|
||||
("_rels/.rels", package_rels()),
|
||||
("word/document.xml", wrap_doc(&unselected_six)),
|
||||
("word/_rels/document.xml.rels", doc_rels()),
|
||||
("word/header1.xml", wrap_hdr(&selected_two)),
|
||||
]);
|
||||
let report = validate_bytes_limited(&cross_part, limits);
|
||||
assert_eq!(report.verdict, Verdict::Fail, "{report:?}");
|
||||
let dml: Vec<_> = report.findings.iter().filter(|f| f.rule == "DML-COORDINATE").collect();
|
||||
assert_eq!(dml.len(), 4, "{dml:?}");
|
||||
assert_eq!(
|
||||
dml.iter()
|
||||
.filter(|f| f.part.as_deref() == Some("word/header1.xml") && f.severity == Severity::Error && f.evidence == Evidence::Observed)
|
||||
.count(),
|
||||
2,
|
||||
"{dml:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
dml.iter()
|
||||
.filter(|f| f.part.as_deref() == Some("word/document.xml") && f.severity == Severity::Warning && f.evidence == Evidence::Observed)
|
||||
.count(),
|
||||
2,
|
||||
"{dml:?}"
|
||||
);
|
||||
assert_eq!(report.coverage_notes.iter().filter(|n| n.starts_with("more than 4 DML-COORDINATE")).count(), 1, "{:?}", report.coverage_notes);
|
||||
|
||||
// Mixed deferred Warning evidences in one part preserve each finding's own evidence class
|
||||
// (Observed for unselected-branch measured fraction, MsDocumented for unmeasured "+12.5").
|
||||
let mixed_warns = format!(
|
||||
r#"<mc:AlternateContent><mc:Choice Requires="wps">{}</mc:Choice><mc:Fallback>{}</mc:Fallback></mc:AlternateContent>"#,
|
||||
geom(ok_arc),
|
||||
geom(&format!("{frac_arc}{plus_arc}"))
|
||||
);
|
||||
let mixed_zip = tiny_zip(&[
|
||||
("[Content_Types].xml", content_types()),
|
||||
("_rels/.rels", package_rels()),
|
||||
("word/document.xml", wrap_doc(&mixed_warns)),
|
||||
("word/_rels/document.xml.rels", doc_rels()),
|
||||
]);
|
||||
let mixed = validate_bytes_limited(&mixed_zip, limits);
|
||||
assert_eq!(mixed.verdict, Verdict::Pass, "{mixed:?}");
|
||||
let mixed_dml: Vec<_> = mixed.findings.iter().filter(|f| f.rule == "DML-COORDINATE").collect();
|
||||
assert_eq!(mixed_dml.len(), 4, "{mixed_dml:?}");
|
||||
for (raw, want_evidence) in [("\"12.5\"", Evidence::Observed), ("\"+12.5\"", Evidence::MsDocumented)] {
|
||||
for attr in ["wR", "hR"] {
|
||||
let finding = mixed_dml
|
||||
.iter()
|
||||
.find(|f| f.message.contains(attr) && f.message.contains(raw))
|
||||
.unwrap_or_else(|| panic!("missing {attr}/{raw}: {mixed_dml:?}"));
|
||||
assert_eq!((finding.severity, finding.evidence), (Severity::Warning, want_evidence), "{attr}/{raw}: {finding:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn media_magic_webp_preflight_respects_and_charges_decode_budget() {
|
||||
let malformed = b"RIFF\x04\0\0\0WEBP";
|
||||
|
||||
+519
-17
@@ -386,6 +386,16 @@ impl StoryFacts {
|
||||
}
|
||||
}
|
||||
|
||||
/// Evidence basis for a deferred `DML-COORDINATE` Warning.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) enum DmlWarnEvidence {
|
||||
/// Word-measured toleration (Strict part or definitively unselected `mc:AlternateContent` branch).
|
||||
ObservedContext,
|
||||
/// Unresolved part profile, unresolved `AlternateContent` selection, unmeasured attribute,
|
||||
/// lexical class, entity encoding, or out-of-schema-range integer.
|
||||
Unmeasured,
|
||||
}
|
||||
|
||||
/// The result of scanning one XML or `.rels` part.
|
||||
pub(crate) struct PartScan {
|
||||
pub malformed: Option<String>,
|
||||
@@ -426,6 +436,10 @@ pub(crate) struct PartScan {
|
||||
pub fact_capped: bool,
|
||||
/// The per-part reference budget dropped at least one `r:id`/`r:embed`/`r:link`.
|
||||
pub refs_capped: bool,
|
||||
/// Deferred `DML-COORDINATE` warning `(evidence, message)` pairs collected during this part
|
||||
/// scan, bounded so Warnings can be flushed after all XML parts without crowding out measured
|
||||
/// Errors.
|
||||
pub dml_coordinate_warnings: Vec<(DmlWarnEvidence, String)>,
|
||||
/// All XML events and story facts were examined; absence joins may use this part.
|
||||
pub facts_complete: bool,
|
||||
/// XML events completed independently of individual fact/reference allocation caps.
|
||||
@@ -451,6 +465,10 @@ impl ElemId<'_> {
|
||||
fn wp(&self) -> bool {
|
||||
self.local_w(NS_WP)
|
||||
}
|
||||
/// Whether this element belongs to the DrawingML main namespace (`a:`).
|
||||
fn a(&self) -> bool {
|
||||
matches!(self.ns, Some(ns) if ns == NS_A.as_bytes() || ns == b"http://purl.oclc.org/ooxml/drawingml/main")
|
||||
}
|
||||
/// Whether this element belongs to the Office Math namespace (`m:`).
|
||||
fn m(&self) -> bool {
|
||||
self.local_w(NS_M)
|
||||
@@ -679,6 +697,10 @@ struct Frame {
|
||||
/// A `w:customXml` frame: likewise a prohibited direct parent only at block,
|
||||
/// cell, or row level — a run-level `customXml` inside a paragraph is not.
|
||||
is_custom_xml: bool,
|
||||
/// This element is within an `a:custGeom` subtree.
|
||||
in_custom_geometry: bool,
|
||||
/// Distinguishes `a:CT_Path2D` from the gradient-fill `a:path` variant.
|
||||
is_path_lst: bool,
|
||||
tc_has_block: bool,
|
||||
/// A block of known kind (or a skipped `AlternateContent`) was seen directly in this cell.
|
||||
tc_known_block: bool,
|
||||
@@ -691,9 +713,9 @@ struct Frame {
|
||||
/// This frame is an `mc:AlternateContent` element.
|
||||
alt: bool,
|
||||
/// For an `mc:Choice` / `mc:Fallback` frame that assigned the
|
||||
/// enclosing block's current branch: the branch value to restore
|
||||
/// when this frame closes.
|
||||
alt_branch_prev: Option<u32>,
|
||||
/// enclosing block's current branch: the `(branch, in_selected_branch)`
|
||||
/// pair to restore when this frame closes.
|
||||
alt_branch_prev: Option<(u32, bool)>,
|
||||
/// The element was opened inside a skipped `mc:AlternateContent` subtree, so its closing event
|
||||
/// must not touch the frame counters or report structural findings.
|
||||
suppressed: bool,
|
||||
@@ -768,6 +790,8 @@ struct State {
|
||||
alt_depth: usize,
|
||||
/// One coverage note per part that contains `mc:AlternateContent`.
|
||||
alt_noted: bool,
|
||||
/// Profile of this part's root element namespace (Transitional, Strict, or Unresolved).
|
||||
part_profile: PartProfile,
|
||||
/// The per-category fact budget, copied from [`crate::Limits`].
|
||||
fact_cap: usize,
|
||||
/// A fact budget was exhausted; no further facts are collected.
|
||||
@@ -1055,7 +1079,7 @@ fn decode_utf16_strict(bytes: &[u8], little_endian: bool) -> Result<String, Deco
|
||||
pub(crate) fn scan_part(part: &str, text: &str, role: PartRole, acc: &mut Acc) -> PartScan {
|
||||
observation_contract! {
|
||||
rules: "STRUCT-TC-NO-P";
|
||||
collections: "access.into_complete_set*2,access.invalidate*2,field.alt_stack*2,field.content_part_exemptions*2,field.content_parts*2,field.declared*8,field.frames*10,field.note_listings*1,field.note_listings_e*1,field.note_listings_f*1,field.para_ids*1,field.special_notes*2,field.unknown_prefixes*2,parser.parse_doctype_entities*1,type.BTreeMap*1,type.HashMap*1,type.HashSet*1,type.Observed*1,type.Vec*9";
|
||||
collections: "access.into_complete_set*2,access.invalidate*2,field.alt_stack*2,field.content_part_exemptions*2,field.content_parts*2,field.declared*8,field.frames*10,field.note_listings*1,field.note_listings_e*1,field.note_listings_f*1,field.para_ids*1,field.special_notes*2,field.unknown_prefixes*2,parser.parse_doctype_entities*1,type.BTreeMap*1,type.HashMap*1,type.HashSet*1,type.Observed*1,type.Vec*10";
|
||||
scope: "source-local bounded extraction; no implicit document owner";
|
||||
loss: "source unavailable or malformed; XML event/depth budget; category allocation cap";
|
||||
fallback: "retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set";
|
||||
@@ -1086,6 +1110,7 @@ pub(crate) fn scan_part(part: &str, text: &str, role: PartRole, acc: &mut Acc) -
|
||||
note_loss: 0,
|
||||
fact_capped: false,
|
||||
refs_capped: false,
|
||||
dml_coordinate_warnings: Vec::new(),
|
||||
facts_complete: false,
|
||||
syntax_complete: false,
|
||||
};
|
||||
@@ -1116,7 +1141,8 @@ pub(crate) fn scan_part(part: &str, text: &str, role: PartRole, acc: &mut Acc) -
|
||||
}
|
||||
Ok(Event::Eof) => break,
|
||||
Ok(Event::Start(e)) => {
|
||||
if state.frames.is_empty() {
|
||||
let is_root = state.frames.is_empty();
|
||||
if is_root {
|
||||
if root_count >= 1 {
|
||||
out.malformed = Some("more than one document element".to_string());
|
||||
break;
|
||||
@@ -1139,11 +1165,13 @@ pub(crate) fn scan_part(part: &str, text: &str, role: PartRole, acc: &mut Acc) -
|
||||
let decls = declarations(&attrs);
|
||||
state.declared.push(decls);
|
||||
note_unresolved_element(&mut state, &mut id, &[]);
|
||||
record_root_profile(&mut state, is_root, &id);
|
||||
let is_alt = enter_alt(&mut state, &id, part, acc);
|
||||
let branch_prev = assign_alt_branch(&mut state, &id);
|
||||
let branch_prev = assign_alt_branch(&mut state, &id, &attrs, reader.resolver(), &[]);
|
||||
push_unknown_prefix(&mut out, &state.declared, &[], id.unknown.as_deref());
|
||||
check_prefixes(&state.declared, &attrs, reader.resolver(), (&[], complete_entities.as_ref().map(|_| &entity_decls)), &mut out);
|
||||
collect_ink_content_part(&id, &attrs, reader.resolver(), &mut out, acc.limits.facts);
|
||||
check_dml_coordinates(&state, &id, &attrs, part, &mut out, acc);
|
||||
if !was_suppressed {
|
||||
collect_refs(&id, &attrs, reader.resolver(), &mut out, acc.limits.facts, &mut state.refs_capped);
|
||||
collect_content_part(&id, &attrs, reader.resolver(), &mut out.content_parts, acc.limits.facts, &mut out.content_part_capped);
|
||||
@@ -1161,11 +1189,18 @@ pub(crate) fn scan_part(part: &str, text: &str, role: PartRole, acc: &mut Acc) -
|
||||
);
|
||||
check_para_ids(&mut state, &id, &attrs, reader.resolver(), role, part, acc);
|
||||
}
|
||||
let frame = Frame { alt: is_alt, suppressed: was_suppressed, alt_branch_prev: branch_prev, ..frame_for(&id) };
|
||||
let frame = Frame {
|
||||
alt: is_alt,
|
||||
suppressed: was_suppressed,
|
||||
alt_branch_prev: branch_prev,
|
||||
in_custom_geometry: in_custom_geometry(&state, &id),
|
||||
..frame_for(&id)
|
||||
};
|
||||
state.frames.push(frame);
|
||||
}
|
||||
Ok(Event::Empty(e)) => {
|
||||
if state.frames.is_empty() {
|
||||
let is_root = state.frames.is_empty();
|
||||
if is_root {
|
||||
if root_count >= 1 {
|
||||
out.malformed = Some("more than one document element".to_string());
|
||||
break;
|
||||
@@ -1181,11 +1216,13 @@ pub(crate) fn scan_part(part: &str, text: &str, role: PartRole, acc: &mut Acc) -
|
||||
let was_suppressed = state.alt_depth > 0;
|
||||
let decls = declarations(&attrs);
|
||||
note_unresolved_element(&mut state, &mut id, &decls);
|
||||
record_root_profile(&mut state, is_root, &id);
|
||||
let is_alt = enter_alt(&mut state, &id, part, acc);
|
||||
let branch_prev = assign_alt_branch(&mut state, &id);
|
||||
let branch_prev = assign_alt_branch(&mut state, &id, &attrs, reader.resolver(), &decls);
|
||||
push_unknown_prefix(&mut out, &state.declared, &decls, id.unknown.as_deref());
|
||||
check_prefixes(&state.declared, &attrs, reader.resolver(), (&decls, complete_entities.as_ref().map(|_| &entity_decls)), &mut out);
|
||||
collect_ink_content_part(&id, &attrs, reader.resolver(), &mut out, acc.limits.facts);
|
||||
check_dml_coordinates(&state, &id, &attrs, part, &mut out, acc);
|
||||
if !was_suppressed {
|
||||
collect_refs(&id, &attrs, reader.resolver(), &mut out, acc.limits.facts, &mut state.refs_capped);
|
||||
collect_content_part(&id, &attrs, reader.resolver(), &mut out.content_parts, acc.limits.facts, &mut out.content_part_capped);
|
||||
@@ -1448,11 +1485,20 @@ fn enter_alt(state: &mut State, id: &ElemId, part: &str, acc: &mut Acc) -> bool
|
||||
|
||||
// An `AlternateContent` of unresolved namespace may be the markup-compatibility one: it is treated as that,
|
||||
// so its branches are skipped exactly as the literal spelling's are (nothing in them is established).
|
||||
let is_alt = id.local == "AlternateContent" && (id.ns == Some(NS_MC.as_bytes()) || id.unresolved);
|
||||
let is_mc = id.ns == Some(NS_MC.as_bytes());
|
||||
let is_alt = id.local == "AlternateContent" && (is_mc || id.unresolved);
|
||||
if is_alt {
|
||||
state.alt_depth += 1;
|
||||
state.alt_seq += 1;
|
||||
state.alt_stack.push(AltCtx { seq: state.alt_seq, branch: 0 });
|
||||
state.alt_stack.push(AltCtx {
|
||||
seq: state.alt_seq,
|
||||
branch: 0,
|
||||
is_mc,
|
||||
choice_seen: false,
|
||||
selected_seen: false,
|
||||
selection_unresolved: !is_mc,
|
||||
in_selected_branch: false,
|
||||
});
|
||||
if !state.alt_noted {
|
||||
acc.note(format!("{part} contains mc:AlternateContent; its contents were skipped"));
|
||||
state.alt_noted = true;
|
||||
@@ -1505,6 +1551,8 @@ fn frame_for(id: &ElemId) -> Frame {
|
||||
},
|
||||
is_sdt_content: w && local == "sdtContent",
|
||||
is_custom_xml: w && local == "customXml",
|
||||
in_custom_geometry: false,
|
||||
is_path_lst: id.a() && local == "pathLst",
|
||||
tc_has_block: false,
|
||||
tc_known_block: false,
|
||||
tc_unresolved_candidate: false,
|
||||
@@ -1946,6 +1994,405 @@ fn check_header_source(state: &mut State, id: &ElemId, role: PartRole, part: &st
|
||||
}
|
||||
}
|
||||
|
||||
/// Schema-defined integer bounds for DrawingML custom geometry types (`dml-main.xsd`).
|
||||
/// `ST_CoordinateUnqualified` (§20.1.10.19): `i32::MIN * 12_700 ..= i32::MAX * 12_700`.
|
||||
const DML_COORD_MIN: i64 = -27_273_042_329_600;
|
||||
const DML_COORD_MAX: i64 = 27_273_042_316_900;
|
||||
/// `ST_Angle` (§20.1.10.3): `xsd:int`.
|
||||
const DML_ANGLE_MIN: i64 = i32::MIN as i64;
|
||||
const DML_ANGLE_MAX: i64 = i32::MAX as i64;
|
||||
|
||||
/// Schema lexical domains and integer bounds used by the custom geometry types in `dml-main.xsd`.
|
||||
#[derive(Clone, Copy)]
|
||||
enum CoordKind {
|
||||
/// `ST_PositiveCoordinate` (§20.1.10.41, path dimensions): integer only, `0..=27273042316900`.
|
||||
PositiveCoordinate,
|
||||
/// `ST_AdjCoordinate` (§20.1.10.2, coordinates/radii): `ST_CoordinateUnqualified`
|
||||
/// (`-27273042329600..=27273042316900`), `ST_UniversalMeasure`, or `ST_GeomGuideName`.
|
||||
AdjCoordinate,
|
||||
/// `ST_AdjAngle` (§20.1.10.1, angles): `ST_Angle` (`xsd:int`, `-2147483648..=2147483647`)
|
||||
/// or `ST_GeomGuideName`.
|
||||
AdjAngle,
|
||||
}
|
||||
|
||||
impl CoordKind {
|
||||
fn allows_guide_name(self) -> bool {
|
||||
matches!(self, Self::AdjCoordinate | Self::AdjAngle)
|
||||
}
|
||||
|
||||
fn int_in_range(self, value: i64) -> bool {
|
||||
match self {
|
||||
Self::PositiveCoordinate => (0..=DML_COORD_MAX).contains(&value),
|
||||
Self::AdjCoordinate => (DML_COORD_MIN..=DML_COORD_MAX).contains(&value),
|
||||
Self::AdjAngle => (DML_ANGLE_MIN..=DML_ANGLE_MAX).contains(&value),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Classification of a custom geometry attribute value against its lexical domain.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum CoordLiteral {
|
||||
/// Valid in-range integer, or (for adjustable attributes) a non-numeric guide name or
|
||||
/// universal measure.
|
||||
Valid,
|
||||
/// Measured-refused decimal-fraction spelling (#8231, Word for Mac 16.114.4, 2026-12-02):
|
||||
/// raw XML attribute source matching `[ ]*-?[0-9]+\.[0-9]+[ ]*` with an `i64`-representable
|
||||
/// whole part.
|
||||
MeasuredDecimalFraction,
|
||||
/// Any other invalid numeric literal (unmeasured signs such as `+`, non-space whitespace
|
||||
/// padding, entity/character-reference-encoded spellings, empty/whitespace-only, lone sign,
|
||||
/// lone dot, leading/trailing dot, scientific notation, integer outside its schema type's
|
||||
/// bounds or whole part outside `i64` range, or non-integer on an integer-only type).
|
||||
OtherInvalid,
|
||||
}
|
||||
|
||||
/// Return `(raw_source, normalized)` for an unprefixed attribute by exact name.
|
||||
///
|
||||
/// `raw_source` is the undecoded UTF-8 attribute slice from the XML source (preserving character
|
||||
/// references, entity references, and literal `\t`/`\r`/`\n` before XML 1.0 attribute-value
|
||||
/// normalization), while `normalized` is `Some` when XML 1.0 normalization succeeds and `None`
|
||||
/// when normalization fails (for example, on a DOCTYPE-declared or unresolvable entity reference).
|
||||
fn dml_attr_values<'a>(attrs: &'a [Attribute<'a>], name: &[u8]) -> Option<(&'a str, Option<String>)> {
|
||||
let attr = attrs.iter().find(|a| a.key.as_ref() == name)?;
|
||||
let raw_source = std::str::from_utf8(attr.value.as_ref()).ok()?;
|
||||
let normalized = attr.normalized_value(quick_xml::XmlVersion::Implicit1_0).ok().map(std::borrow::Cow::into_owned);
|
||||
Some((raw_source, normalized))
|
||||
}
|
||||
|
||||
/// Whether `raw_source` (undecoded, unnormalized XML attribute value) belongs to the
|
||||
/// measured-refused decimal-fraction lexical set (#8231, Word for Mac 16.114.4, 2026-12-02):
|
||||
/// optional surrounding ASCII spaces (`' '`), optional leading `-`, one or more ASCII digits,
|
||||
/// `.`, one or more ASCII digits, with an `i64`-representable signed whole part.
|
||||
///
|
||||
/// Unmeasured spellings — `+`-prefixed fractions, non-space whitespace (`\t`, `\r`, `\n`,
|
||||
/// non-ASCII spaces), character-reference or entity encodings, exponent forms, leading/trailing
|
||||
/// dot forms, empty/whitespace-only values, and out-of-`i64`-range whole parts — return `false`
|
||||
/// and never take the `Error` / `Observed` path.
|
||||
fn is_measured_decimal_fraction(raw_source: &str) -> bool {
|
||||
let trimmed = raw_source.trim_matches(' ');
|
||||
let Some((signed_whole, frac)) = trimmed.split_once('.') else { return false };
|
||||
let whole = signed_whole.strip_prefix('-').unwrap_or(signed_whole);
|
||||
!whole.is_empty()
|
||||
&& !frac.is_empty()
|
||||
&& whole.chars().all(|c| c.is_ascii_digit())
|
||||
&& frac.chars().all(|c| c.is_ascii_digit())
|
||||
&& signed_whole.parse::<i64>().is_ok()
|
||||
}
|
||||
|
||||
/// Classify unqualified numeric literals using both the raw XML attribute source and its
|
||||
/// XML 1.0 normalized value. Other tokens in adjustable attributes may be guide names
|
||||
/// (including `3cd4`), or a unit-qualified `ST_UniversalMeasure` for coordinates.
|
||||
/// Values whose XML 1.0 normalization failed (such as DOCTYPE-declared or unresolvable entity
|
||||
/// references) classify as [`CoordLiteral::OtherInvalid`] so they reach the Warning path using
|
||||
/// their raw text and never enter the `Error` / `Observed` path.
|
||||
fn classify_dml_coord(raw_source: &str, normalized: Option<&str>, kind: CoordKind) -> CoordLiteral {
|
||||
let Some(normalized) = normalized else {
|
||||
return CoordLiteral::OtherInvalid;
|
||||
};
|
||||
let value = normalized.trim_matches([' ', '\t', '\r', '\n']);
|
||||
if let Ok(int_value) = value.parse::<i64>() {
|
||||
return if kind.int_in_range(int_value) { CoordLiteral::Valid } else { CoordLiteral::OtherInvalid };
|
||||
}
|
||||
if is_measured_decimal_fraction(raw_source) {
|
||||
return CoordLiteral::MeasuredDecimalFraction;
|
||||
}
|
||||
let unsigned = value.strip_prefix(['+', '-']).unwrap_or(value);
|
||||
let numeric =
|
||||
unsigned.is_empty() || unsigned == "." || (unsigned.starts_with(|c: char| c.is_ascii_digit() || c == '.') && value.parse::<f64>().is_ok());
|
||||
if kind.allows_guide_name() && !numeric { CoordLiteral::Valid } else { CoordLiteral::OtherInvalid }
|
||||
}
|
||||
|
||||
/// The parser keeps each custom geometry scope even inside AlternateContent.
|
||||
fn in_custom_geometry(state: &State, id: &ElemId) -> bool {
|
||||
observation_contract! {
|
||||
rules: "-";
|
||||
collections: "field.frames*1";
|
||||
scope: "custom geometry ancestry of the current XML event";
|
||||
loss: "XML event/depth budget";
|
||||
fallback: "use ancestry of events already scanned";
|
||||
package_loss: "independent";
|
||||
}
|
||||
(id.a() && id.local == "custGeom") || state.frames.last().is_some_and(|frame| frame.in_custom_geometry)
|
||||
}
|
||||
|
||||
/// Observed-Error custom geometry attributes (#8231): only measured decimal-fraction spellings in
|
||||
/// `wR`/`hR` on `a:arcTo` (Transitional or Strict DrawingML namespace) have desktop consumer
|
||||
/// refusal measurements (Word for Mac 16.114.4, 2026-12-02).
|
||||
fn is_observed_decimal_attr(local: &str, attr: &str) -> bool {
|
||||
local == "arcTo" && matches!(attr, "wR" | "hR")
|
||||
}
|
||||
|
||||
/// Schema-typed custom geometry attributes of CT_Path2D, CT_Path2DArcTo, CT_AdjPoint2D,
|
||||
/// CT_GeomRect, CT_XYAdjustHandle, CT_PolarAdjustHandle and CT_ConnectionSite in the model.
|
||||
/// Entries outside [`is_observed_decimal_attr`] (and unmeasured invalid literals on any entry)
|
||||
/// are unmeasured and graded Warning / MsDocumented.
|
||||
fn dml_coord_spec(local: &str, is_path: bool) -> &'static [(&'static str, CoordKind)] {
|
||||
use CoordKind::{AdjAngle, AdjCoordinate, PositiveCoordinate};
|
||||
match local {
|
||||
"arcTo" => &[("wR", AdjCoordinate), ("hR", AdjCoordinate), ("stAng", AdjAngle), ("swAng", AdjAngle)],
|
||||
"pt" | "pos" => &[("x", AdjCoordinate), ("y", AdjCoordinate)],
|
||||
"rect" => &[("l", AdjCoordinate), ("t", AdjCoordinate), ("r", AdjCoordinate), ("b", AdjCoordinate)],
|
||||
"ahXY" => &[("minX", AdjCoordinate), ("maxX", AdjCoordinate), ("minY", AdjCoordinate), ("maxY", AdjCoordinate)],
|
||||
"ahPolar" => &[("minR", AdjCoordinate), ("maxR", AdjCoordinate), ("minAng", AdjAngle), ("maxAng", AdjAngle)],
|
||||
"cxn" => &[("ang", AdjAngle)],
|
||||
"path" if is_path => &[("w", PositiveCoordinate), ("h", PositiveCoordinate)],
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
|
||||
/// Root namespace profile of the part currently being scanned.
|
||||
#[derive(Clone, Copy, Default, PartialEq, Eq)]
|
||||
enum PartProfile {
|
||||
/// Root element namespace resolved to a Transitional (non-Strict) URI.
|
||||
Transitional,
|
||||
/// Root element namespace resolved to a Strict OOXML URI (`http://purl.oclc.org/ooxml/...`).
|
||||
Strict,
|
||||
/// Root element namespace could not be resolved by the scanner (for example, entity-obscured
|
||||
/// `xmlns`, undeclared prefix, or no namespace binding).
|
||||
#[default]
|
||||
Unresolved,
|
||||
}
|
||||
|
||||
/// Record the namespace profile of this part's root element.
|
||||
fn record_root_profile(state: &mut State, is_root: bool, id: &ElemId) {
|
||||
if is_root {
|
||||
state.part_profile = match id.ns {
|
||||
Some(ns) if !id.unresolved && is_strict_ooxml_ns(ns) => PartProfile::Strict,
|
||||
Some(ns) if !id.unresolved && !ns.is_empty() => PartProfile::Transitional,
|
||||
_ => PartProfile::Unresolved,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a namespace URI belongs to the Strict OOXML family (`http://purl.oclc.org/ooxml/...`).
|
||||
fn is_strict_ooxml_ns(ns: &[u8]) -> bool {
|
||||
ns.starts_with(b"http://purl.oclc.org/ooxml/")
|
||||
}
|
||||
|
||||
/// Whether `ns` is an exact full namespace URI proven by a Word measurement to be rejected as an
|
||||
/// `mc:Choice/@Requires` capability without confounding MCE rejection.
|
||||
///
|
||||
/// Currently always returns `false`: no capability is populated by inference.
|
||||
fn is_unsupported_word_mce_capability(ns: &[u8]) -> bool {
|
||||
let _ = ns;
|
||||
false
|
||||
}
|
||||
|
||||
/// Whether `ns` is an exact full namespace URI known to be supported by Word as an
|
||||
/// `mc:Choice/@Requires` capability.
|
||||
///
|
||||
/// The measured anchor is `http://schemas.microsoft.com/office/word/2010/wordprocessingShape`
|
||||
/// (`wps`, corpus document `d60c276dc845` and Word for Mac 16.114.4 context probes).
|
||||
/// The remaining entries are Word's own main WordprocessingML namespace (`w`) and the complete
|
||||
/// URIs of Word's shipped MCE capability namespaces (`wordprocessingGroup`,
|
||||
/// `wordprocessingCanvas`, `wordprocessingInk`, `wordprocessingDrawing`, 2010/2012
|
||||
/// WordprocessingML, and 2010/2012 DrawingML extensions) that Word resolves as `Requires`
|
||||
/// capabilities.
|
||||
///
|
||||
/// Match by exact URI equality only — closed list, never prefix or namespace-family matching.
|
||||
/// Additions require a Word measurement or a Word-produced document showing the `Requires` value.
|
||||
fn is_word_mce_capability(ns: &[u8]) -> bool {
|
||||
matches!(
|
||||
ns,
|
||||
// WordprocessingML main namespace (w).
|
||||
b"http://schemas.openxmlformats.org/wordprocessingml/2006/main"
|
||||
// Word 2010 shapes (wps — measured anchor).
|
||||
| b"http://schemas.microsoft.com/office/word/2010/wordprocessingShape"
|
||||
// Word 2010 shape groups, drawing canvas, ink, and drawing extensions (wpg, wpc, wpi, wp14).
|
||||
| b"http://schemas.microsoft.com/office/word/2010/wordprocessingGroup"
|
||||
| b"http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas"
|
||||
| b"http://schemas.microsoft.com/office/word/2010/wordprocessingInk"
|
||||
| b"http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing"
|
||||
// Word 2010 and 2012 WordprocessingML extensions (w14, w15).
|
||||
| b"http://schemas.microsoft.com/office/word/2010/wordml"
|
||||
| b"http://schemas.microsoft.com/office/word/2012/wordml"
|
||||
// Office 2010 and 2012 DrawingML extensions (a14, pic14, dgm14, cdr14, a15, c15, cs).
|
||||
| b"http://schemas.microsoft.com/office/drawing/2010/main"
|
||||
| b"http://schemas.microsoft.com/office/drawing/2010/picture"
|
||||
| b"http://schemas.microsoft.com/office/drawing/2010/diagram"
|
||||
| b"http://schemas.microsoft.com/office/drawing/2010/chartDrawing"
|
||||
| b"http://schemas.microsoft.com/office/drawing/2012/main"
|
||||
| b"http://schemas.microsoft.com/office/drawing/2012/chart"
|
||||
| b"http://schemas.microsoft.com/office/drawing/2012/chartStyle"
|
||||
)
|
||||
}
|
||||
|
||||
/// Three-state evaluation outcome of an `mc:Choice/@Requires` attribute.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum ChoiceState {
|
||||
/// Every required prefix resolved to an exact URI in [`is_word_mce_capability`] (or `Requires`
|
||||
/// was absent — measured in Word for Mac probe `r1`).
|
||||
Supported,
|
||||
/// At least one required prefix resolved to a URI not on the allowlist, could not be resolved
|
||||
/// (undeclared, malformed, or entity-obscured), or `Requires` itself was empty or unreadable.
|
||||
/// Makes the whole enclosing `mc:AlternateContent`'s selection uncertain.
|
||||
Unresolved,
|
||||
/// Reserved for capabilities a Word measurement proves Word rejects without confounding MCE
|
||||
/// rejection. Never populated by inference; [`is_unsupported_word_mce_capability`] always
|
||||
/// returns `false` today.
|
||||
Unsupported,
|
||||
}
|
||||
|
||||
/// Evaluate a single prefix token from `mc:Choice/@Requires` against [`is_word_mce_capability`].
|
||||
fn prefix_requires_state(prefix: &str, res: &NamespaceResolver, declared: &[Vec<String>], own_decls: &[String]) -> ChoiceState {
|
||||
observation_contract! {
|
||||
rules: "-";
|
||||
collections: "type.Vec*1";
|
||||
scope: "namespace scope for one mc:Choice Requires prefix";
|
||||
loss: "XML event/depth budget; entity-obscured xmlns declaration";
|
||||
fallback: "treat unlisted, undeclared, malformed, or entity-obscured prefix bindings as unresolved rather than supported or unsupported";
|
||||
package_loss: "independent";
|
||||
}
|
||||
if prefix.is_empty() || prefix.as_bytes().contains(&b':') {
|
||||
return ChoiceState::Unresolved;
|
||||
}
|
||||
if nearest_binding(declared, own_decls, prefix) == Binding::Unresolved {
|
||||
return ChoiceState::Unresolved;
|
||||
}
|
||||
let qname = format!("{prefix}:_");
|
||||
match res.resolve_attribute(QName(qname.as_bytes())).0 {
|
||||
ResolveResult::Bound(Namespace(ns)) if is_word_mce_capability(ns) => ChoiceState::Supported,
|
||||
ResolveResult::Bound(Namespace(ns)) if is_unsupported_word_mce_capability(ns) => ChoiceState::Unsupported,
|
||||
_ => ChoiceState::Unresolved,
|
||||
}
|
||||
}
|
||||
|
||||
/// Evaluate an `mc:Choice` element's `Requires` attribute into [`ChoiceState`]:
|
||||
/// - Missing `Requires` is [`ChoiceState::Supported`] (measured in Word for Mac probe `r1`:
|
||||
/// fractional radii inside an `mc:Choice` with no `Requires` attribute are refused).
|
||||
/// - If every whitespace-delimited prefix resolves to an exact URI in [`is_word_mce_capability`],
|
||||
/// returns [`ChoiceState::Supported`].
|
||||
/// - If any prefix resolves to a URI in [`is_unsupported_word_mce_capability`] (currently none),
|
||||
/// returns [`ChoiceState::Unsupported`].
|
||||
/// - Otherwise (any unlisted URI, undeclared/malformed prefix, empty `Requires`, or
|
||||
/// entity-obscured `Requires` / `xmlns`), returns [`ChoiceState::Unresolved`].
|
||||
fn choice_requires_state(attrs: &[Attribute], res: &NamespaceResolver, declared: &[Vec<String>], own_decls: &[String]) -> ChoiceState {
|
||||
observation_contract! {
|
||||
rules: "-";
|
||||
collections: "type.Vec*1";
|
||||
scope: "mc:Choice Requires attribute evaluation in current namespace scope";
|
||||
loss: "XML event/depth budget; entity-obscured Requires or xmlns declaration";
|
||||
fallback: "withhold Error by returning Unresolved when Requires or any prefix binding is unlisted, empty, undeclared, or unreadable";
|
||||
package_loss: "independent";
|
||||
}
|
||||
let Some(attr) = attrs.iter().find(|a| a.key.as_ref() == b"Requires") else {
|
||||
return ChoiceState::Supported;
|
||||
};
|
||||
let Ok(value) = attr.normalized_value(quick_xml::XmlVersion::Implicit1_0) else {
|
||||
return ChoiceState::Unresolved;
|
||||
};
|
||||
let mut saw_prefix = false;
|
||||
let mut unresolved = false;
|
||||
for prefix in value.split([' ', '\t', '\r', '\n']).filter(|prefix| !prefix.is_empty()) {
|
||||
saw_prefix = true;
|
||||
match prefix_requires_state(prefix, res, declared, own_decls) {
|
||||
ChoiceState::Supported => {}
|
||||
ChoiceState::Unsupported => return ChoiceState::Unsupported,
|
||||
ChoiceState::Unresolved => unresolved = true,
|
||||
}
|
||||
}
|
||||
if !saw_prefix || unresolved { ChoiceState::Unresolved } else { ChoiceState::Supported }
|
||||
}
|
||||
|
||||
/// Enclosing `mc:AlternateContent` selection status for custom geometry checks.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum DmlBranchSelection {
|
||||
/// Outside every `mc:AlternateContent`, or inside the Supported-selected branch of every
|
||||
/// enclosing `mc:AlternateContent` (including a choice-less `mc:Fallback`).
|
||||
Selected,
|
||||
/// Inside a definitively unselected branch of at least one enclosing `mc:AlternateContent`.
|
||||
Unselected,
|
||||
/// At least one enclosing `AlternateContent` has unresolved selection (for example, an
|
||||
/// unlisted `Requires` capability, a `Fallback` behind a Choice, or an entity-obscured
|
||||
/// `xmlns` / `Requires`) and none is definitively unselected.
|
||||
Unresolved,
|
||||
}
|
||||
|
||||
/// Determine whether the current XML event sits in an established Supported-selected branch, a
|
||||
/// definitively unselected branch, or an unresolved `AlternateContent` context.
|
||||
fn dml_branch_selection(state: &State) -> DmlBranchSelection {
|
||||
observation_contract! {
|
||||
rules: "-";
|
||||
collections: "field.alt_stack*1";
|
||||
scope: "enclosing mc:AlternateContent branch selection for the current XML event";
|
||||
loss: "XML event/depth budget";
|
||||
fallback: "evaluate enclosing AlternateContent frames already scanned";
|
||||
package_loss: "independent";
|
||||
}
|
||||
let mut unresolved = false;
|
||||
for ctx in &state.alt_stack {
|
||||
if ctx.is_mc && !ctx.selection_unresolved {
|
||||
if !ctx.in_selected_branch {
|
||||
return DmlBranchSelection::Unselected;
|
||||
}
|
||||
} else {
|
||||
unresolved = true;
|
||||
}
|
||||
}
|
||||
if unresolved { DmlBranchSelection::Unresolved } else { DmlBranchSelection::Selected }
|
||||
}
|
||||
|
||||
/// Report invalid custom geometry literals from the XML events in every branch.
|
||||
/// Measured Errors require ALL of: Transitional part profile + Supported-selected branch (bare
|
||||
/// drawing, Supported `mc:Choice`, or choice-less `mc:Fallback` at every enclosing level) +
|
||||
/// measured fractional geometry (`a:arcTo` `wR`/`hR`). Everything else is Warning, buffered in
|
||||
/// `out` (bounded to one entry past the per-rule finding cap) and flushed after all XML parts
|
||||
/// have been scanned so Warnings cannot crowd out measured Errors at the cap.
|
||||
///
|
||||
/// Warning grade precedence for measured fractional geometry:
|
||||
/// 1. Strict part profile OR definitively unselected enclosing `mc:AlternateContent` branch
|
||||
/// -> `Warning` / `Observed` (`DmlWarnEvidence::ObservedContext`).
|
||||
/// 2. Unresolved part profile OR unresolved `AlternateContent` selection (only in a non-Strict
|
||||
/// part with no definitively unselected enclosing branch)
|
||||
/// -> `Warning` / `MsDocumented` (`DmlWarnEvidence::Unmeasured`).
|
||||
fn check_dml_coordinates(state: &State, id: &ElemId, attrs: &[Attribute], part: &str, out: &mut PartScan, acc: &mut Acc) {
|
||||
observation_contract! {
|
||||
rules: "DML-COORDINATE";
|
||||
collections: "field.dml_coordinate_warnings*2,field.frames*1";
|
||||
scope: "source-local custom geometry attribute values";
|
||||
loss: "source unavailable or malformed; XML event/depth budget";
|
||||
fallback: "measured decimal-fraction spellings ([ ]*-?[0-9]+\\.[0-9]+[ ]* raw XML source) in a:arcTo wR/hR (Transitional or Strict DrawingML namespace) receive Error with Observed evidence only when the part profile is Transitional and every enclosing AlternateContent is Supported-selected (bare drawing, Supported Choice, or choice-less Fallback); Warning grade precedence: Strict parts and definitively unselected enclosing AlternateContent branches report Warning with Observed evidence, while unresolved part profiles and unresolved AlternateContent selections report Warning with MsDocumented evidence only in a non-Strict part with no definitively unselected enclosing branch; other invalid schema-typed custom geometry attributes and unmeasured or unresolvable lexical classes receive Warning with MsDocumented evidence; measured Errors are emitted ahead of Warnings; report invalid values in the scanned prefix";
|
||||
package_loss: "independent";
|
||||
}
|
||||
if !id.a() || !in_custom_geometry(state, id) {
|
||||
return;
|
||||
}
|
||||
if id.local == "custGeom" {
|
||||
acc.ran_dml_coordinate();
|
||||
}
|
||||
let is_path = id.local == "path"
|
||||
&& state.frames.iter().rev().find(|frame| !frame.alt && frame.alt_branch_prev.is_none()).is_some_and(|frame| frame.is_path_lst);
|
||||
for &(attr_name, kind) in dml_coord_spec(&id.local, is_path) {
|
||||
let Some((raw_source, normalized)) = dml_attr_values(attrs, attr_name.as_bytes()) else { continue };
|
||||
let warning_evidence = match classify_dml_coord(raw_source, normalized.as_deref(), kind) {
|
||||
CoordLiteral::Valid => continue,
|
||||
CoordLiteral::MeasuredDecimalFraction if is_observed_decimal_attr(&id.local, attr_name) => {
|
||||
match (state.part_profile, dml_branch_selection(state)) {
|
||||
(PartProfile::Transitional, DmlBranchSelection::Selected) => {
|
||||
acc.add_dml_coordinate_error(
|
||||
part.to_string(),
|
||||
format!("a:{} attribute {attr_name} has invalid coordinate or angle value {raw_source:?} in {part}", id.local),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
(PartProfile::Strict, _) | (_, DmlBranchSelection::Unselected) => DmlWarnEvidence::ObservedContext,
|
||||
(PartProfile::Transitional, DmlBranchSelection::Unresolved)
|
||||
| (PartProfile::Unresolved, DmlBranchSelection::Selected | DmlBranchSelection::Unresolved) => DmlWarnEvidence::Unmeasured,
|
||||
}
|
||||
}
|
||||
CoordLiteral::MeasuredDecimalFraction | CoordLiteral::OtherInvalid => DmlWarnEvidence::Unmeasured,
|
||||
};
|
||||
// Save one extra Warning past the cap to exercise the accumulator's truncation path
|
||||
// while emitting measured Errors first across all XML parts.
|
||||
if out.dml_coordinate_warnings.len() <= acc.limits.findings_per_rule {
|
||||
out.dml_coordinate_warnings.push((
|
||||
warning_evidence,
|
||||
format!("a:{} attribute {attr_name} has invalid coordinate or angle value {raw_source:?} in {part}", id.local),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The AlternateContent ancestry of one `w14:paraId` occurrence: one
|
||||
/// `(block, branch instance)` pair per enclosing `mc:AlternateContent`
|
||||
/// block, outermost first. Branch instance 0 means the occurrence is
|
||||
@@ -2072,6 +2519,21 @@ struct AltCtx {
|
||||
/// no branch element, otherwise the instance number assigned to
|
||||
/// the enclosing `mc:Choice` / `mc:Fallback` element.
|
||||
branch: u32,
|
||||
/// Whether the opening element resolved to the actual Markup Compatibility namespace (`NS_MC`).
|
||||
is_mc: bool,
|
||||
/// Whether this block has already seen any direct `Choice` child (`mc:Choice` or unresolved).
|
||||
/// `mc:Fallback` is selected only when no `Choice` precedes it.
|
||||
choice_seen: bool,
|
||||
/// Whether this `mc:AlternateContent` block has already seen its established selected branch
|
||||
/// (the first `Supported` `mc:Choice`, or `mc:Fallback` when no `Choice` is present).
|
||||
selected_seen: bool,
|
||||
/// Whether branch selection for this block is uncertain (the `AlternateContent` element's
|
||||
/// namespace could not be resolved, an earlier direct `Choice`/`Fallback` before selection
|
||||
/// was unresolved, a `Choice` before selection evaluated to [`ChoiceState::Unresolved`], or
|
||||
/// `mc:Fallback` appeared behind a non-selected `Choice`).
|
||||
selection_unresolved: bool,
|
||||
/// Whether the scanner is currently inside this block's established selected branch.
|
||||
in_selected_branch: bool,
|
||||
}
|
||||
|
||||
/// The `w14:paraId` / `w14:textId` family (MS-DOCX §2.6.2.3 and
|
||||
@@ -2155,10 +2617,10 @@ fn check_para_ids(state: &mut State, id: &ElemId, attrs: &[Attribute], res: &Nam
|
||||
/// are different alternatives — and returns the block's previous
|
||||
/// branch value, which the caller restores when the branch element
|
||||
/// closes (its frame carries it; an empty element restores at once).
|
||||
fn assign_alt_branch(state: &mut State, id: &ElemId) -> Option<u32> {
|
||||
fn assign_alt_branch(state: &mut State, id: &ElemId, attrs: &[Attribute], res: &NamespaceResolver, own_decls: &[String]) -> Option<(u32, bool)> {
|
||||
observation_contract! {
|
||||
rules: "-";
|
||||
collections: "field.alt_stack*1,field.frames*1";
|
||||
collections: "field.alt_stack*1,field.declared*1,field.frames*1";
|
||||
scope: "source-local bounded extraction; no implicit document owner";
|
||||
loss: "source unavailable or malformed; XML event/depth budget; category allocation cap";
|
||||
fallback: "retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set";
|
||||
@@ -2175,15 +2637,54 @@ fn assign_alt_branch(state: &mut State, id: &ElemId) -> Option<u32> {
|
||||
return None;
|
||||
}
|
||||
let ctx = state.alt_stack.last_mut()?;
|
||||
let prev = ctx.branch;
|
||||
let prev = (ctx.branch, ctx.in_selected_branch);
|
||||
state.alt_branch_seq += 1;
|
||||
ctx.branch = state.alt_branch_seq | if unresolved { BRANCH_UNKNOWN } else { 0 };
|
||||
if id.local == "Choice" {
|
||||
ctx.choice_seen = true;
|
||||
}
|
||||
if ctx.selection_unresolved {
|
||||
ctx.in_selected_branch = false;
|
||||
} else if ctx.is_mc && id.ns == Some(NS_MC.as_bytes()) {
|
||||
match id.local.as_str() {
|
||||
"Choice" if !ctx.selected_seen => match choice_requires_state(attrs, res, &state.declared, own_decls) {
|
||||
ChoiceState::Supported => {
|
||||
ctx.selected_seen = true;
|
||||
ctx.in_selected_branch = true;
|
||||
}
|
||||
ChoiceState::Unsupported => {
|
||||
ctx.in_selected_branch = false;
|
||||
}
|
||||
ChoiceState::Unresolved => {
|
||||
ctx.selection_unresolved = true;
|
||||
ctx.in_selected_branch = false;
|
||||
}
|
||||
},
|
||||
"Fallback" if !ctx.selected_seen => {
|
||||
if !ctx.choice_seen {
|
||||
ctx.selected_seen = true;
|
||||
ctx.in_selected_branch = true;
|
||||
} else {
|
||||
ctx.selection_unresolved = true;
|
||||
ctx.in_selected_branch = false;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
ctx.in_selected_branch = false;
|
||||
}
|
||||
}
|
||||
} else if unresolved {
|
||||
if !ctx.selected_seen {
|
||||
ctx.selection_unresolved = true;
|
||||
}
|
||||
ctx.in_selected_branch = false;
|
||||
}
|
||||
Some(prev)
|
||||
}
|
||||
|
||||
/// Restore the innermost block's branch value saved by
|
||||
/// `assign_alt_branch` when its branch element closes.
|
||||
fn restore_branch(state: &mut State, prev: Option<u32>) {
|
||||
fn restore_branch(state: &mut State, prev: Option<(u32, bool)>) {
|
||||
observation_contract! {
|
||||
rules: "-";
|
||||
collections: "field.alt_stack*1";
|
||||
@@ -2193,10 +2694,11 @@ fn restore_branch(state: &mut State, prev: Option<u32>) {
|
||||
package_loss: "independent";
|
||||
}
|
||||
|
||||
if let Some(prev) = prev
|
||||
if let Some((prev_branch, prev_selected)) = prev
|
||||
&& let Some(ctx) = state.alt_stack.last_mut()
|
||||
{
|
||||
ctx.branch = prev;
|
||||
ctx.branch = prev_branch;
|
||||
ctx.in_selected_branch = prev_selected;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user