mirror of
https://github.com/storytold/wordcraft.git
synced 2026-12-04 22:49:54 +00:00
Compare commits
200
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5beded22ad | ||
|
|
0cdd7949b1 | ||
|
|
0c1cf9e1e7 | ||
|
|
8a0155c59d | ||
|
|
85547002bb | ||
|
|
16109fa4bd | ||
|
|
b087513b59 | ||
|
|
0c7546f414 | ||
|
|
18f78039b9 | ||
|
|
07e0f271a4 | ||
|
|
d927d3c03c | ||
|
|
1b4d732f49 | ||
|
|
576755c08b | ||
|
|
ef054ca8c4 | ||
|
|
cfefd93f74 | ||
|
|
b389b12aa8 | ||
|
|
1b29aecc05 | ||
|
|
44cee9a5e3 | ||
|
|
8b0e06339b | ||
|
|
3cef779801 | ||
|
|
2d9790c374 | ||
|
|
6c37ffb1eb | ||
|
|
ca6a949a24 | ||
|
|
ba775deed9 | ||
|
|
17da903053 | ||
|
|
e253cac545 | ||
|
|
08d6f87dca | ||
|
|
401eabf292 | ||
|
|
0b0011e053 | ||
|
|
2573d54c4d | ||
|
|
752b78cd18 | ||
|
|
20f91f5bdf | ||
|
|
69f3ccbba8 | ||
|
|
29c5c19d67 | ||
|
|
34c6eeff8d | ||
|
|
77d00e0ee1 | ||
|
|
9cda9db296 | ||
|
|
500e150132 | ||
|
|
8baa46395f | ||
|
|
416db1b645 | ||
|
|
2f08031e75 | ||
|
|
e9f07d8837 | ||
|
|
3c79eca060 | ||
|
|
a1aa614bf1 | ||
|
|
71abe1c4c9 | ||
|
|
5ca9917471 | ||
|
|
37c8061088 | ||
|
|
d53ba37903 | ||
|
|
5073f8e7c2 | ||
|
|
0df3151f01 | ||
|
|
92eb57fd08 | ||
|
|
f1fb526f3f | ||
|
|
b4ecd20dba | ||
|
|
161c127926 | ||
|
|
de328db448 | ||
|
|
e3d1ee90c3 | ||
|
|
3138201a56 | ||
|
|
0600244e11 | ||
|
|
3b0257ff33 | ||
|
|
1591f99189 | ||
|
|
1ffd5f8d4a | ||
|
|
3b2ce5cb83 | ||
|
|
e2f2fe1f09 | ||
|
|
cfae52c97d | ||
|
|
0e47c8613c | ||
|
|
d7986fc26c | ||
|
|
1812618f10 | ||
|
|
e7172b9a8a | ||
|
|
b211131dec | ||
|
|
bbc587e2a6 | ||
|
|
f1ad785403 | ||
|
|
e3653ada4b | ||
|
|
167e479382 | ||
|
|
81abc0d81b | ||
|
|
eb8a7e311c | ||
|
|
040150d486 | ||
|
|
b7e49e84b3 | ||
|
|
168e39e5a4 | ||
|
|
0fe7ede07e | ||
|
|
5b24de412e | ||
|
|
5dad217316 | ||
|
|
2ad2694407 | ||
|
|
4622fef6ce | ||
|
|
061985fb6b | ||
|
|
b8334518b3 | ||
|
|
2b612d51fa | ||
|
|
472399cb33 | ||
|
|
25b86d2a1d | ||
|
|
dd3dedddae | ||
|
|
04e04e8119 | ||
|
|
e3749fc2d0 | ||
|
|
020eba42ff | ||
|
|
1a339aebb4 | ||
|
|
5d46607ec4 | ||
|
|
456aa68148 | ||
|
|
83ada40e06 | ||
|
|
b36fa16a15 | ||
|
|
04cd0ca6fd | ||
|
|
05cbdfd9ff | ||
|
|
e66ba81d3f | ||
|
|
8bf97aa275 | ||
|
|
a2960ce55d | ||
|
|
48b211621d | ||
|
|
c39e70fc85 | ||
|
|
0a1d913690 | ||
|
|
c55e7a83e6 | ||
|
|
129b6ad2f9 | ||
|
|
fc3146206a | ||
|
|
b682a1fd06 | ||
|
|
6bdd6769d1 | ||
|
|
6a6dfd7f58 | ||
|
|
4c600213dc | ||
|
|
af4cacc45f | ||
|
|
8d75a12b48 | ||
|
|
ba179cb3d1 | ||
|
|
30458a8e0b | ||
|
|
6d27b1a4a1 | ||
|
|
faf55fad76 | ||
|
|
9d5789162f | ||
|
|
cdef8012e9 | ||
|
|
8bca61f529 | ||
|
|
4dd74c36d5 | ||
|
|
83381d344a | ||
|
|
46050e5c4b | ||
|
|
6d2f0d7759 | ||
|
|
4073aa4274 | ||
|
|
95388461a7 | ||
|
|
53b22e61f2 | ||
|
|
f641b83a2f | ||
|
|
8544a588c1 | ||
|
|
9964e4e88c | ||
|
|
49ef461bc3 | ||
|
|
2bfc68964b | ||
|
|
ddb8fa164b | ||
|
|
8d9a614e15 | ||
|
|
0e4d52a5aa | ||
|
|
d25db5fa8f | ||
|
|
9abd324244 | ||
|
|
77dc3e75b9 | ||
|
|
8082743bb8 | ||
|
|
4f4827a7c0 | ||
|
|
54cf516adf | ||
|
|
3db40dabac | ||
|
|
4ea1fe935a | ||
|
|
9a2d6902f4 | ||
|
|
8a2e47f8c3 | ||
|
|
c4cd11c5ff | ||
|
|
3a7a3b4b95 | ||
|
|
1ec83a1a2f | ||
|
|
a6d1534889 | ||
|
|
08eb9ccbb2 | ||
|
|
9386f754f4 | ||
|
|
f670da8602 | ||
|
|
f1e8793b7a | ||
|
|
5c41ef2f08 | ||
|
|
1955eea91d | ||
|
|
a937df1bb7 | ||
|
|
b6488c5773 | ||
|
|
664980b32b | ||
|
|
349556de8a | ||
|
|
869160692f | ||
|
|
13dc60f05c | ||
|
|
2813a0961d | ||
|
|
ddeab752da | ||
|
|
81ed00867e | ||
|
|
473942d205 | ||
|
|
4d1b530601 | ||
|
|
64960989a1 | ||
|
|
16160b1e4b | ||
|
|
e414882ffe | ||
|
|
2c6d291c9b | ||
|
|
d750887f3c | ||
|
|
859e03246f | ||
|
|
0c7ea7278c | ||
|
|
f674177095 | ||
|
|
cb0aeadd2f | ||
|
|
4e79e67534 | ||
|
|
0f83ea9cf4 | ||
|
|
d789f82465 | ||
|
|
6da8a86a41 | ||
|
|
8619e257a7 | ||
|
|
0859a447b6 | ||
|
|
df07115145 | ||
|
|
a761f276d5 | ||
|
|
104fa6133d | ||
|
|
b687f1cd6f | ||
|
|
50041c808c | ||
|
|
c0c42caf95 | ||
|
|
8f8bec4ad7 | ||
|
|
3b73a84082 | ||
|
|
1603a5f34f | ||
|
|
d5239891f6 | ||
|
|
9c7ec843b6 | ||
|
|
777fedb14a | ||
|
|
02de1488cb | ||
|
|
9c05751014 | ||
|
|
6d51d93bb6 | ||
|
|
fe69231544 | ||
|
|
dd20b23d4d | ||
|
|
ab35bfa946 |
Generated
+133
-145
File diff suppressed because it is too large
Load Diff
+55
-55
@@ -13,7 +13,7 @@ run_slots = 3
|
||||
test_threads = 4
|
||||
|
||||
[workspace.package]
|
||||
version = "0.18.1"
|
||||
version = "0.20.0"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
@@ -37,22 +37,22 @@ wordcraft-pdf = { path = "crates/pdf" }
|
||||
# reads the ca-valencia pack), #589 (French elision suggestions first), #497 (flag-based
|
||||
# compounding), #496 (review follow-ups, en-AU) and the merged #482–#490/#495 stack; the font
|
||||
# store's `language-pack` kind is #486 (CP4.1).
|
||||
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "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" }
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ const POLL_MS: i32 = 16;
|
||||
pub fn install(ctx: egui::Context) -> Receiver<ControlRequest> {
|
||||
let (queue, requests) = channel::<ControlRequest>();
|
||||
let request: Request = Rc::new(move |method, params| {
|
||||
let params = super::page_params::control_params(&method, params);
|
||||
let (control, reply) = ControlRequest::new(method, params);
|
||||
if queue.send(control).is_err() {
|
||||
return Box::pin(async { json!({"ok": false, "error": "the app is not running"}) });
|
||||
|
||||
@@ -23,6 +23,8 @@ mod prefs;
|
||||
mod api;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod host;
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
mod page_params;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod web;
|
||||
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
use serde_json::Value;
|
||||
|
||||
pub(super) fn control_params(method: &str, mut params: Value) -> Value {
|
||||
// The page helper asks for inline data. A screenshot without a path already returns it.
|
||||
if method == "ui.screenshot"
|
||||
&& let Some(fields) = params.as_object_mut()
|
||||
&& !fields.contains_key("path")
|
||||
&& fields.get("data") == Some(&Value::Bool(true))
|
||||
{
|
||||
fields.remove("data");
|
||||
}
|
||||
params
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use craft::automation::screenshot::ScreenshotParams;
|
||||
use serde_json::json;
|
||||
|
||||
use super::control_params;
|
||||
|
||||
#[test]
|
||||
fn page_helper_requests_the_same_capture_as_a_direct_request() {
|
||||
for (helper, direct) in
|
||||
[(json!({"data": true}), json!({})), (json!({"data": true, "region": [10, 20, 100, 200]}), json!({"region": [10, 20, 100, 200]}))]
|
||||
{
|
||||
let params = control_params("ui.screenshot", helper);
|
||||
assert_eq!(params, direct);
|
||||
assert!(ScreenshotParams::from_params(¶ms).is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_helper_keeps_screenshot_validation() {
|
||||
for (input, expected) in [
|
||||
(json!({"data": true, "region": [100, 200, 10, 20]}), json!({"region": [100, 200, 10, 20]})),
|
||||
(json!({"data": true, "viewport": "other"}), json!({"viewport": "other"})),
|
||||
(json!({"data": true, "path": "capture.png"}), json!({"data": true, "path": "capture.png"})),
|
||||
(json!({"data": true, "path": null}), json!({"data": true, "path": null})),
|
||||
(json!({"data": false}), json!({"data": false})),
|
||||
(json!({"data": "true"}), json!({"data": "true"})),
|
||||
] {
|
||||
let params = control_params("ui.screenshot", input);
|
||||
assert_eq!(params, expected);
|
||||
assert!(ScreenshotParams::from_params(¶ms).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_requests_keep_their_parameters() {
|
||||
for (method, params) in [("ui.screenshot", json!({"path": "capture.png"})), ("file.new", json!({"data": true}))] {
|
||||
assert_eq!(control_params(method, params.clone()), params);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ use std::net::TcpListener;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::mpsc::Receiver;
|
||||
|
||||
use craft::automation::AutomationError;
|
||||
use craft::automation::args::ControlOptions;
|
||||
use craft::automation::control::ControlRequest;
|
||||
use craft::automation::server::{Listening, serve};
|
||||
@@ -38,6 +39,22 @@ fn remove(path: Option<&Path>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Why starting the control server did not succeed.
|
||||
enum StartError {
|
||||
/// Windows external-tool timeout while creating or checking the owner-only token file.
|
||||
TokenTimeout(String),
|
||||
/// Any other bind, token, or accept-thread error.
|
||||
Other(String),
|
||||
}
|
||||
|
||||
impl StartError {
|
||||
fn message(&self) -> &str {
|
||||
match self {
|
||||
Self::TokenTimeout(msg) | Self::Other(msg) => msg,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Bind `127.0.0.1:port`, settle the token and serve. `None` when the port cannot be bound or
|
||||
/// the token cannot be set up (the control channel is off); a taken port leaves no token file.
|
||||
///
|
||||
@@ -45,35 +62,49 @@ fn remove(path: Option<&Path>) {
|
||||
/// `port` in `settings`; a file left by a run that did not exit cleanly is replaced. Without a
|
||||
/// settings folder a fresh token is generated and reported by the log.
|
||||
pub fn start(options: &ControlOptions, port: u16, host: WindowHost, settings: Option<&Path>) -> Option<(Receiver<ControlRequest>, Control)> {
|
||||
let listener = match TcpListener::bind(("127.0.0.1", port)) {
|
||||
Ok(l) => l,
|
||||
Err(e) => {
|
||||
log::error!("control server failed to bind 127.0.0.1:{port}: {e}");
|
||||
return None;
|
||||
match start_with(options, port, host, settings, ControlOptions::server_token) {
|
||||
Ok(started) => Some(started),
|
||||
Err(err) => {
|
||||
log::error!("{}", err.message());
|
||||
None
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
fn start_with(
|
||||
options: &ControlOptions,
|
||||
port: u16,
|
||||
host: WindowHost,
|
||||
settings: Option<&Path>,
|
||||
token_for: impl FnOnce(&ControlOptions) -> Result<String, AutomationError>,
|
||||
) -> Result<(Receiver<ControlRequest>, Control), StartError> {
|
||||
let listener =
|
||||
TcpListener::bind(("127.0.0.1", port)).map_err(|e| StartError::Other(format!("control server failed to bind 127.0.0.1:{port}: {e}")))?;
|
||||
let created = settings.filter(|_| options.token.is_none() && options.token_file.is_none()).map(|dir| wordcraft_control_key::key_path(dir, port));
|
||||
// The port was free, so no other run owns a file left here.
|
||||
remove(created.as_deref());
|
||||
let effective = ControlOptions { token_file: created.clone().or_else(|| options.token_file.clone()), ..options.clone() };
|
||||
let token = match effective.server_token() {
|
||||
let token = match token_for(&effective) {
|
||||
Ok(t) => t,
|
||||
Err(e) => {
|
||||
remove(created.as_deref());
|
||||
log::error!("control server off: {e}");
|
||||
return None;
|
||||
let msg = format!("control server off: {e}");
|
||||
return Err(if matches!(&e, AutomationError::Io(text) if text.contains("did not finish within ")) {
|
||||
StartError::TokenTimeout(msg)
|
||||
} else {
|
||||
StartError::Other(msg)
|
||||
});
|
||||
}
|
||||
};
|
||||
let notice = effective.token_notice(&token);
|
||||
match serve(listener, token, host) {
|
||||
Ok((rx, listening)) => {
|
||||
log::info!("control server listening on {}, {notice}", listening.addr);
|
||||
Some((rx, Control { listening, created }))
|
||||
Ok((rx, Control { listening, created }))
|
||||
}
|
||||
Err(e) => {
|
||||
remove(created.as_deref());
|
||||
log::error!("control server off: cannot start the accept thread ({e})");
|
||||
None
|
||||
Err(StartError::Other(format!("control server off: cannot start the accept thread ({e})")))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -87,6 +118,41 @@ mod tests {
|
||||
WindowHost::of(&egui::Context::default())
|
||||
}
|
||||
|
||||
/// Attempts for `start_with` when Windows `owner_only` hits its 10 s external-tool limit on
|
||||
/// a busy CI runner (#8556). Non-timeout failures stop on the first attempt.
|
||||
const TOKEN_TIMEOUT_ATTEMPTS: usize = 3;
|
||||
|
||||
fn try_start_retrying_token_timeout(
|
||||
options: &ControlOptions,
|
||||
port: u16,
|
||||
host: WindowHost,
|
||||
settings: Option<&Path>,
|
||||
mut token_for: impl FnMut(&ControlOptions) -> Result<String, AutomationError>,
|
||||
) -> Result<(Receiver<ControlRequest>, Control), (usize, StartError)> {
|
||||
let mut attempt = 1;
|
||||
loop {
|
||||
match start_with(options, port, host.clone(), settings, &mut token_for) {
|
||||
Ok(started) => return Ok(started),
|
||||
Err(StartError::TokenTimeout(msg)) if attempt < TOKEN_TIMEOUT_ATTEMPTS => {
|
||||
log::warn!("retrying control server start after Windows token-file timeout ({attempt}/{TOKEN_TIMEOUT_ATTEMPTS}): {msg}");
|
||||
attempt += 1;
|
||||
}
|
||||
Err(err) => return Err((attempt, err)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn start_retrying_token_timeout(
|
||||
options: &ControlOptions,
|
||||
port: u16,
|
||||
host: WindowHost,
|
||||
settings: Option<&Path>,
|
||||
token_for: impl FnMut(&ControlOptions) -> Result<String, AutomationError>,
|
||||
) -> (Receiver<ControlRequest>, Control) {
|
||||
try_start_retrying_token_timeout(options, port, host, settings, token_for)
|
||||
.unwrap_or_else(|(attempt, err)| panic!("control server start failed on attempt {attempt}: {}", err.message()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_token_file_is_written_after_the_bind_and_removed_on_exit() {
|
||||
let dir = std::env::temp_dir().join(format!("wordcraft-control-life-{}", std::process::id()));
|
||||
@@ -101,7 +167,7 @@ mod tests {
|
||||
drop(taken);
|
||||
|
||||
// Bound: the default file holds the token that opens the port.
|
||||
let (_rx, control) = start(&options, 0, host(), Some(&dir)).unwrap();
|
||||
let (_rx, control) = start_retrying_token_timeout(&options, 0, host(), Some(&dir), ControlOptions::server_token);
|
||||
let path = control.created.clone().unwrap();
|
||||
assert_eq!(path, wordcraft_control_key::key_path(&dir, 0));
|
||||
let token = std::fs::read_to_string(&path).unwrap();
|
||||
@@ -117,13 +183,61 @@ mod tests {
|
||||
// A token file the user supplied stays.
|
||||
let supplied = dir.join("supplied-token");
|
||||
let options = ControlOptions { token_file: Some(supplied.clone()), ..ControlOptions::default() };
|
||||
let (_rx, control) = start(&options, 0, host(), Some(&dir)).unwrap();
|
||||
let (_rx, control) = start_retrying_token_timeout(&options, 0, host(), Some(&dir), ControlOptions::server_token);
|
||||
assert!(control.created.is_none());
|
||||
control.shut_down();
|
||||
assert!(supplied.exists());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_transient_token_file_timeout_retries_while_other_errors_stop() {
|
||||
let dir = std::env::temp_dir().join(format!("wordcraft-control-retry-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let options = ControlOptions::default();
|
||||
|
||||
// A Windows `owner_only` external-tool timeout retries and recovers on a later attempt.
|
||||
let mut timeout_then_ok = 0usize;
|
||||
let (_rx, control) = start_retrying_token_timeout(&options, 0, host(), Some(&dir), |effective| {
|
||||
timeout_then_ok += 1;
|
||||
if timeout_then_ok == 1 {
|
||||
let path = effective.token_file.as_ref().unwrap();
|
||||
Err(AutomationError::Io(format!(
|
||||
"{}: cannot create the control token file for its owner only: powershell.exe did not finish within 10 s and was ended",
|
||||
path.display()
|
||||
)))
|
||||
} else {
|
||||
Ok(TOKEN.to_string())
|
||||
}
|
||||
});
|
||||
assert_eq!(timeout_then_ok, 2);
|
||||
control.shut_down();
|
||||
|
||||
// Repeated timeouts stop after `TOKEN_TIMEOUT_ATTEMPTS` instead of looping forever.
|
||||
let mut exhausted = 0usize;
|
||||
let Err((attempt, err)) = try_start_retrying_token_timeout(&options, 0, host(), Some(&dir), |_| {
|
||||
exhausted += 1;
|
||||
Err(AutomationError::Io("powershell.exe did not finish within 10 s and was ended".into()))
|
||||
}) else {
|
||||
panic!("exhausted timeouts must fail");
|
||||
};
|
||||
assert_eq!((attempt, exhausted), (TOKEN_TIMEOUT_ATTEMPTS, TOKEN_TIMEOUT_ATTEMPTS));
|
||||
assert!(matches!(err, StartError::TokenTimeout(_)));
|
||||
|
||||
// Non-timeout failures stop on the first attempt.
|
||||
let mut other = 0usize;
|
||||
let Err((attempt, err)) = try_start_retrying_token_timeout(&options, 0, host(), Some(&dir), |_| {
|
||||
other += 1;
|
||||
Err(AutomationError::Io("permission denied".into()))
|
||||
}) else {
|
||||
panic!("non-timeout error must fail");
|
||||
};
|
||||
assert_eq!((attempt, other), (1, 1));
|
||||
assert!(matches!(err, StartError::Other(msg) if msg.contains("permission denied")));
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
|
||||
|
||||
fn boot() -> (u16, Receiver<ControlRequest>, Control) {
|
||||
|
||||
+195
-134
@@ -152,6 +152,21 @@ impl eframe::App for App {
|
||||
}
|
||||
}
|
||||
|
||||
/// Files dropped on a document window. eframe hands `raw_input_hook` only the root's and deferred
|
||||
/// viewports' input, and document windows are immediate viewports (every one under the windowless
|
||||
/// root), so their drops come through this hook. It runs first and takes the batch, so nothing reads
|
||||
/// it twice.
|
||||
struct ChildDrops(IntakeSender);
|
||||
|
||||
impl eframe::ViewportHooks for ChildDrops {
|
||||
fn raw_input(&self, _ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
if raw.viewport_id != egui::ViewportId::ROOT && !raw.dropped_files.is_empty() {
|
||||
self.0.dropped(dropped_files(raw));
|
||||
raw.dropped_files.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The files dropped in this frame's input, as the intake carries them: a file with a path by its
|
||||
/// path, a file without one by its bytes.
|
||||
fn dropped_files(raw: &egui::RawInput) -> Vec<DroppedFile> {
|
||||
@@ -463,6 +478,46 @@ fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
|
||||
Some(launch_profile::passthrough_args(early.passthrough_args, had_separator))
|
||||
}
|
||||
|
||||
/// Runs the app with the windowless root when `windowless` is set, and with the visible root when it is not. eframe
|
||||
/// refuses a windowless root on a session that cannot run it before it calls the creator, which then stays in its
|
||||
/// cell for a retry with the visible root: the app always starts.
|
||||
fn run_with_visible_root_fallback(
|
||||
creator: eframe::AppCreator<'static>,
|
||||
windowless: Arc<std::sync::atomic::AtomicBool>,
|
||||
mut options: eframe::NativeOptions,
|
||||
) -> eframe::Result {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
let creator = std::rc::Rc::new(std::cell::RefCell::new(Some(creator)));
|
||||
let name = wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity());
|
||||
let run = |options: eframe::NativeOptions| {
|
||||
let creator = creator.clone();
|
||||
eframe::run_native(
|
||||
name,
|
||||
options,
|
||||
Box::new(move |cc| match creator.borrow_mut().take() {
|
||||
Some(create) => create(cc),
|
||||
None => Err("the app was already created".into()),
|
||||
}),
|
||||
)
|
||||
};
|
||||
let on = windowless.load(Relaxed);
|
||||
// The clone keeps no event-loop hook, which only the X11 start sets and that start is windowed.
|
||||
let mut visible_root = on.then(|| options.clone());
|
||||
if on {
|
||||
options.root_viewport_mode = eframe::RootViewportMode::Windowless;
|
||||
}
|
||||
let result = run(options);
|
||||
if let Err(eframe::Error::UnsupportedConfiguration(reason)) = &result
|
||||
&& let Some(options) = visible_root.take()
|
||||
&& creator.borrow().is_some()
|
||||
{
|
||||
log::warn!("windowless root unavailable ({reason}); starting with a visible root window");
|
||||
windowless.store(false, Relaxed);
|
||||
return run(options);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Parses the command line, installs logging and the panic hook, restores preferences and window
|
||||
/// geometry, opens requested documents or the Start screen, starts the control server when
|
||||
/// asked, and runs the eframe event loop.
|
||||
@@ -676,6 +731,7 @@ fn main() -> eframe::Result {
|
||||
// Registered before the event loop starts, so it catches the Finder event that launched us as
|
||||
// well as later ones. Lives until the event loop returns.
|
||||
let drops = intake.sender();
|
||||
options.viewport_hooks = Some(Arc::new(ChildDrops(drops.clone())));
|
||||
#[cfg(target_os = "macos")]
|
||||
let _apple_events = craft::platform::open::apple_events::install(sender);
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
@@ -705,147 +761,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.
|
||||
|
||||
@@ -6,13 +6,22 @@ use wordcraft_ui_egui::{WordApp, i18n};
|
||||
|
||||
const APP_NAME: &str = "WordCraft";
|
||||
const ABOUT: &str = "About WordCraft";
|
||||
const QUIT: &str = "Quit WordCraft";
|
||||
|
||||
/// The application menu, with `tr` the translation of an English string.
|
||||
pub(super) fn layout(tr: &dyn Fn(&'static str) -> String) -> Layout {
|
||||
let about = Item::new(CommandRef::with_params("ui.dialog", json!({"name": "about"})), tr(ABOUT)).role(ItemRole::About);
|
||||
let bar = MenuBar::new(vec![Menu::new(APP_NAME, vec![about.into()]).role(MenuRole::App)]);
|
||||
// Without its own Quit `mac_layout` adds one whose click only closes the root window: it must ask about every document.
|
||||
let quit = Item::new(CommandRef::new("ui.quit"), tr(QUIT)).role(ItemRole::Quit);
|
||||
let bar = MenuBar::new(vec![Menu::new(APP_NAME, vec![about.into(), quit.into()]).role(MenuRole::App)]);
|
||||
// `mac_layout` words About as the template; WordCraft's catalogs translate the whole label.
|
||||
let label = |s: &'static str| tr(if s == "About {app}" { ABOUT } else { s });
|
||||
let label = |s: &'static str| {
|
||||
tr(match s {
|
||||
"About {app}" => ABOUT,
|
||||
"Quit {app}" => QUIT,
|
||||
s => s,
|
||||
})
|
||||
};
|
||||
let mut layout = mac_layout(&bar, &LayoutOptions::new(APP_NAME).label(&label));
|
||||
// WordCraft's document menus live in its ribbon; keep only the application menu.
|
||||
layout.bar.menus.retain(|menu| menu.role == MenuRole::App);
|
||||
@@ -61,4 +70,12 @@ mod tests {
|
||||
let about = layout.bar.items().into_iter().find(|item| item.role == Some(ItemRole::About)).unwrap();
|
||||
assert_eq!(about.label, "Über WordCraft");
|
||||
}
|
||||
|
||||
/// ⌘Q and the menu's Quit run `ui.quit`, which asks about unsaved documents; craft's built-in Quit only closes the root window (#8709).
|
||||
#[test]
|
||||
fn quit_runs_the_command_that_asks_about_documents() {
|
||||
let layout = layout(&|s| s.to_owned());
|
||||
let quit = layout.bar.items().into_iter().find(|item| item.role == Some(ItemRole::Quit)).unwrap();
|
||||
assert_eq!(quit.command.id, "ui.quit");
|
||||
}
|
||||
}
|
||||
|
||||
+24
-1
@@ -23,7 +23,8 @@ mod para_props;
|
||||
mod table_props;
|
||||
|
||||
pub use char_props::{
|
||||
CharProps, CombineBrackets, DEFAULT_FONT_SIZE, EastAsianLayout, EmphasisMark, Highlight, Ligatures, NumChange, PropChange, Underline, VertAlign,
|
||||
CharProps, CombineBrackets, DEFAULT_FONT_SIZE, EastAsianLayout, EmphasisMark, Highlight, Ligatures, NumChange, PropChange, ThemeFont, Underline,
|
||||
VertAlign,
|
||||
};
|
||||
pub use color::{Rgb, TextColor};
|
||||
pub use para_props::{
|
||||
@@ -200,4 +201,26 @@ mod tests {
|
||||
assert_eq!(changed.sym_font.as_deref(), Some("Wingdings"));
|
||||
assert_eq!(p.cleared().sym_font.as_deref(), Some("Wingdings"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn named_east_asian_font_replaces_theme_slot_and_minus_round_trips() {
|
||||
let mut base = CharProps { font_ea: Some("Times New Roman".into()), font_ea_theme: Some(ThemeFont::MinorEastAsia), ..Default::default() };
|
||||
let named = CharProps { font_ea: Some("SimSun".into()), ..Default::default() };
|
||||
base.overlay(&named);
|
||||
assert_eq!(base.font_ea.as_deref(), Some("SimSun"));
|
||||
assert_eq!(base.font_ea_theme, None);
|
||||
|
||||
// Changing only `font_ea` while keeping `font_ea_theme` preserves the slot across minus/overlay.
|
||||
let themed_base = CharProps { font_ea: Some("SimSun".into()), font_ea_theme: Some(ThemeFont::MinorEastAsia), ..Default::default() };
|
||||
let run = CharProps { font_ea: Some("MS Mincho".into()), ..themed_base.clone() };
|
||||
let mut back = themed_base.clone();
|
||||
back.overlay(&run.clone().minus(&themed_base));
|
||||
assert_eq!(back, run);
|
||||
|
||||
// Clearing `font_ea_theme` while keeping the same `font_ea` preserves `font_ea` in the patch.
|
||||
let cleared_slot = CharProps { font_ea_theme: None, ..themed_base.clone() };
|
||||
let mut back_cleared = themed_base.clone();
|
||||
back_cleared.overlay(&cleared_slot.clone().minus(&themed_base));
|
||||
assert_eq!(back_cleared, cleared_slot);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -329,6 +329,10 @@ pub struct CharProps {
|
||||
/// inherit, then `font`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub font_ea: Option<String>,
|
||||
/// The theme font slot of the East Asian font (`w:rFonts/@w:eastAsiaTheme`: `minorEastAsia`,
|
||||
/// `majorEastAsia`…), taking precedence over `font_ea` when set.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub font_ea_theme: Option<ThemeFont>,
|
||||
/// Complex-script size, points (`w:szCs`). `None` leaves the inherited value unchanged.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub size_cs: Option<f32>,
|
||||
@@ -450,6 +454,62 @@ impl CombineBrackets {
|
||||
}
|
||||
}
|
||||
|
||||
/// A theme font slot in `w:rFonts` (`ST_Theme`, ECMA-376 §17.18.96).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ThemeFont {
|
||||
MajorEastAsia,
|
||||
MajorBidi,
|
||||
MajorAscii,
|
||||
MajorHAnsi,
|
||||
MinorEastAsia,
|
||||
MinorBidi,
|
||||
MinorAscii,
|
||||
MinorHAnsi,
|
||||
}
|
||||
|
||||
impl ThemeFont {
|
||||
const ALL: [ThemeFont; 8] = [
|
||||
ThemeFont::MajorEastAsia,
|
||||
ThemeFont::MajorBidi,
|
||||
ThemeFont::MajorAscii,
|
||||
ThemeFont::MajorHAnsi,
|
||||
ThemeFont::MinorEastAsia,
|
||||
ThemeFont::MinorBidi,
|
||||
ThemeFont::MinorAscii,
|
||||
ThemeFont::MinorHAnsi,
|
||||
];
|
||||
|
||||
/// The OOXML `ST_Theme` value.
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
ThemeFont::MajorEastAsia => "majorEastAsia",
|
||||
ThemeFont::MajorBidi => "majorBidi",
|
||||
ThemeFont::MajorAscii => "majorAscii",
|
||||
ThemeFont::MajorHAnsi => "majorHAnsi",
|
||||
ThemeFont::MinorEastAsia => "minorEastAsia",
|
||||
ThemeFont::MinorBidi => "minorBidi",
|
||||
ThemeFont::MinorAscii => "minorAscii",
|
||||
ThemeFont::MinorHAnsi => "minorHAnsi",
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse an OOXML `ST_Theme` value (`None` for any value outside the schema).
|
||||
pub fn parse(s: &str) -> Option<ThemeFont> {
|
||||
ThemeFont::ALL.into_iter().find(|t| t.as_str() == s)
|
||||
}
|
||||
|
||||
/// Whether this slot picks the theme's major (heading) font rather than minor (body).
|
||||
pub fn is_major(self) -> bool {
|
||||
matches!(self, ThemeFont::MajorEastAsia | ThemeFont::MajorBidi | ThemeFont::MajorAscii | ThemeFont::MajorHAnsi)
|
||||
}
|
||||
|
||||
/// Whether this is one of the Latin theme slots (`ascii` / `hAnsi`).
|
||||
pub fn is_latin(self) -> bool {
|
||||
matches!(self, ThemeFont::MajorAscii | ThemeFont::MajorHAnsi | ThemeFont::MinorAscii | ThemeFont::MinorHAnsi)
|
||||
}
|
||||
}
|
||||
|
||||
/// A tracked formatting change (ECMA-376 §17.13.5: `w:rPrChange`, `w:pPrChange`,
|
||||
/// `w:tblPrChange`, `w:trPrChange`, `w:tcPrChange`, `w:sectPrChange`): the properties as they
|
||||
/// were before the change, and the revision (author, date) that made it.
|
||||
@@ -509,7 +569,16 @@ impl CharProps {
|
||||
}
|
||||
|
||||
fn minus_script_style(&mut self, base: &CharProps) {
|
||||
drop_same_fields!(self, base; cs, font_cs, font_ea, size_cs, bold_cs, italic_cs, lang_bidi, lang_ea, east_asian_layout);
|
||||
// A theme slot stays while its named font does; a same font stays when its slot differs.
|
||||
let keep = self.font_ea_theme;
|
||||
let ea = self.font_ea.clone();
|
||||
drop_same_fields!(self, base; cs, font_cs, font_ea, font_ea_theme, size_cs, bold_cs, italic_cs, lang_bidi, lang_ea, east_asian_layout);
|
||||
if self.font_ea.is_none() && keep != base.font_ea_theme {
|
||||
self.font_ea = ea;
|
||||
}
|
||||
if self.font_ea.is_some() {
|
||||
self.font_ea_theme = keep;
|
||||
}
|
||||
}
|
||||
|
||||
fn minus_document_marks(&mut self, base: &CharProps) {
|
||||
@@ -540,7 +609,12 @@ impl CharProps {
|
||||
}
|
||||
|
||||
fn overlay_script_style(&mut self, patch: &CharProps) {
|
||||
overlay_fields!(self, patch; cs, font_cs, font_ea, size_cs, bold_cs, italic_cs, lang_bidi, lang_ea, east_asian_layout);
|
||||
// A named East Asian font without a theme slot replaces the slot too: Word gives the slot
|
||||
// precedence over the named font, so keeping it would hide the font just chosen.
|
||||
if patch.font_ea.is_some() && patch.font_ea_theme.is_none() {
|
||||
self.font_ea_theme = None;
|
||||
}
|
||||
overlay_fields!(self, patch; cs, font_cs, font_ea, font_ea_theme, size_cs, bold_cs, italic_cs, lang_bidi, lang_ea, east_asian_layout);
|
||||
}
|
||||
|
||||
fn overlay_document_marks(&mut self, patch: &CharProps) {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::props::{
|
||||
Align, Border, Borders, CharProps, Highlight, LineSpacing, NumRef, ParaProps, Rgb, TabAlign, TabStop, TextColor, Underline, VertAlign,
|
||||
Align, Border, Borders, CharProps, Highlight, LineSpacing, NumRef, ParaProps, Rgb, TabAlign, TabStop, TextColor, ThemeFont, Underline, VertAlign,
|
||||
};
|
||||
use crate::styles::{StyleKind, StyleSheet};
|
||||
|
||||
@@ -71,6 +71,10 @@ pub struct ResolvedChar {
|
||||
/// East Asian font (Chinese, Japanese and Korean text), when one is set.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub font_ea: Option<String>,
|
||||
/// Theme font slot for the East Asian font (`w:eastAsiaTheme`), taking precedence over
|
||||
/// `font_ea` when set.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub font_ea_theme: Option<ThemeFont>,
|
||||
pub size_cs: f32,
|
||||
pub bold_cs: bool,
|
||||
pub italic_cs: bool,
|
||||
@@ -117,6 +121,7 @@ impl ResolvedChar {
|
||||
cs: c.cs.unwrap_or(false),
|
||||
font_cs: c.font_cs.clone().or_else(|| c.font.clone()).unwrap_or_else(|| crate::styles::BODY_FONT.to_string()),
|
||||
font_ea: c.font_ea.clone(),
|
||||
font_ea_theme: c.font_ea_theme,
|
||||
size_cs: c.size_cs.or(c.size).unwrap_or(crate::props::DEFAULT_FONT_SIZE).clamp(1.0, 1638.0),
|
||||
// A run marked complex script (`w:cs`) is bold and italic only by `w:bCs` and `w:iCs`:
|
||||
// Word draws Thai with `<w:b/><w:cs/>` and no `w:bCs` upright and plain (measured in
|
||||
|
||||
@@ -296,6 +296,7 @@ impl NumFormat {
|
||||
use crate::cjk_numbers as cjk;
|
||||
match self {
|
||||
NumFormat::DecimalZero => format!("{n:02}"),
|
||||
NumFormat::Hex => format!("{n:X}"),
|
||||
NumFormat::ThaiNumbers => thai_digits(n),
|
||||
NumFormat::UpperRoman => roman(n).to_uppercase(),
|
||||
NumFormat::LowerRoman => roman(n),
|
||||
@@ -341,7 +342,6 @@ impl NumFormat {
|
||||
NumFormat::Chosung => cjk::chosung(n),
|
||||
NumFormat::Decimal
|
||||
| NumFormat::DecimalHalfWidth
|
||||
| NumFormat::Hex
|
||||
| NumFormat::VietnameseCounting
|
||||
| NumFormat::Hebrew1
|
||||
| NumFormat::Hebrew2
|
||||
@@ -496,13 +496,21 @@ pub fn cardinal_text(n: u32) -> String {
|
||||
let h = format!("{} hundred", words(n / 100));
|
||||
if n.is_multiple_of(100) { h } else { format!("{h} {}", words(n % 100)) }
|
||||
}
|
||||
_ => {
|
||||
1_000..=999_999 => {
|
||||
let th = format!("{} thousand", words(n / 1000));
|
||||
if n.is_multiple_of(1000) { th } else { format!("{th} {}", words(n % 1000)) }
|
||||
}
|
||||
1_000_000..=999_999_999 => {
|
||||
let m = format!("{} million", words(n / 1_000_000));
|
||||
if n.is_multiple_of(1_000_000) { m } else { format!("{m} {}", words(n % 1_000_000)) }
|
||||
}
|
||||
_ => {
|
||||
let b = format!("{} billion", words(n / 1_000_000_000));
|
||||
if n.is_multiple_of(1_000_000_000) { b } else { format!("{b} {}", words(n % 1_000_000_000)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
capitalize(&words(n.min(999_999)))
|
||||
capitalize(&words(n))
|
||||
}
|
||||
|
||||
/// English ordinal words (`Twenty-First`).
|
||||
@@ -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() {
|
||||
|
||||
@@ -1330,6 +1330,8 @@ fn hinted_east_asian_or_cs_font_does_not_replace_the_latin_font() {
|
||||
assert_eq!((ea.font.as_str(), ea.font_ea.as_deref()), ("Times New Roman", Some("宋体")));
|
||||
let cs = d.styles.resolve_char(p.props.style.as_deref(), &p.runs[1].props);
|
||||
assert_eq!((cs.font.as_str(), cs.font_cs.as_str()), ("Times New Roman", "Arial"));
|
||||
assert_eq!(ea.font_ea_theme, None, "named w:eastAsia replaces Heading2's w:eastAsiaTheme");
|
||||
assert_eq!(cs.font_ea_theme, Some(wordcraft_doc::props::ThemeFont::MajorEastAsia));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2444,33 +2446,51 @@ 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.)
|
||||
/// A hyperlinked nested group in a footnote or endnote separator is flattened through the block
|
||||
/// mapping just as it is in the document body.
|
||||
#[test]
|
||||
fn 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>"#;
|
||||
fn linked_nested_group_in_a_note_separator_is_flattened() {
|
||||
let inner = r#"<wpg:grpSp><wpg:cNvPr id="3" name="Inner"><a:hlinkClick r:id="rId9"/></wpg:cNvPr><wpg:cNvGrpSpPr/><wpg:grpSpPr><a:xfrm><a:off x="635000" y="0"/><a:ext cx="635000" cy="635000"/><a:chOff x="0" y="0"/><a:chExt cx="635000" cy="635000"/></a:xfrm></wpg:grpSpPr><wps:wsp><wps:cNvPr id="4" name="Frame"/><wps:cNvSpPr/><wps:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="635000" cy="635000"/></a:xfrm><a:prstGeom prst="frame"/></wps:spPr><wps:bodyPr/></wps:wsp></wpg:grpSp>"#;
|
||||
let group = format!(
|
||||
r#"<w:r><w:drawing><wp:inline><wp:extent cx="1270000" cy="635000"/><wp:docPr id="1" name="Outer"/><a:graphic><a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup"><wpg:wgp><wpg:cNvGrpSpPr/><wpg:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="1270000" cy="635000"/><a:chOff x="0" y="0"/><a:chExt cx="1270000" cy="635000"/></a:xfrm></wpg:grpSpPr>{inner}</wpg:wgp></a:graphicData></a:graphic></wp:inline></w:drawing></w:r>"#
|
||||
);
|
||||
let notes = |root: &str, item: &str| {
|
||||
format!(r#"<w:{root} {W_NS}><w:{item} w:type="separator" w:id="-1"><w:p>{frame}<w:r><w:separator/></w:r></w:p></w:{item}></w:{root}>"#)
|
||||
format!(r#"<w:{root} {W_NS}><w:{item} w:type="separator" w:id="-1"><w:p>{group}<w:r><w:separator/></w:r></w:p></w:{item}></w:{root}>"#)
|
||||
};
|
||||
let footnotes = notes("footnotes", "footnote");
|
||||
let endnotes = notes("endnotes", "endnote");
|
||||
let link_rels = rels(&[("rId9", "hyperlink", "https://example.com/")]);
|
||||
let bytes = docx(
|
||||
&format!("<w:p>{frame}</w:p>"),
|
||||
&[("rId1", "footnotes", "footnotes.xml"), ("rId2", "endnotes", "endnotes.xml")],
|
||||
&[("word/footnotes.xml", &footnotes), ("word/endnotes.xml", &endnotes)],
|
||||
&format!("<w:p>{group}</w:p>"),
|
||||
&[("rId1", "footnotes", "footnotes.xml"), ("rId2", "endnotes", "endnotes.xml"), ("rId9", "hyperlink", "https://example.com/")],
|
||||
&[
|
||||
("word/footnotes.xml", &footnotes),
|
||||
("word/_rels/footnotes.xml.rels", &link_rels),
|
||||
("word/endnotes.xml", &endnotes),
|
||||
("word/_rels/endnotes.xml.rels", &link_rels),
|
||||
],
|
||||
);
|
||||
let d = wordcraft_docx::read(&bytes).unwrap();
|
||||
let 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 flattened = |p: &Paragraph| -> Vec<(f32, f32, ShapeKind, f32)> {
|
||||
let Some(children) = p.objects.iter().find_map(|o| match o {
|
||||
InlineObject::Group { children, .. } => Some(children),
|
||||
_ => None,
|
||||
}) else {
|
||||
panic!("{:?}", p.objects);
|
||||
};
|
||||
children
|
||||
.iter()
|
||||
.map(|c| match &c.obj {
|
||||
InlineObject::Shape { kind, w, .. } => (c.x, c.y, *kind, *w),
|
||||
other => panic!("{other:?}"),
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let in_body = 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);
|
||||
let in_body = flattened(d.body[0].as_para().unwrap());
|
||||
assert_eq!(in_body, [(50.0, 0.0, ShapeKind::Frame, 50.0)]);
|
||||
for separators in [&d.footnote_separators, &d.endnote_separators] {
|
||||
let sep = separators.separator.as_ref().unwrap()[0].as_para().unwrap();
|
||||
assert_eq!(shapes(sep), in_body);
|
||||
assert_eq!(flattened(sep), in_body);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -132,6 +132,7 @@ fn every_char_prop_round_trips() {
|
||||
cs: Some(true),
|
||||
font_cs: Some("B Nazanin".into()),
|
||||
font_ea: Some("宋体".into()),
|
||||
font_ea_theme: Some(wordcraft_doc::props::ThemeFont::MinorEastAsia),
|
||||
size_cs: Some(13.0),
|
||||
bold_cs: Some(false),
|
||||
italic_cs: Some(true),
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use serde_json::Value;
|
||||
use wordcraft_doc::math_edit::MathPos;
|
||||
use wordcraft_doc::para::OBJ;
|
||||
use wordcraft_doc::{InlineObject, Pos, StoryRef};
|
||||
use wordcraft_doc::{InlineObject, Paragraph, Path, Pos, StoryRef};
|
||||
use wordcraft_layout::ViewMode;
|
||||
|
||||
use super::{parse_pos, sel_result};
|
||||
@@ -110,7 +110,8 @@ fn bidi_para(s: &Session) -> bool {
|
||||
|
||||
/// Left/Right: with a selection and no Shift, collapse to its edge.
|
||||
fn lr(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
|
||||
if !extend(v) && !s.sel.is_collapsed() {
|
||||
let ext = extend(v);
|
||||
if !ext && !s.sel.is_collapsed() {
|
||||
let (a, b) = s.sel.ordered();
|
||||
// The left edge of a selection in right-to-left text is its logical end.
|
||||
let to_start = is_left != rtl_para(s);
|
||||
@@ -121,26 +122,33 @@ fn lr(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
|
||||
if bidi_para(s) {
|
||||
return visual_lr(s, v, is_left);
|
||||
}
|
||||
if !extend(v)
|
||||
let from = s.sel.focus.clone();
|
||||
// Equation entry and the grapheme step start at the same visible edge.
|
||||
let hidden = s.layout_hides_deleted(from.story);
|
||||
let edge = logical_edge(s, &from, is_left, hidden);
|
||||
if !ext
|
||||
&& !s.math_left
|
||||
&& let Some(r) = into_equation(s, is_left)
|
||||
&& let Some(r) = into_equation(s, &from, edge, is_left, hidden)
|
||||
{
|
||||
return r;
|
||||
}
|
||||
mv(s, v, if is_left { left } else { right })
|
||||
s.goal_x = None;
|
||||
let to = step_from_edge(s, &from, edge, is_left);
|
||||
apply(s, to, ext);
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
/// Left/Right onto an equation opens it, at its end from the right and at its start from the
|
||||
/// left, as in Word (#4138). Leaving it puts the caret on the far side, so the same arrow then
|
||||
/// moves on instead of going back in. A caret.left/right that itself left an equation (sent
|
||||
/// while editing one) moves on too.
|
||||
fn into_equation(s: &mut Session, is_left: bool) -> Option<CmdResult> {
|
||||
let f = s.sel.focus.clone();
|
||||
let off = if is_left { f.off.checked_sub(OBJ.len_utf8())? } else { f.off };
|
||||
if !matches!(s.doc.para_at(&f)?.object_at(off), Some(InlineObject::Equation { .. })) {
|
||||
fn into_equation(s: &mut Session, from: &Pos, edge: usize, is_left: bool, hidden: wordcraft_layout::HideDeleted) -> Option<CmdResult> {
|
||||
let off = if is_left { edge.checked_sub(OBJ.len_utf8())? } else { edge };
|
||||
let para = s.doc.para_at(from)?;
|
||||
if !matches!(para.object_at(off), Some(InlineObject::Equation { .. })) || (hidden.any() && hidden.hides(&s.doc, para.props_of_char(off).del)) {
|
||||
return None;
|
||||
}
|
||||
s.sel = Selection::caret(Pos { off, ..f });
|
||||
s.sel = Selection::caret(Pos { off, ..from.clone() });
|
||||
s.goal_x = None;
|
||||
s.pending = None;
|
||||
Some(super::equation::edit_at(s, (!is_left).then(MathPos::default)))
|
||||
@@ -159,62 +167,103 @@ fn visual_lr(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
|
||||
Some(wordcraft_layout::VisualStep::Edge { start, stop, last_line, rtl }) => {
|
||||
let at = |off| Pos { off, ..from.clone() };
|
||||
if is_left != rtl {
|
||||
match s.doc.para_at(&from) {
|
||||
Some(para) if start > 0 => at(para.prev_boundary(start)),
|
||||
_ => left(s, &at(0)),
|
||||
}
|
||||
logical_step(s, &at(start), true)
|
||||
} else if !last_line {
|
||||
at(stop)
|
||||
} else {
|
||||
let len = s.doc.para_at(&from).map_or(stop, |p| p.len());
|
||||
right(s, &at(len))
|
||||
logical_step(s, &at(len), false)
|
||||
}
|
||||
}
|
||||
None if is_left => left(s, &from),
|
||||
None => right(s, &from),
|
||||
None => logical_step(s, &from, is_left),
|
||||
};
|
||||
apply(s, to, ext);
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
fn left(s: &mut Session, p: &Pos) -> Pos {
|
||||
if let Some(para) = s.doc.para_at(p)
|
||||
&& p.off > 0
|
||||
{
|
||||
return Pos { off: para.prev_boundary(p.off), ..p.clone() };
|
||||
/// The two ends of a hidden deletion share a caret position. Cross the hidden
|
||||
/// span before taking the normal grapheme step, including adjacent deletions.
|
||||
fn hidden_deletion_edge(para: &Paragraph, off: usize, is_left: bool, hides: impl Fn(Option<u32>) -> bool) -> usize {
|
||||
// At a run boundary, inspect the byte on the side the caret is moving toward.
|
||||
let Some(byte) = off.checked_sub(usize::from(is_left)).filter(|&byte| byte < para.len()) else { return off };
|
||||
// Runs store lengths, so find the containing run from the nearer end of the paragraph.
|
||||
let found = if byte < para.len() / 2 {
|
||||
para.run_ranges().enumerate().find_map(|(i, (range, _))| range.contains(&byte).then_some((i, range)))
|
||||
} else {
|
||||
let mut end = para.len();
|
||||
para.runs.iter().enumerate().rev().find_map(|(i, run)| {
|
||||
let range = end - run.len..end;
|
||||
end = range.start;
|
||||
range.contains(&byte).then_some((i, range))
|
||||
})
|
||||
};
|
||||
let Some((i, range)) = found else { return off };
|
||||
if !hides(para.runs[i].props.del) {
|
||||
return off;
|
||||
}
|
||||
match s.doc.prev_para(p.story, &p.path) {
|
||||
Some(q) => {
|
||||
let off = s.doc.para(p.story, &q).map(|x| x.len()).unwrap_or(0);
|
||||
Pos { story: p.story, path: q, off }
|
||||
}
|
||||
None => p.clone(),
|
||||
if is_left {
|
||||
range.start - para.runs[..i].iter().rev().take_while(|run| hides(run.props.del)).map(|run| run.len).sum::<usize>()
|
||||
} else {
|
||||
range.end + para.runs[i + 1..].iter().take_while(|run| hides(run.props.del)).map(|run| run.len).sum::<usize>()
|
||||
}
|
||||
}
|
||||
|
||||
fn right(s: &mut Session, p: &Pos) -> Pos {
|
||||
if let Some(para) = s.doc.para_at(p)
|
||||
&& p.off < para.len()
|
||||
fn logical_edge(s: &Session, from: &Pos, is_left: bool, hidden: wordcraft_layout::HideDeleted) -> usize {
|
||||
if hidden.any()
|
||||
&& let Some(para) = s.doc.para_at(from)
|
||||
{
|
||||
return Pos { off: para.next_boundary(p.off), ..p.clone() };
|
||||
return hidden_deletion_edge(para, from.off, is_left, |del| hidden.hides(&s.doc, del));
|
||||
}
|
||||
match s.doc.next_para(p.story, &p.path) {
|
||||
Some(q) => Pos { story: p.story, path: q, off: 0 },
|
||||
None => p.clone(),
|
||||
from.off
|
||||
}
|
||||
|
||||
fn logical_step(s: &Session, from: &Pos, is_left: bool) -> Pos {
|
||||
let edge = logical_edge(s, from, is_left, s.layout_hides_deleted(from.story));
|
||||
step_from_edge(s, from, edge, is_left)
|
||||
}
|
||||
|
||||
fn step_from_edge(s: &Session, from: &Pos, edge: usize, is_left: bool) -> Pos {
|
||||
if let Some(para) = s.doc.para_at(from) {
|
||||
if is_left && edge > 0 {
|
||||
return Pos { off: para.prev_boundary(edge), ..from.clone() };
|
||||
}
|
||||
if !is_left && edge < para.len() {
|
||||
return Pos { off: para.next_boundary(edge), ..from.clone() };
|
||||
}
|
||||
}
|
||||
step_to_neighbor(s, from, is_left, !s.view.show_markup)
|
||||
}
|
||||
|
||||
fn step_to_neighbor(s: &Session, from: &Pos, is_left: bool, skip_deleted: bool) -> Pos {
|
||||
let story = from.story;
|
||||
let neighbor = if is_left { s.doc.prev_para(story, &from.path) } else { s.doc.next_para(story, &from.path) };
|
||||
let Some(mut path) = neighbor else { return from.clone() };
|
||||
// Layout collapses a wholly deleted paragraph in No Markup. A surviving mark still gives
|
||||
// even a paragraph without visible text a caret stop.
|
||||
let deleted = |path: &Path| s.doc.para(story, path).is_some_and(|p| p.mark.del.is_some() && p.runs.iter().all(|r| r.props.del.is_some()));
|
||||
if skip_deleted && deleted(&path) {
|
||||
// Get the story's paths once for the rest of the walk, even across many deleted paragraphs.
|
||||
let paths = s.doc.para_paths(story);
|
||||
let Ok(i) = paths.binary_search(&path) else { return from.clone() };
|
||||
let stop = if is_left { paths[..i].iter().rev().find(|p| !deleted(p)) } else { paths[i + 1..].iter().find(|p| !deleted(p)) };
|
||||
let Some(stop) = stop else { return from.clone() };
|
||||
path = stop.clone();
|
||||
}
|
||||
let off = if is_left { s.doc.para(story, &path).map_or(0, Paragraph::len) } else { 0 };
|
||||
Pos { story, path, off }
|
||||
}
|
||||
|
||||
fn word_left(s: &mut Session, p: &Pos) -> Pos {
|
||||
match s.doc.para_at(p) {
|
||||
Some(para) if p.off > 0 => Pos { off: para.word_start(p.off), ..p.clone() },
|
||||
_ => left(s, p),
|
||||
_ => step_to_neighbor(s, p, true, false),
|
||||
}
|
||||
}
|
||||
|
||||
fn word_right(s: &mut Session, p: &Pos) -> Pos {
|
||||
match s.doc.para_at(p) {
|
||||
Some(para) if p.off < para.len() => Pos { off: para.word_end(p.off), ..p.clone() },
|
||||
_ => right(s, p),
|
||||
_ => step_to_neighbor(s, p, false, false),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -521,6 +521,13 @@ fn place(s: &mut Session, layout: &DocLayout, obj: InlineObject, page: usize, (x
|
||||
float.y = y - origin.y;
|
||||
}
|
||||
para.touch();
|
||||
if !on_page && let Some(offset) = super::objects::shifted_float_offset(s, &at, page, y, origin.y) {
|
||||
super::objects::edit_obj(s, &at, |o| {
|
||||
if let Some(float) = o.float_mut() {
|
||||
float.y = offset;
|
||||
}
|
||||
})?;
|
||||
}
|
||||
Ok(at)
|
||||
}
|
||||
|
||||
|
||||
@@ -145,7 +145,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
sel_result(s)
|
||||
})
|
||||
.key("Mod+W / Mod+F4")
|
||||
.params(r#"{"force"?: bool (desktop app's control channel and MCP bridge only: without it a document with unsaved changes is an error and stays open; with it the changes are discarded. Headless sessions never ask; file.closeDocument closes a document there)}"#)
|
||||
.params(r#"{"save"?: bool (desktop app's control channel and MCP bridge only: save the shown document, then close it; it does not apply to a background `doc`, which needs force or its own save first), "force"?: bool (desktop app's control channel and MCP bridge only: without save or force a document with unsaved changes is an error and stays open; with force the changes are discarded. Headless sessions never ask; file.closeDocument closes a document there)}"#)
|
||||
.pure(),
|
||||
CommandSpec::new("file.closeDocument", "Close Document", "Agents", close_document)
|
||||
.params(r#"{"id"?: n (an open document, see view.switchWindows; default the active one), "force"?: bool (discard unsaved changes; without it a document with unsaved changes is an error and stays open)} → {"closed": id, "active": id, "documents": [{"id", "title", "path", "dirty", "active"}]}; closing the last document leaves a new blank one"#)
|
||||
|
||||
@@ -352,11 +352,14 @@ 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).
|
||||
/// Whether a toggle without a `value` turns its format on. A selection (including a selected
|
||||
/// text box or a non-empty column block, whose `sel` is non-collapsed) follows its first
|
||||
/// character in document order, as Word does: one that starts formatted loses the format, all of
|
||||
/// it (#6516). A collapsed caret (including an empty column block) requires the whole word to
|
||||
/// carry the format before toggling it off.
|
||||
fn turns_on(s: &Session, has: impl Fn(&ResolvedChar) -> bool) -> bool {
|
||||
let chars = resolved(s);
|
||||
if !s.sel.is_collapsed() || selected_text_box(s).is_some() || column_rows(s).is_some() {
|
||||
if !s.sel.is_collapsed() {
|
||||
return !chars.first().is_some_and(has);
|
||||
}
|
||||
!chars.iter().all(has)
|
||||
@@ -424,6 +427,7 @@ fn font(s: &mut Session, v: &Value) -> CmdResult {
|
||||
}
|
||||
if let Some(n) = &ea {
|
||||
c.font_ea = Some(n.clone());
|
||||
c.font_ea_theme = None;
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -908,4 +908,29 @@ mod tests {
|
||||
let spec = s.registry.get(TEXT).unwrap();
|
||||
assert!(spec.mutates, "view.markdownSourceText mutates session and dirty state");
|
||||
}
|
||||
|
||||
/// Verifies entering and applying Markdown Source keep the document intact and report errors
|
||||
/// when Markdown conversion fails.
|
||||
#[test]
|
||||
fn failed_markdown_conversion_keeps_document_and_reports_error() {
|
||||
let mut s = session(SAMPLE);
|
||||
s.md_file = FileText::default();
|
||||
let err = wordcraft_formats::with_shared_conversion_error("bridge failed", || s.run(TOGGLE, &json!({}))).unwrap_err();
|
||||
assert!(err.to_string().contains("bridge failed"), "{err}");
|
||||
assert!(s.md_source.is_none());
|
||||
|
||||
for skip in [1, 2] {
|
||||
let err = wordcraft_formats::with_shared_conversion_error_after(skip, "bridge failed", || s.run(TOGGLE, &json!({}))).unwrap_err();
|
||||
assert!(err.to_string().contains("bridge failed"), "skip={skip}: {err}");
|
||||
assert!(s.md_source.is_none());
|
||||
}
|
||||
|
||||
let mut s = session(SAMPLE);
|
||||
s.run(TOGGLE, &json!({})).unwrap();
|
||||
let before = body_text(&s);
|
||||
set_text(&mut s, "# Replaced\n");
|
||||
wordcraft_formats::with_shared_conversion_error("bridge failed", || apply(&mut s));
|
||||
assert_eq!(body_text(&s), before, "failed apply leaves the document intact");
|
||||
assert!(s.status.contains("bridge failed"), "{}", s.status);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ mod shape;
|
||||
mod specs;
|
||||
|
||||
pub use arrange::moves_with_text;
|
||||
pub(crate) use arrange::{anchor_paragraph, nearest_line};
|
||||
pub(crate) use arrange::{anchor_paragraph, nearest_line, shifted_float_offset};
|
||||
#[cfg(test)]
|
||||
use group::ungroup;
|
||||
pub use picture::{OriginalSize, PictureLook, cropped_original_size, fit_size, original_size};
|
||||
|
||||
@@ -212,9 +212,29 @@ fn move_object_once(s: &mut Session, pos: &Pos, page: usize, x: f32, y: f32, (w,
|
||||
f.x = (x - origin.x).clamp(-MAX_OFFSET, MAX_OFFSET);
|
||||
f.y = (y - origin.y).clamp(-MAX_OFFSET, MAX_OFFSET);
|
||||
})?;
|
||||
if let Some(offset) = shifted_float_offset(s, &at, page, y, origin.y) {
|
||||
edit_float(s, &at, |f| f.y = offset.clamp(-MAX_OFFSET, MAX_OFFSET))?;
|
||||
}
|
||||
Ok(at)
|
||||
}
|
||||
|
||||
/// A page-to-paragraph conversion can make a float move from the unpushed paragraph top to
|
||||
/// the pushed first line. Once layout has resolved that choice, offset from the origin it used.
|
||||
/// Leave other layout effects, such as wrapping settlement or a change of page, to the caller.
|
||||
pub(crate) fn shifted_float_offset(s: &mut Session, at: &Pos, page: usize, y: f32, old_origin: f32) -> Option<f32> {
|
||||
let offset = y - old_origin;
|
||||
if offset >= 0.0
|
||||
|| at.story != StoryRef::Body
|
||||
|| at.path.depth() != 0
|
||||
|| (!s.view.read_mode && !matches!(s.view.mode, wordcraft_layout::ViewMode::Print | wordcraft_layout::ViewMode::Read))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
s.touch();
|
||||
let hit = s.layout().object(at, page)?;
|
||||
(hit.page == page && hit.origin.y > old_origin + 0.01 && (hit.rect.y - hit.origin.y - offset).abs() < 0.01).then_some(y - hit.origin.y)
|
||||
}
|
||||
|
||||
/// Turn the selected floating object's alignment (left, centred, …) into an offset from its
|
||||
/// column / paragraph that keeps it where it is, so it can be moved by an offset.
|
||||
pub(super) fn unalign(s: &mut Session) -> Result<(), CmdError> {
|
||||
@@ -245,6 +265,12 @@ pub(super) fn unalign(s: &mut Session) -> Result<(), CmdError> {
|
||||
f.y = oy.clamp(-MAX_OFFSET, MAX_OFFSET);
|
||||
}
|
||||
})?;
|
||||
if float.v_align.is_some()
|
||||
&& float.v_rel != Anchor::Page
|
||||
&& let Some(offset) = shifted_float_offset(s, &pos, hit.page, hit.rect.y, hit.origin.y)
|
||||
{
|
||||
edit_float(s, &pos, |f| f.y = offset.clamp(-MAX_OFFSET, MAX_OFFSET))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -268,11 +294,14 @@ pub(super) fn move_with_text(s: &mut Session, with_text: bool) -> CmdResult {
|
||||
let hit = s.layout().object(&pos, s.page_hint).ok_or_else(|| CmdError::Failed("the object isn't laid out".into()))?;
|
||||
// Paragraph offsets start at the paragraph's top (the hit's origin), page offsets at the page's.
|
||||
let y = if with_text { hit.rect.y - hit.origin.y } else { hit.rect.y };
|
||||
let o = edit_float(s, &pos, |f| {
|
||||
let mut o = edit_float(s, &pos, |f| {
|
||||
f.v_rel = if with_text { Anchor::Paragraph } else { Anchor::Page };
|
||||
f.v_align = None;
|
||||
f.y = y.clamp(-MAX_OFFSET, MAX_OFFSET);
|
||||
})?;
|
||||
if with_text && let Some(offset) = shifted_float_offset(s, &pos, hit.page, hit.rect.y, hit.origin.y) {
|
||||
o = edit_float(s, &pos, |f| f.y = offset.clamp(-MAX_OFFSET, MAX_OFFSET))?;
|
||||
}
|
||||
Ok(json!({"object": serde_json::to_value(o).unwrap_or(Value::Null)}))
|
||||
}
|
||||
|
||||
|
||||
@@ -54,7 +54,13 @@ type Reset = (fn(&CharProps) -> bool, fn(&mut CharProps));
|
||||
const RESETS: [Reset; 24] = [
|
||||
(|c| c.font.is_some(), |c| c.font = None),
|
||||
(|c| c.font_cs.is_some(), |c| c.font_cs = None),
|
||||
(|c| c.font_ea.is_some(), |c| c.font_ea = None),
|
||||
(
|
||||
|c| c.font_ea.is_some() || c.font_ea_theme.is_some(),
|
||||
|c| {
|
||||
c.font_ea = None;
|
||||
c.font_ea_theme = None;
|
||||
},
|
||||
),
|
||||
(|c| c.size.is_some(), |c| c.size = None),
|
||||
(|c| c.size_cs.is_some(), |c| c.size_cs = None),
|
||||
(|c| c.color.is_some(), |c| c.color = None),
|
||||
|
||||
@@ -337,7 +337,7 @@ fn clipboard_content(s: &mut Session, v: &Value) -> Result<Pasted, CmdError> {
|
||||
let text = p::str(v, "text").map(|t| t.replace("\r\n", "\n"));
|
||||
match text {
|
||||
Some(t) if !t.is_empty() => Ok(Pasted::Text(t)),
|
||||
_ => Err(CmdError::Failed("the clipboard is empty".into())),
|
||||
_ => Err(CmdError::ClipboardEmpty),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -402,7 +402,7 @@ pub fn update_fields_in(s: &mut Session, all: bool) -> Result<(), CmdError> {
|
||||
}
|
||||
let mut updates: Vec<(usize, String)> = Vec::new();
|
||||
for (k, o) in p.objects.iter().enumerate() {
|
||||
let InlineObject::Field { instr, locked: false, .. } = o else { continue };
|
||||
let InlineObject::Field { instr, result, locked: false, .. } = o else { continue };
|
||||
// A table formula reads the cells around its own cell again.
|
||||
if instr.trim_start().starts_with('=') {
|
||||
if let Some((tp, r, c)) = path.cell()
|
||||
@@ -425,12 +425,15 @@ pub fn update_fields_in(s: &mut Session, all: bool) -> Result<(), CmdError> {
|
||||
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) {
|
||||
// file opened without one, or with one that can't be read, keeps any result
|
||||
// it already has; when inserted with none, it shows today's date (the date
|
||||
// a save would stamp).
|
||||
let text = if name == "CREATEDATE"
|
||||
&& let Some((unix, offset)) = created_at(created)
|
||||
{
|
||||
crate::cmd::insert::format_date_at_in(&pic, lang.as_deref(), unix, offset)
|
||||
} else if name != "CREATEDATE" || result.is_empty() || (created.is_empty() && s.path.is_none()) {
|
||||
crate::cmd::insert::format_date_in(&pic, lang.as_deref())
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
|
||||
@@ -556,6 +556,26 @@ fn createdate_without_a_readable_creation_date() {
|
||||
assert_eq!(fields(&s)[0].1, crate::cmd::insert::format_date("yyyy-MM"));
|
||||
}
|
||||
|
||||
/// Inserting CREATEDATE into an opened file that has no creation date (plain text, Markdown, or a
|
||||
/// DOCX without `dcterms:created`) shows today's date rather than an empty result, while an
|
||||
/// existing field with a cached result keeps it.
|
||||
#[test]
|
||||
fn createdate_inserted_into_opened_file_without_creation_date() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Notes"));
|
||||
s.path = Some(std::env::temp_dir().join("notes.txt"));
|
||||
s.doc.core.created.clear();
|
||||
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#, "result": "2019-05"})).unwrap();
|
||||
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#})).unwrap();
|
||||
let expected = crate::cmd::insert::format_date("yyyy-MM");
|
||||
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
|
||||
assert_eq!(results, ["2019-05".to_string(), expected.clone()]);
|
||||
// An unreadable creation date behaves the same way: cached results stay, empty ones fill in.
|
||||
s.doc.core.created = "sometime in May".into();
|
||||
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#})).unwrap();
|
||||
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
|
||||
assert_eq!(results, ["2019-05".to_string(), expected.clone(), expected]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toc_tabs_ignore_nonentries() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Before\nContents\nOld\t9\nAfter"));
|
||||
@@ -677,6 +697,96 @@ fn a_toc_replaced_right_before_a_table_still_lands_the_caret_in_a_paragraph() {
|
||||
assert!(matches!(&*s.doc.body[new_end + 1], Block::Para(_)));
|
||||
}
|
||||
|
||||
/// Inserting a table of contents in the middle of a document places the caret in the paragraph
|
||||
/// right after the table and leaves the text above and below it unchanged.
|
||||
#[test]
|
||||
fn a_toc_inserted_in_the_middle_of_a_document_leaves_the_caret_after_it() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Intro\nAfter TOC\nChapter One\nBody below."));
|
||||
s.run("select.text", &json!({"text": "Chapter One"})).unwrap();
|
||||
s.run("styles.apply", &json!({"style": "Heading 1"})).unwrap();
|
||||
s.sel = Selection::caret(Pos { story: StoryRef::Body, path: Path::top(1), off: 0 });
|
||||
s.run("references.toc", &json!({"levels": 2})).unwrap();
|
||||
let (start, end) = toc_range(&s).unwrap();
|
||||
assert!(start > 0, "the TOC is inserted after the intro paragraph");
|
||||
assert_eq!(s.doc.body[0].as_para().map(|p| p.plain_text()).as_deref(), Some("Intro"));
|
||||
assert_eq!(
|
||||
s.sel.focus,
|
||||
Pos { story: StoryRef::Body, path: Path::top(end + 1), off: 0 },
|
||||
"the caret must land in the paragraph right after the TOC"
|
||||
);
|
||||
let below: Vec<String> = s.doc.body[end + 1..].iter().filter_map(|b| b.as_para()).map(|p| p.plain_text()).collect();
|
||||
assert_eq!(below, ["After TOC", "Chapter One", "Body below."]);
|
||||
}
|
||||
|
||||
/// One undo removes both the table of contents and the empty paragraph `caret_after_toc` adds
|
||||
/// when the table ends the document or comes right before a table, leaving no stray blank
|
||||
/// paragraph behind.
|
||||
#[test]
|
||||
fn undoing_a_toc_removes_both_the_table_and_the_added_paragraph() {
|
||||
let toc_instr = |s: &Session, i: usize| {
|
||||
s.doc.body[i].as_para().and_then(|p| {
|
||||
p.objects.iter().find_map(|o| match o {
|
||||
InlineObject::Field { instr, .. } => Some(instr.clone()),
|
||||
_ => None,
|
||||
})
|
||||
})
|
||||
};
|
||||
|
||||
// Fresh insert on an empty document undoes in one step.
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("references.toc", &json!({"levels": 2})).unwrap();
|
||||
assert!(toc_range(&s).is_some());
|
||||
assert_eq!(s.undo_depth(), 1);
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.undo_depth(), 0);
|
||||
assert!(toc_range(&s).is_none());
|
||||
assert_eq!(s.doc.body.len(), 1);
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "");
|
||||
|
||||
// Table ending the document: `caret_after_toc` appends an empty paragraph, and one undo
|
||||
// removes both the replaced table and that added paragraph.
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("references.toc", &json!({"levels": 2})).unwrap();
|
||||
let (start, end) = toc_range(&s).unwrap();
|
||||
while s.doc.body.len() > end + 1 {
|
||||
s.doc.remove_block(StoryRef::Body, &Path::top(end + 1)).unwrap();
|
||||
}
|
||||
let before_blocks = s.doc.body.len();
|
||||
let depth = s.undo_depth();
|
||||
s.run("references.toc", &json!({"levels": 3})).unwrap();
|
||||
let (_, new_end) = toc_range(&s).unwrap();
|
||||
assert!(s.doc.body.get(new_end + 1).is_some_and(|b| b.as_para().is_some_and(|p| p.is_empty())));
|
||||
assert_eq!(s.doc.body.len(), before_blocks + 1);
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.undo_depth(), depth);
|
||||
assert_eq!(s.doc.body.len(), before_blocks, "undo must remove the added trailing paragraph");
|
||||
assert_eq!(toc_range(&s), Some((start, end)));
|
||||
assert!(toc_instr(&s, start).as_deref().is_some_and(|i| i.contains(r#"\o "1-2""#)));
|
||||
|
||||
// Table right before another table: `caret_after_toc` inserts an empty paragraph before the
|
||||
// table, and one undo removes both the replaced TOC and that added paragraph.
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("references.toc", &json!({"levels": 2})).unwrap();
|
||||
s.run("insert.table", &json!({"rows": 1, "cols": 1})).unwrap();
|
||||
let (start, end) = toc_range(&s).unwrap();
|
||||
while s.doc.body.get(end + 1).is_some_and(|b| b.as_para().is_some_and(|p| p.is_empty())) {
|
||||
s.doc.remove_block(StoryRef::Body, &Path::top(end + 1)).unwrap();
|
||||
}
|
||||
assert!(matches!(&*s.doc.body[end + 1], Block::Table(_)));
|
||||
let before_blocks = s.doc.body.len();
|
||||
let depth = s.undo_depth();
|
||||
s.run("references.toc", &json!({"levels": 3})).unwrap();
|
||||
let (_, new_end) = toc_range(&s).unwrap();
|
||||
assert!(s.doc.body.get(new_end + 1).is_some_and(|b| b.as_para().is_some_and(|p| p.is_empty())));
|
||||
assert_eq!(s.doc.body.len(), before_blocks + 1);
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.undo_depth(), depth);
|
||||
assert_eq!(s.doc.body.len(), before_blocks, "undo must remove the added paragraph before the table");
|
||||
assert_eq!(toc_range(&s), Some((start, end)));
|
||||
assert!(matches!(&*s.doc.body[end + 1], Block::Table(_)));
|
||||
assert!(toc_instr(&s, start).as_deref().is_some_and(|i| i.contains(r#"\o "1-2""#)));
|
||||
}
|
||||
|
||||
/// A fresh scratch directory for the file-name tests below.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn filename_scratch_dir(tag: &str) -> std::path::PathBuf {
|
||||
|
||||
@@ -270,8 +270,14 @@ fn resolve_all(s: &mut Session, accept: bool) -> CmdResult {
|
||||
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)?;
|
||||
if trailing && remove_trailing_para(s, st, &path)? {
|
||||
// Selection ends in the removed paragraph go to the end of the one before it;
|
||||
// clamping later would keep their offsets in that paragraph's text (#8500).
|
||||
for end in [&mut s.sel.anchor, &mut s.sel.focus] {
|
||||
if end.story == st && end.path == path {
|
||||
*end = s.doc.clamp(&Pos { off: usize::MAX, ..end.clone() });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -491,6 +491,81 @@ fn deletions_outside_the_body_stay_inline_when_revisions_go_in_balloons() {
|
||||
assert_eq!(deletion_balloons(&s), vec![DeletionBalloon { at: Pos::body(0, at), author: "Ana".into(), text: "zeta".into() }]);
|
||||
}
|
||||
|
||||
fn assert_revision_arrow_stops(s: &mut Session, story: wordcraft_doc::StoryRef, from: [usize; 2], to: [usize; 2]) {
|
||||
use wordcraft_doc::{Path, Pos};
|
||||
|
||||
let pos = |off| Pos::new(story, Path::top(0), off);
|
||||
for (key, start, end) in [("Right", from[0], to[0]), ("Left", from[1], to[1])] {
|
||||
let cmd = s.registry.by_shortcut(key).unwrap().id;
|
||||
for extend in [false, true] {
|
||||
s.run("caret.set", &json!({"pos": pos(start)})).unwrap();
|
||||
s.run(cmd, &json!({"extend": extend})).unwrap();
|
||||
assert_eq!(s.sel.focus, pos(end), "{key}, Shift {extend}, from {start}");
|
||||
assert_eq!(s.sel.anchor, pos(if extend { start } else { end }));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn horizontal_arrows_follow_revision_balloon_visibility_by_story() {
|
||||
use wordcraft_doc::{Path, Pos, StoryRef};
|
||||
|
||||
let mut s = Session::new(Document::from_text("AQRSZ"));
|
||||
let id = s.run("insert.header", &json!({"text": "ABCDZ"})).unwrap()["story"].as_u64().unwrap() as u32;
|
||||
let header = StoryRef::Part(id);
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
s.run("review.trackChanges", &json!({"value": true})).unwrap();
|
||||
for story in [StoryRef::Body, header] {
|
||||
let at = |off| Pos::new(story, Path::top(0), off);
|
||||
s.run("select.range", &json!({"anchor": at(1), "focus": at(4)})).unwrap();
|
||||
s.run("text.delete", &json!({})).unwrap();
|
||||
assert!(s.doc.para_at(&at(1)).unwrap().props_of_char(1).del.is_some());
|
||||
}
|
||||
|
||||
s.run("review.trackingOptions", &json!({"balloons": "revisions"})).unwrap();
|
||||
assert!(s.revisions_in_balloons());
|
||||
assert_revision_arrow_stops(&mut s, StoryRef::Body, [1, 4], [5, 0]);
|
||||
assert_revision_arrow_stops(&mut s, header, [1, 4], [2, 3]);
|
||||
|
||||
s.run("view.commentsPane", &json!({"value": true})).unwrap();
|
||||
assert!(!s.revisions_in_balloons());
|
||||
assert_revision_arrow_stops(&mut s, StoryRef::Body, [1, 4], [2, 3]);
|
||||
|
||||
s.run("review.trackingOptions", &json!({"balloons": "inline"})).unwrap();
|
||||
s.run("view.commentsPane", &json!({"value": false})).unwrap();
|
||||
assert_revision_arrow_stops(&mut s, StoryRef::Body, [1, 4], [2, 3]);
|
||||
|
||||
s.run("review.markup", &json!({"value": "noMarkup"})).unwrap();
|
||||
for story in [StoryRef::Body, header] {
|
||||
assert_revision_arrow_stops(&mut s, story, [1, 4], [5, 0]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn horizontal_arrows_distinguish_hidden_deletions_from_hidden_move_sources() {
|
||||
use wordcraft_doc::{Pos, Revision, RevisionKind, StoryRef};
|
||||
|
||||
let mut doc = Document::from_text("AxyuvZuv");
|
||||
let deletion = Revision::new(RevisionKind::Delete, "Author", "");
|
||||
let source = Revision { move_name: Some("Move1".into()), ..deletion.clone() };
|
||||
let destination = Revision { kind: RevisionKind::Insert, ..source.clone() };
|
||||
doc.revisions.extend([deletion, source, destination]);
|
||||
doc.format_range(&Pos::body(0, 1), &Pos::body(0, 3), &|c| c.del = Some(0)).unwrap();
|
||||
doc.format_range(&Pos::body(0, 3), &Pos::body(0, 5), &|c| c.del = Some(1)).unwrap();
|
||||
doc.format_range(&Pos::body(0, 6), &Pos::body(0, 8), &|c| c.ins = Some(2)).unwrap();
|
||||
let mut s = Session::new(doc);
|
||||
|
||||
for (delete_mark, move_from_mark, expected) in [
|
||||
("strikethrough", "strikethrough", [2, 4]),
|
||||
("hidden", "strikethrough", [4, 4]),
|
||||
("strikethrough", "hidden", [2, 2]),
|
||||
("hidden", "hidden", [6, 0]),
|
||||
] {
|
||||
s.run("review.trackingOptions", &json!({"balloons": "inline", "deleteMark": delete_mark, "moveFromMark": move_from_mark})).unwrap();
|
||||
assert_revision_arrow_stops(&mut s, StoryRef::Body, [1, 5], expected);
|
||||
}
|
||||
}
|
||||
|
||||
fn body_para(s: &Session) -> &wordcraft_doc::Paragraph {
|
||||
s.doc.para(wordcraft_doc::StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap()
|
||||
}
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -16,72 +16,6 @@ fn empty_paras(s: &Session) -> usize {
|
||||
s.doc.body.iter().filter(|b| matches!(b.as_para(), Some(p) if p.is_empty())).count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_marks_a_whole_paragraph_and_its_mark() {
|
||||
// A whole inserted paragraph carries the insertion on its mark, not just on its runs.
|
||||
let mut s = Session::new(Document::from_text("A\nB"));
|
||||
s.run("review.compare", &json!({"text": "A\nNEW\nB"})).unwrap();
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
let mid = s.doc.body[1].as_para().unwrap();
|
||||
assert_eq!(mid.plain_text(), "NEW");
|
||||
assert!(mid.mark.ins.is_some(), "the inserted paragraph's mark is not marked inserted");
|
||||
s.run("review.rejectAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
|
||||
assert_eq!(s.doc.body.len(), 2);
|
||||
assert_eq!(empty_paras(&s), 0, "rejecting an inserted paragraph left an empty paragraph behind");
|
||||
let mut s = Session::new(Document::from_text("A\nB"));
|
||||
s.run("review.compare", &json!({"text": "A\nNEW\nB"})).unwrap();
|
||||
s.run("review.acceptAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nNEW\nB");
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
assert_eq!(empty_paras(&s), 0, "accepting an inserted paragraph left an empty paragraph behind");
|
||||
|
||||
// A whole deleted paragraph carries the deletion on its mark.
|
||||
let mut s = Session::new(Document::from_text("A\nOLD\nB"));
|
||||
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
let mid = s.doc.body[1].as_para().unwrap();
|
||||
assert_eq!(mid.plain_text(), "OLD");
|
||||
assert!(mid.mark.del.is_some(), "the deleted paragraph's mark is not marked deleted");
|
||||
s.run("review.acceptAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
|
||||
assert_eq!(s.doc.body.len(), 2);
|
||||
assert_eq!(empty_paras(&s), 0, "accepting a deleted paragraph left an empty paragraph behind");
|
||||
let mut s = Session::new(Document::from_text("A\nOLD\nB"));
|
||||
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
|
||||
s.run("review.rejectAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nOLD\nB");
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
assert_eq!(empty_paras(&s), 0, "rejecting a deleted paragraph left an empty paragraph behind");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_marks_an_empty_paragraphs_mark() {
|
||||
// An empty inserted paragraph is stamped on its mark, though `format` skips its empty range.
|
||||
let mut s = Session::new(Document::from_text("A\nB"));
|
||||
s.run("review.compare", &json!({"text": "A\n\nB"})).unwrap();
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
let empty = s.doc.body[1].as_para().unwrap();
|
||||
assert!(empty.is_empty());
|
||||
assert!(empty.mark.ins.is_some(), "the empty inserted paragraph's mark is not marked inserted");
|
||||
s.run("review.rejectAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
|
||||
assert_eq!(s.doc.body.len(), 2);
|
||||
assert_eq!(empty_paras(&s), 0, "rejecting an empty inserted paragraph left it behind");
|
||||
|
||||
// An empty deleted paragraph is stamped on its mark too.
|
||||
let mut s = Session::new(Document::from_text("A\n\nB"));
|
||||
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
let empty = s.doc.body[1].as_para().unwrap();
|
||||
assert!(empty.is_empty());
|
||||
assert!(empty.mark.del.is_some(), "the empty deleted paragraph's mark is not marked deleted");
|
||||
s.run("review.acceptAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
|
||||
assert_eq!(s.doc.body.len(), 2);
|
||||
assert_eq!(empty_paras(&s), 0, "accepting an empty deleted paragraph left it behind");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_keeps_another_authors_deletion_stamp() {
|
||||
// A paragraph the original already carries as a tracked deletion by another author: Compare
|
||||
@@ -130,6 +64,24 @@ fn compare_terminal_deleted_paragraph_resolves_fully() {
|
||||
assert_eq!(empty_paras(&s), 0, "accepting a terminal deleted paragraph left an empty paragraph behind");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolving_a_selected_terminal_paragraph_puts_the_caret_before_it() {
|
||||
// A selection inside the terminal paragraph that Reject All (insertion) or Accept All
|
||||
// (deletion) removes ends as a caret at the end of the paragraph before it, not over the
|
||||
// same offsets of that paragraph's text (#8500).
|
||||
let cases = [("A\nKeep this", "A\nKeep this\nNEW", "review.rejectAll"), ("A\nKeep this\nOLD", "A\nKeep this", "review.acceptAll")];
|
||||
for (orig, revised, cmd) in cases {
|
||||
let mut s = Session::new(Document::from_text(orig));
|
||||
s.run("review.compare", &json!({"text": revised})).unwrap();
|
||||
s.sel = Selection { anchor: Pos::body(2, 0), focus: Pos::body(2, 3) };
|
||||
s.run(cmd, &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nKeep this", "{cmd}");
|
||||
assert_eq!(s.sel, Selection::caret(Pos::body(1, "Keep this".len())), "{cmd}");
|
||||
s.run("text.insert", &json!({"text": "Z"})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nKeep thisZ", "{cmd}");
|
||||
}
|
||||
}
|
||||
|
||||
#[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
|
||||
@@ -220,16 +172,8 @@ fn compare_pins_accepting_a_deleted_section_keeps_the_next_paragraphs_style() {
|
||||
}
|
||||
|
||||
#[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);
|
||||
fn compare_keeps_terminal_paragraph_when_insertion_accepted_or_deletion_rejected() {
|
||||
// Inserted last paragraph: accepting keeps it whole.
|
||||
let mut s = Session::new(Document::from_text("A\nB"));
|
||||
s.run("review.compare", &json!({"text": "A\nB\nNEW"})).unwrap();
|
||||
s.run("review.acceptAll", &json!({})).unwrap();
|
||||
@@ -237,15 +181,7 @@ fn compare_marks_the_last_paragraphs_mark() {
|
||||
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);
|
||||
// Deleted last paragraph: rejecting keeps it whole.
|
||||
let mut s = Session::new(Document::from_text("A\nB\nOLD"));
|
||||
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
|
||||
s.run("review.rejectAll", &json!({})).unwrap();
|
||||
@@ -1744,7 +1680,8 @@ fn compare_lcs_window_move_past_cap_does_not_cascade_false_revisions() {
|
||||
}
|
||||
|
||||
/// Verifies that `mark_block` records paragraph mark revisions on whole-block deletions,
|
||||
/// whole-block insertions, empty paragraphs, and ensures clean resolution via `review.acceptAll`.
|
||||
/// whole-block insertions, empty paragraphs, and ensures clean resolution via `review.acceptAll`
|
||||
/// and `review.rejectAll`.
|
||||
#[test]
|
||||
fn compare_mark_block_records_paragraph_mark_revisions_on_whole_block_changes() {
|
||||
// Whole block delete/insert: test with differing paragraph count so whole-block paths trigger
|
||||
@@ -1762,17 +1699,34 @@ fn compare_mark_block_records_paragraph_mark_revisions_on_whole_block_changes()
|
||||
assert!(del_para.mark.del.is_some(), "whole-block delete must record revision on paragraph mark");
|
||||
assert_eq!(del_para.mark.bold, Some(true), "paragraph mark formatting must be preserved on deleted block");
|
||||
|
||||
let mut s2_rej = Session::new(s2.doc.clone());
|
||||
s2_rej.run("review.rejectAll", &json!({})).unwrap();
|
||||
assert_eq!(s2_rej.doc.plain_text(StoryRef::Body), orig_multi);
|
||||
assert_eq!(s2_rej.doc.body.len(), 3);
|
||||
assert_eq!(empty_paras(&s2_rej), 0, "rejecting a deleted paragraph left an empty paragraph behind");
|
||||
|
||||
// Accept all changes: deleted paragraph is removed
|
||||
s2.run("review.acceptAll", &json!({})).unwrap();
|
||||
assert_eq!(s2.doc.plain_text(StoryRef::Body), rev_multi);
|
||||
assert_eq!(s2.doc.body.len(), 2);
|
||||
assert_eq!(empty_paras(&s2), 0, "accepting a deleted paragraph left an empty paragraph behind");
|
||||
|
||||
// Test whole-block insertion
|
||||
let mut s3 = Session::new(Document::from_text(rev_multi));
|
||||
s3.run("review.compare", &json!({"text": orig_multi})).unwrap();
|
||||
let ins_para = s3.doc.body[1].as_para().expect("block 1 must be paragraph");
|
||||
assert!(ins_para.mark.ins.is_some(), "whole-block insert must record revision on paragraph mark");
|
||||
|
||||
let mut s3_rej = Session::new(s3.doc.clone());
|
||||
s3_rej.run("review.rejectAll", &json!({})).unwrap();
|
||||
assert_eq!(s3_rej.doc.plain_text(StoryRef::Body), rev_multi);
|
||||
assert_eq!(s3_rej.doc.body.len(), 2);
|
||||
assert_eq!(empty_paras(&s3_rej), 0, "rejecting an inserted paragraph left an empty paragraph behind");
|
||||
|
||||
s3.run("review.acceptAll", &json!({})).unwrap();
|
||||
assert_eq!(s3.doc.plain_text(StoryRef::Body), orig_multi);
|
||||
assert_eq!(s3.doc.body.len(), 3);
|
||||
assert_eq!(empty_paras(&s3), 0, "accepting an inserted paragraph left an empty paragraph behind");
|
||||
|
||||
// Test empty paragraph deletion and insertion (len == 0, where only mark carries the revision)
|
||||
let orig_empty = "Before.\n\nAfter.";
|
||||
@@ -1784,14 +1738,24 @@ fn compare_mark_block_records_paragraph_mark_revisions_on_whole_block_changes()
|
||||
assert!(empty_del.mark.del.is_some(), "empty paragraph deletion must set mark.del");
|
||||
s4.run("review.acceptAll", &json!({})).unwrap();
|
||||
assert_eq!(s4.doc.plain_text(StoryRef::Body), rev_empty);
|
||||
assert_eq!(s4.doc.body.len(), 2);
|
||||
assert_eq!(empty_paras(&s4), 0, "accepting an empty deleted paragraph left it behind");
|
||||
|
||||
let mut s5 = Session::new(Document::from_text(rev_empty));
|
||||
s5.run("review.compare", &json!({"text": orig_empty})).unwrap();
|
||||
let empty_ins = s5.doc.body[1].as_para().expect("empty paragraph block");
|
||||
assert_eq!(empty_ins.len(), 0);
|
||||
assert!(empty_ins.mark.ins.is_some(), "empty paragraph insertion must set mark.ins");
|
||||
|
||||
let mut s5_rej = Session::new(s5.doc.clone());
|
||||
s5_rej.run("review.rejectAll", &json!({})).unwrap();
|
||||
assert_eq!(s5_rej.doc.plain_text(StoryRef::Body), rev_empty);
|
||||
assert_eq!(s5_rej.doc.body.len(), 2);
|
||||
assert_eq!(empty_paras(&s5_rej), 0, "rejecting an empty inserted paragraph left it behind");
|
||||
|
||||
s5.run("review.acceptAll", &json!({})).unwrap();
|
||||
assert_eq!(s5.doc.plain_text(StoryRef::Body), orig_empty);
|
||||
assert_eq!(s5.doc.body.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -84,6 +84,8 @@ pub enum CmdError {
|
||||
Params(String),
|
||||
#[error("not available: {0}")]
|
||||
Disabled(String),
|
||||
#[error("the clipboard is empty")]
|
||||
ClipboardEmpty,
|
||||
#[error("{0}")]
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use wordcraft_layout::HideDeleted;
|
||||
|
||||
use super::doc_state::{Selection, TypedWord, typed_range};
|
||||
use super::locale::SYSTEM_LOCALE;
|
||||
use super::snapshot_types::LayoutEntry;
|
||||
@@ -11,6 +13,20 @@ impl Session {
|
||||
self.layout_with(typing)
|
||||
}
|
||||
|
||||
fn revision_layout_options(&self) -> LayoutOptions {
|
||||
LayoutOptions {
|
||||
hide_deleted: !self.view.show_markup,
|
||||
hide_marked: self.prefs.markup.hidden_deletions(),
|
||||
deletions_in_balloons: self.revisions_in_balloons(),
|
||||
..LayoutOptions::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Which tracked deletions the editor leaves out of this story.
|
||||
pub(crate) fn layout_hides_deleted(&self, story: StoryRef) -> HideDeleted {
|
||||
self.revision_layout_options().hides_deleted(story)
|
||||
}
|
||||
|
||||
/// [`Session::layout`] with `typing` as the word being typed.
|
||||
fn layout_with(&mut self, typing: Option<wordcraft_layout::TypingWord>) -> Arc<DocLayout> {
|
||||
let mode = if self.view.read_mode { ViewMode::Read } else { self.view.mode };
|
||||
@@ -23,8 +39,8 @@ impl Session {
|
||||
let spacing = if self.view.read_mode { self.view.read_line_spacing.map(f32::to_bits) } else { None };
|
||||
// Deletions in balloons depend on the view (the Comments pane, Read Mode, side by side), so
|
||||
// a view change that moves them in or out of the text lays it out again.
|
||||
let hide_deleted = !self.view.show_markup;
|
||||
let deleted = (hide_deleted, self.prefs.markup.hidden_deletions(), self.revisions_in_balloons());
|
||||
let revisions = self.revision_layout_options();
|
||||
let deleted = (revisions.hide_deleted, revisions.hide_marked, revisions.deletions_in_balloons);
|
||||
let outline = (mode == ViewMode::Outline).then(|| self.view.outline.view());
|
||||
let shown = (self.view.marks || self.prefs.marks.hidden, self.view.field_codes);
|
||||
// A dictionary or Language pack installed, removed or edited (in this document's window or
|
||||
@@ -62,9 +78,6 @@ impl Session {
|
||||
read_height: height,
|
||||
read_line_spacing: spacing.map(f32::from_bits),
|
||||
show_hidden: shown.0,
|
||||
hide_deleted,
|
||||
hide_marked: deleted.1,
|
||||
deletions_in_balloons: deleted.2,
|
||||
proofing: self.view.proofing,
|
||||
numeral: self.view.numeral.resolve(SYSTEM_LOCALE.get().map(String::as_str)),
|
||||
comment_balloons: false,
|
||||
@@ -77,6 +90,7 @@ impl Session {
|
||||
// The editor shows a body page reference as stored until fields are updated.
|
||||
output_page_refs: false,
|
||||
bookmark_error: None,
|
||||
..revisions
|
||||
};
|
||||
let l = Arc::new(wordcraft_layout::layout(&self.doc, &mut self.cache, &opts));
|
||||
let [newest, _] = std::mem::take(&mut self.layout);
|
||||
|
||||
+248
-81
@@ -293,14 +293,6 @@ 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() {
|
||||
@@ -1118,6 +1110,79 @@ fn toggle_on_a_selection_from_an_empty_paragraph_follows_the_first_text() {
|
||||
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]);
|
||||
}
|
||||
|
||||
/// A collapsed caret inside a partly formatted word (including when column mode just started with
|
||||
/// an empty block) turns the format on unless the whole word already has it (#8658).
|
||||
#[test]
|
||||
fn toggle_at_collapsed_caret_in_partly_formatted_word_turns_on() {
|
||||
let toggled = |column_mode: bool| -> String {
|
||||
let mut s = s();
|
||||
run(&mut s, "text.insert", json!({"text": "Abc"}));
|
||||
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 0}, "focus": {"block": 0, "off": 1}}));
|
||||
run(&mut s, "format.bold", json!({"value": true}));
|
||||
run(&mut s, "caret.set", json!({"pos": {"block": 0, "off": 1}}));
|
||||
if column_mode {
|
||||
run(&mut s, "select.column", json!({}));
|
||||
}
|
||||
run(&mut s, "format.bold", json!({}));
|
||||
let p = s.doc.para_at(&Pos::body(0, 0)).unwrap();
|
||||
(0..3).map(|i| if p.props_of_char(i).bold == Some(true) { 'B' } else { '.' }).collect()
|
||||
};
|
||||
assert_eq!(toggled(false), "BBB");
|
||||
assert_eq!(toggled(true), "BBB");
|
||||
}
|
||||
|
||||
#[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).
|
||||
@@ -5109,6 +5174,48 @@ fn no_markup_view_lays_out_the_final_text() {
|
||||
assert!(gap(&mut s).abs() < 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn horizontal_caret_skips_hidden_tracked_deletions() {
|
||||
let mut s = s();
|
||||
let text = "Aé🧪ZUVΩT";
|
||||
let before = Pos::body(0, "A".len());
|
||||
let between = Pos::body(0, "Aé".len());
|
||||
let after = Pos::body(0, "Aé🧪".len());
|
||||
let far_start = Pos::body(0, "Aé🧪ZUV".len());
|
||||
let far_end = Pos::body(0, "Aé🧪ZUVΩ".len());
|
||||
run(&mut s, "document.setText", json!({"text": text}));
|
||||
// Keep the adjacent deleted characters in separate formatting runs.
|
||||
s.doc.format_range(&before, &between, &|c| c.bold = Some(true)).unwrap();
|
||||
run(&mut s, "review.trackChanges", json!({"value": true}));
|
||||
run(&mut s, "select.text", json!({"text": "é🧪"}));
|
||||
run(&mut s, "text.delete", json!({}));
|
||||
run(&mut s, "select.text", json!({"text": "Ω"}));
|
||||
run(&mut s, "text.delete", json!({}));
|
||||
assert_eq!(s.doc.para_at(&before).unwrap().deleted_ranges(), [before.off..between.off, between.off..after.off, far_start.off..far_end.off]);
|
||||
|
||||
s.sel = crate::Selection::caret(before.clone());
|
||||
run(&mut s, "caret.right", json!({}));
|
||||
assert_eq!(s.sel.focus, Pos::body(0, "Aé".len()), "visible markup still has ordinary caret stops");
|
||||
|
||||
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
|
||||
s.sel = crate::Selection::caret(before.clone());
|
||||
run(&mut s, "caret.right", json!({"extend": true}));
|
||||
assert_eq!(s.sel.anchor, before);
|
||||
assert_eq!(s.sel.focus, Pos::body(0, "Aé🧪Z".len()), "Right crosses the next visible character in one step");
|
||||
|
||||
s.sel = crate::Selection::caret(after);
|
||||
run(&mut s, "caret.left", json!({}));
|
||||
assert_eq!(s.sel.focus, Pos::body(0, 0), "Left crosses the previous visible character in one step");
|
||||
assert!(s.sel.is_collapsed());
|
||||
|
||||
s.sel = crate::Selection::caret(Pos::body(0, "Aé🧪Z".len()));
|
||||
run(&mut s, "caret.right", json!({}));
|
||||
assert_eq!(s.sel.focus, Pos::body(0, "Aé🧪ZU".len()), "a distant deletion does not change a visible stop");
|
||||
s.sel = crate::Selection::caret(far_end);
|
||||
run(&mut s, "caret.left", json!({}));
|
||||
assert_eq!(s.sel.focus, Pos::body(0, "Aé🧪ZU".len()), "Left also skips the later deletion");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replace_all_is_tracked() {
|
||||
let mut s = s();
|
||||
@@ -7062,6 +7169,56 @@ fn select_box(s: &mut Session) {
|
||||
run(s, "select.range", json!({"anchor": o.pos(), "focus": end}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dragging_above_a_pushed_first_line_keeps_the_drop_position() {
|
||||
use wordcraft_doc::para::{Anchor, Float, InlineObject, OBJ, ShapeKind, Wrap};
|
||||
let shape = |w, h, float| InlineObject::Shape {
|
||||
kind: ShapeKind::Rectangle,
|
||||
w,
|
||||
h,
|
||||
fill: None,
|
||||
stroke: None,
|
||||
stroke_width: 1.0,
|
||||
float,
|
||||
story: None,
|
||||
freeform: None,
|
||||
effects: Default::default(),
|
||||
extra: Default::default(),
|
||||
};
|
||||
for frame_wrap in [Wrap::TopAndBottom, Wrap::BehindText] {
|
||||
// Original synthetic version of #6587's first-line push. Only the frame wraps text.
|
||||
let mut doc = wordcraft_doc::Document::from_text("A line under a frame.");
|
||||
let old_top = doc.last_section.margin_top;
|
||||
let (x, y) = (120.0, old_top - 22.0);
|
||||
let object = Float { wrap: Wrap::InFrontOfText, h_rel: Anchor::Page, v_rel: Anchor::Page, x, y: old_top + 12.0, ..Default::default() };
|
||||
let frame = Float { wrap: frame_wrap, v_rel: Anchor::Paragraph, y: -20.0, ..Default::default() };
|
||||
let at = Pos::body(0, 0);
|
||||
let end = Pos::body(0, OBJ.len_utf8());
|
||||
doc.insert_object(&at, shape(40.0, 18.0, object), &Default::default()).unwrap();
|
||||
doc.insert_object(&end, shape(300.0, 250.0, frame), &Default::default()).unwrap();
|
||||
let mut s = Session::new(doc);
|
||||
run(&mut s, "select.range", json!({"anchor": at, "focus": end}));
|
||||
run(&mut s, "arrange.bounds", json!({"page": 0, "x": x, "y": y}));
|
||||
let hit = s.layout().object(&at, 0).unwrap();
|
||||
assert!((hit.rect.y - y).abs() < 0.01 && (hit.rect.x - x).abs() < 0.01, "{frame_wrap:?}: {hit:?}");
|
||||
assert_eq!(hit.origin.y > old_top + 1.0, frame_wrap == Wrap::TopAndBottom);
|
||||
|
||||
for (with_text, anchor) in [(false, Anchor::Page), (true, Anchor::Paragraph)] {
|
||||
run(&mut s, "arrange.moveWithText", json!({"value": with_text}));
|
||||
let hit = s.layout().object(&at, 0).unwrap();
|
||||
let (_, _, float) = s.doc.para_at(&at).unwrap().object_at(at.off).unwrap().frame().unwrap();
|
||||
assert_eq!(float.v_rel, anchor);
|
||||
assert!((hit.rect.y - y).abs() < 0.01, "{frame_wrap:?}, {anchor:?}: {hit:?}");
|
||||
let origin = if with_text { hit.origin.y } else { 0.0 };
|
||||
assert!((hit.rect.y - origin - float.y).abs() < 0.01, "{frame_wrap:?}, {anchor:?}: {hit:?}");
|
||||
}
|
||||
|
||||
run(&mut s, "draw.stroke", json!({"page": 0, "points": [[x, y], [x + 10.0, y]], "width": 2.0}));
|
||||
let ink = s.layout().object(&at, 0).unwrap();
|
||||
assert!((ink.rect.y - (y - 1.0)).abs() < 0.01, "{frame_wrap:?}: {ink:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrange_bounds_resizes_and_moves_objects() {
|
||||
use wordcraft_doc::para::{Anchor, Wrap};
|
||||
@@ -10004,77 +10161,6 @@ fn change_case_keeps_each_runs_formatting_when_lengths_change() {
|
||||
assert_eq!(text(&s), "Q");
|
||||
}
|
||||
|
||||
/// #3479: Change Case follows language-aware mapping for Turkish, Azerbaijani, and Crimean Tatar (i↔İ, ı↔I).
|
||||
#[test]
|
||||
fn change_case_follows_turkic_language_mapping() {
|
||||
// 1. Turkish (tr-TR): all 5 modes
|
||||
// Capitalize Each Word (title)
|
||||
let mut s = s();
|
||||
run(&mut s, "review.language", json!({"lang": "tr-TR", "default": true}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul ışık", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "title"}));
|
||||
assert_eq!(text(&s), "İstanbul Işık");
|
||||
|
||||
// UPPERCASE
|
||||
run(&mut s, "format.changeCase", json!({"mode": "upper"}));
|
||||
assert_eq!(text(&s), "İSTANBUL IŞIK");
|
||||
|
||||
// lowercase
|
||||
run(&mut s, "format.changeCase", json!({"mode": "lower"}));
|
||||
assert_eq!(text(&s), "istanbul ışık");
|
||||
|
||||
// sentence case
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "tr-TR", "default": true}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul. ışık.", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "sentence"}));
|
||||
assert_eq!(text(&s), "İstanbul. Işık.");
|
||||
|
||||
// toggle case
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "tr-TR", "default": true}));
|
||||
run(&mut s, "text.insert", json!({"text": "İstanbul Işık", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "toggle"}));
|
||||
assert_eq!(text(&s), "iSTANBUL ıŞIK");
|
||||
|
||||
// 2. Azerbaijani (az-AZ)
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "az-AZ", "default": true}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "title"}));
|
||||
assert_eq!(text(&s), "İstanbul");
|
||||
|
||||
// 3. Crimean Tatar (crh)
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "crh", "default": true}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "title"}));
|
||||
assert_eq!(text(&s), "İstanbul");
|
||||
|
||||
// 4. English control (en-US): unchanged Unicode default
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "en-US", "default": true}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "title"}));
|
||||
assert_eq!(text(&s), "Istanbul");
|
||||
|
||||
// 5. Mixed-language selection: Turkish run followed by English run
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "tr-TR"}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul ", "raw": true}));
|
||||
run(&mut s, "review.language", json!({"lang": "en-US"}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "title"}));
|
||||
assert_eq!(text(&s), "İstanbul Istanbul");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn change_case_sentence_ignores_decimal_points() {
|
||||
// #3485: Sentence case should not capitalize after decimal points.
|
||||
@@ -12623,10 +12709,12 @@ fn outline_level_changes_are_undoable() {
|
||||
assert!(s.run("outline.level", &json!({"level": 12})).is_err());
|
||||
assert!(s.run("outline.level", &json!({})).is_err());
|
||||
// Every outline command survives junk parameters in Outline view.
|
||||
for spec in cmd::registry().all().iter().filter(|c| c.id.starts_with("outline.")) {
|
||||
let reg = cmd::registry();
|
||||
for spec in reg.all().iter().filter(|c| c.id.starts_with("outline.")) {
|
||||
for j in [json!(null), json!({"block": 99999, "level": "x", "value": 5}), json!({"block": -1, "level": 0})] {
|
||||
let mut s = outline_doc();
|
||||
let _ = s.run(spec.id, &j);
|
||||
let r = s.run(spec.id, &j);
|
||||
assert!(!caught_panic(®, &r), "{} panicked on {j}: {r:?}", spec.id);
|
||||
let _ = s.layout();
|
||||
}
|
||||
}
|
||||
@@ -16166,3 +16254,82 @@ fn nested_group_text_box_survives_mutating_session_commands() {
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Part(id)), "nested group box");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copy_refuses_to_fill_clipboard_by_halves_when_export_fails() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("first second"));
|
||||
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, 5)}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
|
||||
let prev_text = s.clipboard_text.clone();
|
||||
let prev_html = s.clipboard_html.clone();
|
||||
let prev_rtf = s.clipboard_rtf.clone();
|
||||
let prev_history_len = s.clip_history.len();
|
||||
assert_eq!(prev_text, "first");
|
||||
assert!(!prev_html.is_empty() && !prev_rtf.is_empty());
|
||||
|
||||
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 6), "focus": Pos::body(0, 12)}));
|
||||
|
||||
// HTML export fails first.
|
||||
let err = wordcraft_formats::with_shared_conversion_error("html failed", || s.run("edit.copy", &json!({}))).unwrap_err();
|
||||
assert!(err.to_string().contains("html failed"), "{err}");
|
||||
assert_eq!(s.clipboard_text, prev_text);
|
||||
assert_eq!(s.clipboard_html, prev_html);
|
||||
assert_eq!(s.clipboard_rtf, prev_rtf);
|
||||
assert_eq!(s.clipboard.as_ref().map(|f| f.plain_text()), Some("first".to_string()));
|
||||
assert_eq!(s.clip_history.len(), prev_history_len);
|
||||
|
||||
// HTML export succeeds and RTF export fails: clipboard still keeps "first" whole.
|
||||
let err = wordcraft_formats::with_shared_conversion_error_after(1, "rtf failed", || s.run("edit.copy", &json!({}))).unwrap_err();
|
||||
assert!(err.to_string().contains("rtf failed"), "{err}");
|
||||
assert_eq!(s.clipboard_text, prev_text);
|
||||
assert_eq!(s.clipboard_html, prev_html);
|
||||
assert_eq!(s.clipboard_rtf, prev_rtf);
|
||||
assert_eq!(s.clipboard.as_ref().map(|f| f.plain_text()), Some("first".to_string()));
|
||||
assert_eq!(s.clip_history.len(), prev_history_len);
|
||||
|
||||
// Cut also refuses to delete the selection when export fails.
|
||||
let err = wordcraft_formats::with_shared_conversion_error_after(1, "rtf failed", || s.run("edit.cut", &json!({}))).unwrap_err();
|
||||
assert!(err.to_string().contains("rtf failed"), "{err}");
|
||||
assert_eq!(text(&s), "first second");
|
||||
assert_eq!(s.clipboard_text, prev_text);
|
||||
assert_eq!(s.clipboard_html, prev_html);
|
||||
assert_eq!(s.clipboard_rtf, prev_rtf);
|
||||
assert_eq!(s.clip_history.len(), prev_history_len);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paste_reports_or_falls_back_when_html_import_fails() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("kept"));
|
||||
let err = wordcraft_formats::with_shared_conversion_error("html import failed", || {
|
||||
s.run("edit.pasteSpecial", &json!({"as": "html", "html": "<p>new</p>"}))
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(err.to_string().contains("html import failed"), "{err}");
|
||||
assert_eq!(text(&s), "kept");
|
||||
|
||||
let fallback = wordcraft_formats::with_shared_conversion_error_after(0, "html import failed", || {
|
||||
cmd::paste::rich_fragment(&mut s, &json!({"html": "<p>from html</p>", "rtf": "{\\rtf1 from rtf}"}))
|
||||
});
|
||||
assert_eq!(fallback.as_ref().map(|f| f.plain_text()), Some("from rtf".to_string()));
|
||||
|
||||
let none = wordcraft_formats::with_shared_conversion_error("html import failed", || {
|
||||
cmd::paste::rich_fragment(&mut s, &json!({"html": "<p>from html</p>"}))
|
||||
});
|
||||
assert!(none.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_and_save_report_format_conversion_errors() {
|
||||
let doc = wordcraft_doc::Document::from_text("hello");
|
||||
wordcraft_formats::with_shared_conversion_error("bridge down", || {
|
||||
for (name, bytes) in [("a.html", b"<p>hello</p>" as &[u8]), ("a.md", b"# hello"), ("a.tex", b"hello")] {
|
||||
let err = crate::io::open_bytes(name, bytes).unwrap_err();
|
||||
assert!(err.contains("bridge down"), "{name}: {err}");
|
||||
}
|
||||
for name in ["a.html", "a.md", "a.tex", "a.rtf"] {
|
||||
let err = crate::io::save_bytes(name, &doc).unwrap_err();
|
||||
assert!(err.contains("bridge down"), "{name}: {err}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -226,6 +226,27 @@ fn arrow_keys_move_visually_in_rtl_text() {
|
||||
assert_eq!(s.sel.focus.off, b.off);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrow_keys_skip_hidden_deletions_in_rtl_text() {
|
||||
let text = "אבגדה";
|
||||
let mut s = session(text, true);
|
||||
run(&mut s, "review.trackChanges", json!({"value": true}));
|
||||
run(&mut s, "select.text", json!({"text": "בגד"}));
|
||||
run(&mut s, "text.delete", json!({}));
|
||||
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
|
||||
|
||||
for (command, from, to, direction) in [("caret.left", 0, text.len(), -1.0), ("caret.right", text.len(), 0, 1.0)] {
|
||||
s.sel = crate::Selection::caret(Pos::body(0, from));
|
||||
for _ in 0..2 {
|
||||
let before = caret_x(&mut s);
|
||||
run(&mut s, command, json!({}));
|
||||
assert!((caret_x(&mut s) - before) * direction > 0.01, "{command} moves to the next visual stop");
|
||||
assert!(s.sel.focus.off <= "א".len() || s.sel.focus.off >= "אבגד".len());
|
||||
}
|
||||
assert_eq!(s.sel.focus.off, to);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrow_keys_in_mixed_text_visit_each_position() {
|
||||
// A left-to-right paragraph with a Persian word: Right walks across the screen.
|
||||
|
||||
@@ -179,34 +179,57 @@ fn fit_one_page_respects_max_delta() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_respects_step_pt() {
|
||||
let at_11_4 = |lines: usize| {
|
||||
let mut s = create_multiline_doc(lines);
|
||||
let set_size = |s: &mut Session, size_pt: f32| {
|
||||
for b in &mut s.doc.body {
|
||||
if let wordcraft_doc::Block::Para(p) = std::sync::Arc::make_mut(b) {
|
||||
p.mark.size = Some(11.4);
|
||||
p.mark.size = Some(size_pt);
|
||||
for r in &mut p.runs {
|
||||
r.props.size = Some(11.4);
|
||||
r.props.size = Some(size_pt);
|
||||
}
|
||||
}
|
||||
}
|
||||
s.touch();
|
||||
s.relayout();
|
||||
};
|
||||
let at_size = |lines: usize, size_pt: f32| {
|
||||
let mut s = create_multiline_doc(lines);
|
||||
set_size(&mut s, size_pt);
|
||||
s
|
||||
};
|
||||
let mut s = just_spilling(at_11_4);
|
||||
|
||||
// Find the most lines that fit on one page at 11.4 pt, spill the last paragraph at 11.1 pt
|
||||
// so 0.1..0.3 pt reductions are not enough, then restore 11.4 pt so fitting requires 0.4 pt.
|
||||
let mut lines = 10;
|
||||
while at_size(lines + 1, 11.4).layout().pages.len() < 2 {
|
||||
lines += 1;
|
||||
assert!(lines < 120, "{lines} lines still fit on one page at 11.4 pt");
|
||||
}
|
||||
let mut s = at_size(lines, 11.1);
|
||||
assert_eq!(s.layout().pages.len(), 1, "{lines} lines must fit on one page at 11.1 pt");
|
||||
spill_last_paragraph(&mut s);
|
||||
set_size(&mut s, 11.4);
|
||||
assert_eq!(s.layout().pages.len(), 2, "must start as 2-page document at 11.4 pt");
|
||||
assert_fixture_font(&mut s);
|
||||
|
||||
// Both calls hold maxDeltaPt constant at 0.4 and disable spacing adjustments.
|
||||
// Hold maxDeltaPt constant at 0.4 and disable spacing adjustments.
|
||||
// Default 0.5 pt step generates no candidates <= 0.4 pt, so it must fail.
|
||||
let doc_backup = s.doc.clone();
|
||||
let default_res = s.run("layout.fitOnePage", &json!({"maxDeltaPt": 0.4, "adjustSpacing": false}));
|
||||
assert!(default_res.is_err(), "default step 0.5 must skip all candidates when maxDelta is 0.4");
|
||||
|
||||
// With stepPt = 0.1 under the same maxDeltaPt = 0.4, a fine-grained step (0.1 to 0.4 pt) succeeds.
|
||||
// With stepPt = 0.1 and maxDeltaPt = 0.3, the document still spills onto page 2.
|
||||
s.doc = doc_backup.clone();
|
||||
s.touch();
|
||||
let too_small_res = s.run("layout.fitOnePage", &json!({"maxDeltaPt": 0.3, "stepPt": 0.1, "adjustSpacing": false}));
|
||||
assert!(too_small_res.is_err(), "0.3 pt cap must not recover a document needing 0.4 pt");
|
||||
|
||||
// With stepPt = 0.1 under maxDeltaPt = 0.4, the 0.4 pt boundary step (11.4 -> 11.0 pt) succeeds.
|
||||
s.doc = doc_backup;
|
||||
s.touch();
|
||||
let res = s.run("layout.fitOnePage", &json!({"maxDeltaPt": 0.4, "stepPt": 0.1, "adjustSpacing": false}));
|
||||
assert!(res.is_ok(), "stepPt=0.1 must generate fine-grained candidates under maxDelta 0.4: {res:?}");
|
||||
assert!(res.is_ok(), "stepPt=0.1 must reach the 0.4 pt boundary step under maxDelta 0.4: {res:?}");
|
||||
assert_eq!(s.layout().pages.len(), 1);
|
||||
assert!(s.status.contains("font: -0.4 pt"), "expected 0.4 pt reduction in status, got: {}", s.status);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -2407,6 +2407,57 @@ fn arrow(s: &mut Session, key: &str) {
|
||||
run(s, id, if extend { json!({"extend": true}) } else { json!({}) });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrow_keys_skip_wholly_deleted_paragraphs_in_no_markup() {
|
||||
for (text, last) in [("AB\nCD\nEF", 2), ("AB\nCD\nDE\nEF", 3)] {
|
||||
let mut s = typed(text);
|
||||
let after_a = Pos::body(0, 1);
|
||||
let before_f = Pos::body(last, 1);
|
||||
run(&mut s, "review.trackChanges", json!({"value": true}));
|
||||
run(&mut s, "select.range", json!({"anchor": after_a, "focus": before_f}));
|
||||
run(&mut s, "text.delete", json!({}));
|
||||
for i in 1..last {
|
||||
let middle = s.doc.para_at(&Pos::body(i, 0)).unwrap();
|
||||
assert!(middle.mark.del.is_some() && middle.runs.iter().all(|r| r.props.del.is_some()));
|
||||
}
|
||||
|
||||
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
|
||||
for (from, key, shift, across, next) in [
|
||||
(after_a.clone(), "Right", "Shift+Right", Pos::body(last, 0), Pos::body(last, 2)),
|
||||
(before_f.clone(), "Left", "Shift+Left", Pos::body(0, 2), Pos::body(0, 0)),
|
||||
] {
|
||||
run(&mut s, "caret.set", json!({"pos": from}));
|
||||
arrow(&mut s, shift);
|
||||
assert_eq!((&s.sel.anchor, &s.sel.focus), (&from, &across));
|
||||
run(&mut s, "caret.set", json!({"pos": from}));
|
||||
arrow(&mut s, key);
|
||||
assert!(s.sel.is_collapsed());
|
||||
assert_eq!(s.sel.focus, across);
|
||||
arrow(&mut s, key);
|
||||
assert_eq!(s.sel.focus, next);
|
||||
}
|
||||
|
||||
run(&mut s, "review.markup", json!({"value": "allMarkup"}));
|
||||
run(&mut s, "review.trackingOptions", json!({"balloons": "inline"}));
|
||||
for (from, key, expected) in [(Pos::body(0, 2), "Right", Pos::body(1, 0)), (Pos::body(last, 0), "Left", Pos::body(last - 1, 2))] {
|
||||
run(&mut s, "caret.set", json!({"pos": from}));
|
||||
arrow(&mut s, key);
|
||||
assert_eq!(s.sel.focus, expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrow_keys_stop_in_a_visible_empty_paragraph_in_no_markup() {
|
||||
let mut s = typed("AB\n\nEF");
|
||||
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
|
||||
for (from, key) in [(Pos::body(0, 2), "Right"), (Pos::body(2, 0), "Left")] {
|
||||
run(&mut s, "caret.set", json!({"pos": from}));
|
||||
arrow(&mut s, key);
|
||||
assert_eq!(s.sel.focus, Pos::body(1, 0));
|
||||
}
|
||||
}
|
||||
|
||||
/// The equation being edited and the caret in it.
|
||||
fn editing(s: &Session) -> Option<(Pos, wordcraft_doc::math_edit::MathPos)> {
|
||||
s.math.as_ref().map(|m| (m.at.clone(), m.pos.clone()))
|
||||
@@ -2471,6 +2522,63 @@ fn left_and_right_keys_step_into_and_out_of_an_equation() {
|
||||
assert_eq!((editing(&s), s.sel.anchor.clone(), s.sel.focus.clone()), (None, Pos::body(0, 1), Pos::body(0, 1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrow_keys_skip_a_deleted_equation_in_no_markup() {
|
||||
let mut s = equations_between_a_and_b(1);
|
||||
let before = Pos::body(0, 1);
|
||||
let after = Pos::body(0, 1 + wordcraft_doc::para::OBJ.len_utf8());
|
||||
run(&mut s, "review.trackChanges", json!({"value": true}));
|
||||
run(&mut s, "select.range", json!({"anchor": before, "focus": after}));
|
||||
run(&mut s, "text.delete", json!({}));
|
||||
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
|
||||
|
||||
let end = Pos::body(0, after.off + 1);
|
||||
for (from, key, expected) in [(before, "Right", end), (after, "Left", Pos::body(0, 0))] {
|
||||
run(&mut s, "caret.set", json!({"pos": from}));
|
||||
arrow(&mut s, key);
|
||||
assert!(editing(&s).is_none(), "{key} must not open a hidden equation");
|
||||
assert_eq!(s.sel.focus, expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrow_keys_enter_a_visible_equation_across_a_hidden_deletion() {
|
||||
use wordcraft_doc::math_edit::{MathPos, units};
|
||||
|
||||
let equation_width = wordcraft_doc::para::OBJ.len_utf8();
|
||||
let before = "a".len();
|
||||
let after = "aé".len();
|
||||
let end = MathPos::new(Vec::new(), units(&wordcraft_doc::math::parse_linear("x+y")));
|
||||
for markup in ["noMarkup", "allMarkup"] {
|
||||
for (key, shift_key, equation, from, across, math_pos) in [
|
||||
("Right", "Shift+Right", after, before, after + equation_width, MathPos::default()),
|
||||
("Left", "Shift+Left", before, after + equation_width, before, end.clone()),
|
||||
] {
|
||||
let mut s = typed("aéb");
|
||||
let from = Pos::body(0, from);
|
||||
let equation = Pos::body(0, equation);
|
||||
run(&mut s, "caret.set", json!({"pos": equation}));
|
||||
run(&mut s, "insert.equation", json!({"linear": "x+y", "edit": false}));
|
||||
run(&mut s, "review.trackChanges", json!({"value": true}));
|
||||
run(&mut s, "select.text", json!({"text": "é"}));
|
||||
run(&mut s, "text.delete", json!({}));
|
||||
run(&mut s, "review.markup", json!({"value": markup}));
|
||||
if markup == "allMarkup" {
|
||||
run(&mut s, "review.trackingOptions", json!({"balloons": "inline", "deleteMark": "hidden"}));
|
||||
}
|
||||
|
||||
run(&mut s, "caret.set", json!({"pos": from}));
|
||||
arrow(&mut s, shift_key);
|
||||
assert!(editing(&s).is_none(), "{shift_key} extends the selection");
|
||||
assert_eq!((s.sel.anchor.clone(), s.sel.focus.clone()), (from.clone(), Pos::body(0, across)));
|
||||
|
||||
run(&mut s, "caret.set", json!({"pos": from}));
|
||||
arrow(&mut s, key);
|
||||
assert_eq!(editing(&s), Some((equation, math_pos)), "{key} with {markup}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn right_out_of_an_equation_steps_into_the_one_beside_it() {
|
||||
let e = wordcraft_doc::para::OBJ.len_utf8();
|
||||
@@ -3465,11 +3573,11 @@ fn autocorrect_capitalisation_follows_turkic_case_mapping() {
|
||||
fn change_case_follows_turkic_case_mapping() {
|
||||
for tag in ["tr-TR", "az-AZ", "crh"] {
|
||||
for (mode, input, want) in [
|
||||
("upper", "istanbul", "İSTANBUL"),
|
||||
("lower", "IŞIK", "ışık"),
|
||||
("title", "istanbul güzel", "İstanbul Güzel"),
|
||||
("sentence", "istanbul. izmir", "İstanbul. İzmir"),
|
||||
("toggle", "iI", "İı"),
|
||||
("upper", "istanbul ışık", "İSTANBUL IŞIK"),
|
||||
("lower", "İSTANBUL IŞIK", "istanbul ışık"),
|
||||
("title", "istanbul ışık", "İstanbul Işık"),
|
||||
("sentence", "istanbul. izmir. ışık.", "İstanbul. İzmir. Işık."),
|
||||
("toggle", "iIİı", "İıiI"),
|
||||
] {
|
||||
let mut s = s();
|
||||
run(&mut s, "review.language", json!({"lang": tag, "default": true}));
|
||||
@@ -3486,17 +3594,20 @@ fn change_case_follows_turkic_case_mapping() {
|
||||
run(&mut s, "format.changeCase", json!({"mode": "title"}));
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "Istanbul", "en-US");
|
||||
// Mixed runs: each run's own language decides.
|
||||
let mut s = self::s();
|
||||
run(&mut s, "text.insert", json!({"text": "IŞIK IŞIK", "raw": true}));
|
||||
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 0)}));
|
||||
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 5), "extend": true}));
|
||||
run(&mut s, "review.language", json!({"lang": "tr-TR"}));
|
||||
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 6)}));
|
||||
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 11), "extend": true}));
|
||||
run(&mut s, "review.language", json!({"lang": "en-US"}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "lower"}));
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "ışık işik", "mixed runs");
|
||||
for (mode, first, second, want) in [
|
||||
("lower", "IŞIK ", "IŞIK", "ışık işik"),
|
||||
("title", "istanbul ", "istanbul", "İstanbul Istanbul"),
|
||||
("upper", "istanbul ", "istanbul", "İSTANBUL ISTANBUL"),
|
||||
] {
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "tr-TR"}));
|
||||
run(&mut s, "text.insert", json!({"text": first, "raw": true}));
|
||||
run(&mut s, "review.language", json!({"lang": "en-US"}));
|
||||
run(&mut s, "text.insert", json!({"text": second, "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": mode}));
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), want, "mixed runs {mode}");
|
||||
}
|
||||
}
|
||||
|
||||
// Spelling as you type (#1552): the word being typed gets no red squiggle until the caret leaves
|
||||
|
||||
@@ -183,18 +183,6 @@ fn german_date_fields_inherit_the_document_default_language() {
|
||||
}
|
||||
}
|
||||
|
||||
/// `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]
|
||||
@@ -207,27 +195,6 @@ fn a_german_time_field_uses_german_names() {
|
||||
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> {
|
||||
|
||||
@@ -9,8 +9,10 @@ description = "WordCraft import/export: plain text, Markdown, HTML, RTF, OpenDoc
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
# `sheet::xls_fixture`, the binary workbook builder other crates' tests share; turned on only as a
|
||||
# dev-dependency, so never built into the app.
|
||||
# Test helpers shared with other crates: `sheet::xls_fixture` (binary workbook builder via
|
||||
# `craft-xls/test-support`) and `with_shared_conversion_error` / `with_shared_conversion_error_after`,
|
||||
# which wire thread-local forced-failure hooks into `to_shared` and `from_shared`. Never enable
|
||||
# outside dev-dependencies, so those hooks are never built into the app.
|
||||
test-support = ["craft-xls/test-support"]
|
||||
|
||||
[dependencies]
|
||||
|
||||
@@ -28,17 +28,76 @@ use wordcraft_doc::Document;
|
||||
/// (`wordcraft_docx::package::MAX_ENTRIES`); checked before `zip` parses them (#3660).
|
||||
pub const MAX_ZIP_ENTRIES: u64 = 20_000;
|
||||
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
thread_local! {
|
||||
/// `(skip, repeat, message)`: when `Some`, lets `skip` calls to `to_shared` / `from_shared`
|
||||
/// run normally, then fails the next call with `message` (and every subsequent call when
|
||||
/// `repeat` is `true`).
|
||||
static SHARED_ERROR: std::cell::Cell<Option<(usize, bool, &'static str)>> = const { std::cell::Cell::new(None) };
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
fn take_shared_error() -> Option<String> {
|
||||
SHARED_ERROR.with(|slot| {
|
||||
let (skip, repeat, msg) = slot.get()?;
|
||||
if skip > 0 {
|
||||
slot.set(Some((skip - 1, repeat, msg)));
|
||||
None
|
||||
} else {
|
||||
if !repeat {
|
||||
slot.set(None);
|
||||
}
|
||||
Some(msg.to_string())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
fn with_shared_error_state<T>(state: Option<(usize, bool, &'static str)>, f: impl FnOnce() -> T) -> T {
|
||||
struct Reset(Option<(usize, bool, &'static str)>);
|
||||
impl Drop for Reset {
|
||||
fn drop(&mut self) {
|
||||
SHARED_ERROR.with(|slot| slot.set(self.0));
|
||||
}
|
||||
}
|
||||
let prev = SHARED_ERROR.with(|slot| slot.replace(state));
|
||||
let _reset = Reset(prev);
|
||||
f()
|
||||
}
|
||||
|
||||
/// Simulates a `to_shared` / `from_shared` conversion failure for every call inside `f`.
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
#[doc(hidden)]
|
||||
pub fn with_shared_conversion_error<T>(msg: &'static str, f: impl FnOnce() -> T) -> T {
|
||||
with_shared_error_state(Some((0, true, msg)), f)
|
||||
}
|
||||
|
||||
/// Lets `skip` `to_shared` / `from_shared` conversions run normally, then fails the next one once.
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
#[doc(hidden)]
|
||||
pub fn with_shared_conversion_error_after<T>(skip: usize, msg: &'static str, f: impl FnOnce() -> T) -> T {
|
||||
with_shared_error_state(Some((skip, false, msg)), f)
|
||||
}
|
||||
|
||||
/// The document as the shared model the format crates read and write.
|
||||
///
|
||||
/// A conversion that fails is an error, never an empty document or an empty file: the caller
|
||||
/// says so instead of writing a file with nothing in it.
|
||||
pub(crate) fn to_shared(doc: &Document) -> Result<craft_wordmodel::Document, String> {
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
if let Some(err) = take_shared_error() {
|
||||
return Err(err);
|
||||
}
|
||||
wordcraft_docx::to_shared_model(doc).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// The shared model as the app's document model. A conversion that fails is an error, never
|
||||
/// an empty document.
|
||||
pub(crate) fn from_shared(shared: craft_wordmodel::Document) -> Result<Document, String> {
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
if let Some(err) = take_shared_error() {
|
||||
return Err(err);
|
||||
}
|
||||
wordcraft_docx::from_shared_model(shared).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
|
||||
@@ -338,6 +338,74 @@ fn a_format_that_cannot_be_read_is_an_error_not_a_blank_document() {
|
||||
assert!(e.contains("RTF"), "{e}");
|
||||
}
|
||||
|
||||
/// Every HTML, Markdown, LaTeX, RTF and MHT importer and exporter propagates `to_shared` /
|
||||
/// `from_shared` errors instead of falling back to an empty document or empty string.
|
||||
#[test]
|
||||
fn shared_conversion_errors_propagate_through_all_formats_without_empty_fallback() {
|
||||
let doc = sample();
|
||||
let page = wordcraft_doc::SectionProps::default();
|
||||
let mht_bytes = b"MIME-Version: 1.0\r\nContent-Type: multipart/related; boundary=\"b\"\r\n\r\n--b\r\nContent-Type: text/html\r\n\r\n<p>hello</p>\r\n--b--\r\n";
|
||||
let msg = "simulated shared conversion failure";
|
||||
let assert_err = |res: Result<String, String>, label: &str| {
|
||||
let e = res.unwrap_err();
|
||||
assert!(e.contains(msg), "{label}: {e}");
|
||||
};
|
||||
|
||||
crate::with_shared_conversion_error(msg, || {
|
||||
assert_err(crate::html::import("<p>hello</p>").map(|_| String::new()), "html::import");
|
||||
assert_err(crate::html::import_page("<p>hello</p>", &|_| None).map(|_| String::new()), "html::import_page");
|
||||
assert_err(crate::html::import_with("<p>hello</p>", &|_| None).map(|_| String::new()), "html::import_with");
|
||||
assert_err(crate::html::import_on("<p>hello</p>", &|_| None, &page).map(|_| String::new()), "html::import_on (section)");
|
||||
assert_err(crate::html::export(&doc), "html::export");
|
||||
assert_err(crate::html::export_fragment(&doc), "html::export_fragment");
|
||||
|
||||
assert_err(crate::markdown::import("hello").map(|_| String::new()), "markdown::import");
|
||||
assert_err(crate::markdown::import_on("hello", &page).map(|_| String::new()), "markdown::import_on (section)");
|
||||
assert_err(crate::markdown::import_on_with_lines("hello", &page).map(|_| String::new()), "markdown::import_on_with_lines (section)");
|
||||
assert_err(crate::markdown::export(&doc), "markdown::export");
|
||||
|
||||
assert_err(crate::latex::import(b"hello").map(|_| String::new()), "latex::import");
|
||||
assert_err(crate::latex::import_on(b"hello", &page).map(|_| String::new()), "latex::import_on");
|
||||
assert_err(crate::latex::export(&doc), "latex::export");
|
||||
|
||||
assert_err(crate::rtf::import(br"{\rtf1 hello}").map(|_| String::new()), "rtf::import");
|
||||
assert_err(crate::rtf::export(&doc), "rtf::export");
|
||||
|
||||
assert_err(crate::mht::import(mht_bytes).map(|_| String::new()), "mht::import (section)");
|
||||
assert_err(crate::mht::import_on(mht_bytes, &page).map(|_| String::new()), "mht::import_on (section)");
|
||||
|
||||
for (ext, bytes) in [("html", b"<p>hello</p>" as &[u8]), ("md", b"hello"), ("tex", b"hello"), ("rtf", br"{\rtf1 hello}"), ("mht", mht_bytes)]
|
||||
{
|
||||
assert_err(import(ext, bytes).unwrap().map(|_| String::new()), &format!("import({ext})"));
|
||||
assert_err(crate::import_on(ext, bytes, &page).unwrap().map(|_| String::new()), &format!("import_on({ext})"));
|
||||
}
|
||||
for ext in ["html", "md", "tex", "rtf"] {
|
||||
assert_err(export(ext, &doc).unwrap().map(|_| String::new()), &format!("export({ext})"));
|
||||
assert_err(
|
||||
crate::export_with(ext, &doc, &crate::ExportOptions { comments: true }).unwrap().map(|_| String::new()),
|
||||
&format!("export_with({ext})"),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// For `import_on` helpers that first convert `page` via `shared_section`, also verify that
|
||||
// a `from_shared` failure after `shared_section` succeeds still propagates as an error.
|
||||
for (label, res) in [
|
||||
(
|
||||
"html::import_on (from_shared)",
|
||||
crate::with_shared_conversion_error_after(1, msg, || crate::html::import_on("<p>hello</p>", &|_| None, &page)),
|
||||
),
|
||||
("markdown::import_on (from_shared)", crate::with_shared_conversion_error_after(1, msg, || crate::markdown::import_on("hello", &page))),
|
||||
(
|
||||
"markdown::import_on_with_lines (from_shared)",
|
||||
crate::with_shared_conversion_error_after(1, msg, || crate::markdown::import_on_with_lines("hello", &page).map(|(d, _)| d)),
|
||||
),
|
||||
("mht::import_on (from_shared)", crate::with_shared_conversion_error_after(1, msg, || crate::mht::import_on(mht_bytes, &page))),
|
||||
] {
|
||||
assert_err(res.map(|_| String::new()), label);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn odt_round_trip() {
|
||||
check_round_trip("odt", true);
|
||||
|
||||
@@ -14,6 +14,7 @@ wordcraft-doc = { workspace = true }
|
||||
wordcraft-fonts = { workspace = true }
|
||||
wordcraft-proof = { workspace = true }
|
||||
craft-metafile = { workspace = true }
|
||||
craft-xml = { workspace = true }
|
||||
kurbo = { workspace = true }
|
||||
unicode-bidi = { workspace = true }
|
||||
unicode-linebreak = { workspace = true }
|
||||
|
||||
+21
-12
@@ -1,6 +1,6 @@
|
||||
use super::ctx::{Ctx, Joining, page_anchored};
|
||||
use super::floats::{
|
||||
ObjFrame, ObjectPlacement, WrapArea, align_in, float_rect, floating, left_out_objects, place_objects, rel_exclusions, wrap_area,
|
||||
AnchoredFloat, ObjFrame, ObjectPlacement, WrapArea, align_in, float_rect, floating, left_out_objects, place_objects, rel_exclusions, wrap_area,
|
||||
};
|
||||
use super::flow::again;
|
||||
use super::page::PageFrame;
|
||||
@@ -160,8 +160,8 @@ fn layout_table_block(input: TableBlockContext<'_, '_, '_>) -> bool {
|
||||
let layout = table::layout_table(ctx, story, t, path, width, depth + 1);
|
||||
let (tx, ty) = match t.props.float {
|
||||
Some(float) => {
|
||||
let legacy = (ctx.doc.settings.compat_mode < 15).then(|| table::first_cell_left_margin(ctx, t));
|
||||
let (rect, area) = box_float_table_rect(frame, width, *y, &layout, &float, legacy, float_tables);
|
||||
let place = FloatPlace { shift: table::float_offset_shift(ctx, t), modern: ctx.doc.settings.compat_mode >= 15 };
|
||||
let (rect, area) = box_float_table_rect(frame, width, *y, &layout, &float, place, float_tables);
|
||||
exclusions.push((area, false, None, WrapText::BothSides, true));
|
||||
float_tables.push(area);
|
||||
table_areas.push(area);
|
||||
@@ -361,9 +361,9 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
|
||||
let outline = ctx.wrap_outline(o);
|
||||
excl.extend(wrap_area(r, float, outline.as_deref().map(Vec::as_slice)));
|
||||
}
|
||||
floats.insert(oi, r);
|
||||
floats.insert(oi, AnchoredFloat::new(r));
|
||||
}
|
||||
let rel = rel_exclusions(&excl, 0.0, y);
|
||||
let rel = rel_exclusions(&excl, 0.0, y, applied);
|
||||
if !rel.is_empty() {
|
||||
pl = ctx.para_labelled(p, width, table, &rel, applied, label);
|
||||
}
|
||||
@@ -525,17 +525,25 @@ pub(crate) struct BoxLayout {
|
||||
pub(crate) last_top: f32,
|
||||
}
|
||||
|
||||
/// How a floating table placed by an offset stands from it.
|
||||
#[derive(Clone, Copy)]
|
||||
struct FloatPlace {
|
||||
/// How far left of the offset its edge stands ([`table::float_offset_shift`]).
|
||||
shift: f32,
|
||||
/// Word 2013 layout (compatibility mode 15).
|
||||
modern: bool,
|
||||
}
|
||||
|
||||
/// Where floating table `tl` goes in a box `width` wide whose next paragraph starts at `y`, and
|
||||
/// the area text keeps clear of. Positions relative to the page or its margins need the box's
|
||||
/// `frame`; without one (a table cell) they're relative to the box. `legacy` is the first cell's
|
||||
/// left margin before Word 2013 layout, `None` in it.
|
||||
/// `frame`; without one (a table cell) they're relative to the box.
|
||||
fn box_float_table_rect(
|
||||
frame: Option<PageFrame>,
|
||||
width: f32,
|
||||
y: f32,
|
||||
tl: &table::TableLayout,
|
||||
f: &TableFloat,
|
||||
legacy: Option<f32>,
|
||||
place: FloatPlace,
|
||||
float_tables: &[Rect],
|
||||
) -> (Rect, Rect) {
|
||||
let h = tl.rows.iter().map(|r| r.height).sum::<f32>().clamp(0.0, 100_000.0);
|
||||
@@ -571,8 +579,8 @@ fn box_float_table_rect(
|
||||
};
|
||||
// Nor is there an area to align in: the table starts where the text is.
|
||||
let v_align = if frame.is_none() && matches!(f.v_rel, Anchor::Page | Anchor::Margin) { None } else { f.v_align };
|
||||
let x = align_in(h_area, f.x, w, PageFrame::h_align(frame.as_ref(), f.h_align)) - if f.h_align.is_none() { legacy.unwrap_or(0.0) } else { 0.0 };
|
||||
let r = clear_of_float_tables(Rect::new(x, align_in(v_area, y_off, h, v_align), w, h), f, legacy.is_none(), h_area.0, float_tables);
|
||||
let x = align_in(h_area, f.x, w, PageFrame::h_align(frame.as_ref(), f.h_align)) - if f.h_align.is_none() { place.shift } else { 0.0 };
|
||||
let r = clear_of_float_tables(Rect::new(x, align_in(v_area, y_off, h, v_align), w, h), f, place.modern, h_area.0 - place.shift, float_tables);
|
||||
let [dl, dt, dr, db] = f.dist_from_text();
|
||||
(r, r.inset(-dl, -dt, -dr, -db))
|
||||
}
|
||||
@@ -827,8 +835,9 @@ 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.
|
||||
/// it, it runs right to left, or it is a text frame placed apart (`frames` and `cell_frame`
|
||||
/// both hold, sharing no line; in a table cell, only frames anchored to `"text"`): without
|
||||
/// its space before, as [`Joint::fit`] lays it out.
|
||||
fn take_up(
|
||||
self,
|
||||
ctx: &mut Ctx,
|
||||
|
||||
@@ -152,6 +152,11 @@ 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);
|
||||
// Theme fonts affect East Asian slot resolution (when `font_ea_theme` is set).
|
||||
doc.settings.major_font.hash(&mut h);
|
||||
doc.settings.minor_font.hash(&mut h);
|
||||
doc.passthrough.get("wordcraft:theme.fonts").hash(&mut h);
|
||||
doc.passthrough.get("wordcraft:settings.orig").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);
|
||||
|
||||
+84
-23
@@ -219,8 +219,10 @@ pub(crate) fn wrap_area(r: Rect, float: &Float, outline: Option<&[(f32, f32)]>)
|
||||
Some((Rect::new(r.x - side, r.y - top, r.w + side * 2.0, r.h + top + bottom), float.wrap == Wrap::TopAndBottom, None, float.wrap_text, false))
|
||||
}
|
||||
|
||||
/// Wrap areas relative to a paragraph whose column starts at `x0` and whose top is `y0`.
|
||||
pub(crate) fn rel_exclusions(excl: &[WrapArea], x0: f32, y0: f32) -> Vec<para::Exclusion> {
|
||||
/// Wrap areas relative to a paragraph whose column starts at `x0` and whose top is `y0`, with
|
||||
/// `space_before` the space before it that the flow laid out above it.
|
||||
pub(crate) fn rel_exclusions(excl: &[WrapArea], x0: f32, y0: f32, space_before: f32) -> Vec<para::Exclusion> {
|
||||
let before = if space_before > 0.0 { space_before } else { 0.0 };
|
||||
excl.iter()
|
||||
.map(|(r, tb, c, side, table)| para::Exclusion {
|
||||
top: r.y - y0,
|
||||
@@ -232,10 +234,11 @@ pub(crate) fn rel_exclusions(excl: &[WrapArea], x0: f32, y0: f32) -> Vec<para::E
|
||||
side: *side,
|
||||
table: *table,
|
||||
})
|
||||
// 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)
|
||||
// Top-and-Bottom areas ending within the paragraph's applied space before can still take
|
||||
// room, with that space laid out again below them (#7143). Any ending at or above it
|
||||
// (like side-wrapping areas above the first line) cannot reach the paragraph and is
|
||||
// dropped so paragraphs below keep empty exclusions and hit the cache (#8613).
|
||||
.filter(|e| e.bottom > 0.0 || (e.top_bottom && e.bottom > -before))
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -346,7 +349,7 @@ pub(crate) fn anchor_floats(
|
||||
pb: &mut PageBuilder,
|
||||
anchor: FloatAnchor,
|
||||
force: &[usize],
|
||||
) -> (HashMap<usize, Rect>, Arc<ParaLayout>, Vec<para::Exclusion>, Vec<usize>) {
|
||||
) -> (HashMap<usize, AnchoredFloat>, Arc<ParaLayout>, Vec<para::Exclusion>, Vec<usize>) {
|
||||
let FloatAnchor { p, block, y0, place, .. } = anchor;
|
||||
ctx.fields.page = pb.number;
|
||||
// Each layout of it here counts its automatic equation numbers from the same place.
|
||||
@@ -468,18 +471,32 @@ pub(crate) fn anchor_lines(p: &Paragraph, pl: &ParaLayout) -> Vec<Option<usize>>
|
||||
out
|
||||
}
|
||||
|
||||
/// A float placed before its paragraph's objects are drawn.
|
||||
pub(crate) struct AnchoredFloat {
|
||||
rect: Rect,
|
||||
/// The origin used when the float was placed again from the pushed first line.
|
||||
pushed_origin: Option<f32>,
|
||||
}
|
||||
|
||||
impl AnchoredFloat {
|
||||
pub(crate) fn new(rect: Rect) -> Self {
|
||||
Self { rect, pushed_origin: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// [`anchor_floats`], leaving out the floats in `late` (in order).
|
||||
fn anchor_floats_but(
|
||||
ctx: &mut Ctx,
|
||||
pb: &mut PageBuilder,
|
||||
anchor: FloatAnchor,
|
||||
late: &[usize],
|
||||
) -> (HashMap<usize, Rect>, Arc<ParaLayout>, Vec<para::Exclusion>) {
|
||||
) -> (HashMap<usize, AnchoredFloat>, Arc<ParaLayout>, Vec<para::Exclusion>) {
|
||||
let FloatAnchor { p, block, y0, before, excl_mark, label, place } = anchor;
|
||||
ctx.fields.page = pb.number;
|
||||
ctx.fields.page_format = pb.page_format;
|
||||
let (col_x, width) = (pb.col_x(), pb.col_w());
|
||||
let mut rects = HashMap::new();
|
||||
let mut areas = HashMap::new();
|
||||
if !pb.web && place {
|
||||
// (A mark from a page before may be short of the areas this page started with.)
|
||||
pb.excl.truncate(excl_mark.max(pb.seeded));
|
||||
@@ -511,25 +528,68 @@ fn anchor_floats_but(
|
||||
let seed = early.and_then(|v| v.iter().find(|(b, k, _)| (*b, *k) == (block, oi))).map(|(_, _, a)| a);
|
||||
(r, area) = settle_early(r, area, seed, top, |r| wrap_area(r, float, outline));
|
||||
}
|
||||
rects.insert(oi, r);
|
||||
rects.insert(oi, AnchoredFloat::new(r));
|
||||
// Above the paragraph, beside text laid out before it: the page is laid out again
|
||||
// with it known from the start (#2048).
|
||||
let above = area.as_ref().filter(|a| text_before && a.0.y < top - 0.5).map(|a| (page, a.clone()));
|
||||
ctx.floats_above.insert((block, oi), above);
|
||||
if let Some(area) = area {
|
||||
match early.and_then(|v| v.iter().position(|(b, k, _)| (*b, *k) == (block, oi))).filter(|k| *k < pb.seeded) {
|
||||
let slot = if let Some(area) = area {
|
||||
let b = area.0.bottom();
|
||||
let k = match early.and_then(|v| v.iter().position(|(b, k, _)| (*b, *k) == (block, oi))).filter(|k| *k < pb.seeded) {
|
||||
Some(k) => {
|
||||
if let Some(slot) = pb.excl.get_mut(k) {
|
||||
*slot = area;
|
||||
}
|
||||
k
|
||||
}
|
||||
None => pb.excl.push(area),
|
||||
None => {
|
||||
let k = pb.excl.len();
|
||||
pb.excl.push(area);
|
||||
k
|
||||
}
|
||||
};
|
||||
Some((k, b))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
areas.insert(oi, slot);
|
||||
}
|
||||
}
|
||||
let rel = rel_exclusions(&body_wraps(ctx, pb), col_x, y0, before);
|
||||
let pl = ctx.para_labelled(p, width, None, &rel, before, label.clone());
|
||||
let lead = pl.lines.first().map_or(0.0, |l| l.top.max(0.0));
|
||||
if !pb.web && place && lead > 0.0 {
|
||||
let page = pb.pages.len().saturating_sub(1);
|
||||
let top = y0 - before;
|
||||
let text_before = top > pb.top + 0.5 || pb.col > 0;
|
||||
let frame = PageFrame { sect: pb.sect, margin_top: None, origin: (0.0, 0.0), number: pb.number, mirror: ctx.mirror };
|
||||
for (oi, o) in p.objects.iter().enumerate() {
|
||||
let Some((_, _, float)) = floating(o) else { continue };
|
||||
let Some(&area) = areas.get(&oi) else { continue };
|
||||
let Some(placed) = rects.get_mut(&oi) else { continue };
|
||||
let r = placed.rect;
|
||||
if float.y < 0.0 && area.map_or(r.bottom(), |(_, b)| b) < y0 + lead - 0.5 {
|
||||
// Only down: across it stays where it was placed (`settle_early` may have moved it).
|
||||
let moved = Rect { y: float_rect(Some(frame), (col_x, width), top + lead, r.w, r.h, float).y, ..r };
|
||||
// A wrap area moved onto the first line would cover text laid out without it.
|
||||
if area.is_some_and(|(_, b)| b + (moved.y - r.y) > y0 + lead - 0.5) {
|
||||
continue;
|
||||
}
|
||||
placed.rect = moved;
|
||||
placed.pushed_origin = match float.v_rel {
|
||||
Anchor::Page | Anchor::Margin | Anchor::TopMargin | Anchor::BottomMargin | Anchor::InsideMargin | Anchor::OutsideMargin => None,
|
||||
_ => Some(top + lead),
|
||||
};
|
||||
if let Some((k, _)) = area
|
||||
&& let Some(slot) = pb.excl.get_mut(k)
|
||||
{
|
||||
slot.0.y += moved.y - r.y;
|
||||
let above = (text_before && slot.0.y < top - 0.5).then(|| (page, slot.clone()));
|
||||
ctx.floats_above.insert((block, oi), above);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let rel = rel_exclusions(&body_wraps(ctx, pb), col_x, y0);
|
||||
let pl = ctx.para_labelled(p, width, None, &rel, before, label.clone());
|
||||
(rects, pl, rel)
|
||||
}
|
||||
|
||||
@@ -696,7 +756,7 @@ pub(crate) struct ObjectPlacement<'a> {
|
||||
pub lines: (usize, usize),
|
||||
pub origin: (f32, f32),
|
||||
pub at: &'a ObjFrame<'a>,
|
||||
pub floats: &'a HashMap<usize, Rect>,
|
||||
pub floats: &'a HashMap<usize, AnchoredFloat>,
|
||||
pub depth: usize,
|
||||
}
|
||||
|
||||
@@ -756,22 +816,23 @@ pub(crate) fn place_objects(ctx: &mut Ctx, req: &ObjectPlacement) -> (Vec<Placed
|
||||
continue;
|
||||
}
|
||||
let pinned = at.pinned.and_then(|m| m.get(&oi)).copied().filter(|_| floating);
|
||||
let rect = if let Some(r) = pinned {
|
||||
r
|
||||
let (rect, origin_y) = if let Some(r) = pinned {
|
||||
(r, at.para_y)
|
||||
} else if let Some(l) = late_here {
|
||||
l.rect
|
||||
(l.rect, l.top)
|
||||
} else if floating {
|
||||
match floats.get(&oi) {
|
||||
Some(r) => *r,
|
||||
Some(placed) => (placed.rect, placed.pushed_origin.unwrap_or(at.para_y)),
|
||||
None => {
|
||||
let h = ctx.float_height(obj, w, h);
|
||||
float_rect(at.page, at.col, at.para_y, w, h, float)
|
||||
(float_rect(at.page, at.col, at.para_y, w, h, float), at.para_y)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let cx = x + line.cl_left(k).unwrap_or(0.0);
|
||||
let modern = ctx.doc.settings.compat_mode >= wordcraft_doc::COMPAT_MODE_CURRENT;
|
||||
display::inline_rect(Some(obj), cx, y + (line.baseline - fl.top), c.adv, (c.obj_h, c.obj_d), pl.rule_room(line, k), modern)
|
||||
let r = display::inline_rect(Some(obj), cx, y + (line.baseline - fl.top), c.adv, (c.obj_h, c.obj_d), pl.rule_room(line, k), modern);
|
||||
(r, at.para_y)
|
||||
};
|
||||
let (mut behind, mut front) = (Vec::new(), Vec::new());
|
||||
let layer = if float.wrap == Wrap::BehindText { &mut behind } else { &mut front };
|
||||
@@ -818,7 +879,7 @@ pub(crate) fn place_objects(ctx: &mut Ctx, req: &ObjectPlacement) -> (Vec<Placed
|
||||
off: c.start,
|
||||
text_box: shown,
|
||||
wrap: float.wrap,
|
||||
origin: Point::new(at.col.0, late_here.map_or(at.para_y, |l| l.top)),
|
||||
origin: Point::new(at.col.0, origin_y),
|
||||
group_boxes,
|
||||
});
|
||||
for (id, rect) in boxes {
|
||||
@@ -864,7 +925,7 @@ pub(crate) fn place_objects(ctx: &mut Ctx, req: &ObjectPlacement) -> (Vec<Placed
|
||||
/// touch its lines and are left out.
|
||||
pub(crate) fn continued_exclusions(rel: &[para::Exclusion], excl: &[WrapArea], x0: f32, y: f32, t: f32, width: f32) -> Vec<para::Exclusion> {
|
||||
let before = rel.iter().filter(|e| e.top < t).map(|e| para::Exclusion { bottom: e.bottom.min(t), ..e.clone() });
|
||||
let here = rel_exclusions(excl, x0, y - t)
|
||||
let here = rel_exclusions(excl, x0, y - t, 0.0)
|
||||
.into_iter()
|
||||
.filter(|e| e.bottom > t && e.right > -width && e.left < 2.0 * width)
|
||||
.map(|e| if e.top < t && e.contour.is_none() { para::Exclusion { top: t, ..e } } else { e });
|
||||
|
||||
@@ -2,16 +2,16 @@ use super::boxes::{BoxInput, BoxLayout, Edges, Joint, frame_float, joined, layou
|
||||
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, float_rect, late_floats,
|
||||
place_late, place_objects, wrap_area,
|
||||
AnchoredFloat, 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};
|
||||
use super::placed::Placed;
|
||||
use super::table_flow::table_start_need;
|
||||
use super::{
|
||||
Arc, Block, Counters, Document, HashMap, InlineObject, Level, LineEnd, Page, ParaLayout, Paragraph, Path, Rect, StoryRef, TextDirection,
|
||||
ViewMode, outline, para,
|
||||
Arc, Block, Counters, Document, HashMap, InlineObject, Level, LineEnd, Page, ParaLayout, Paragraph, Path, StoryRef, TextDirection, ViewMode,
|
||||
outline, para,
|
||||
};
|
||||
#[cfg(test)]
|
||||
use crate::WRAP_RELAYS;
|
||||
@@ -279,7 +279,7 @@ struct Flow<'a> {
|
||||
excl_mark: usize,
|
||||
/// Where its automatic equation numbers start: each layout of it again counts from here.
|
||||
eq_start: u32,
|
||||
float_rects: HashMap<usize, Rect>,
|
||||
float_rects: HashMap<usize, AnchoredFloat>,
|
||||
pl: Arc<ParaLayout>,
|
||||
rel: Vec<para::Exclusion>,
|
||||
/// The page its fields were laid out for, and the width.
|
||||
@@ -652,6 +652,39 @@ impl<'a> Flow<'a> {
|
||||
true
|
||||
}
|
||||
|
||||
/// Keep with next for the end of a paragraph begun in an earlier column (#6829): in columns
|
||||
/// being balanced, the piece holding its last line must leave room below for the next
|
||||
/// paragraph to start (as [`Self::keep_together`] asks of a paragraph's start), or its last
|
||||
/// lines (two under widow/orphan control) go over with that paragraph, as in Word. All of
|
||||
/// them going over returns `l0`, and the caller moves on even from a column's top: the
|
||||
/// balancing pass then runs onto another page and the columns are tried taller. Nothing
|
||||
/// moves in the full-height pass that is the balancing's fallback, nor when the paragraph's
|
||||
/// tail and the next paragraph's start could not fit a full column.
|
||||
fn kept_tail_end(&self, ctx: &mut Ctx, pb: &PageBuilder, rooms: Rooms, fit: &Fit) -> usize {
|
||||
let (rp, n, l0) = (&self.pl.rp, self.n(), self.l0);
|
||||
// Not in the full-height fallback pass, which must keep the original layout.
|
||||
let column = pb.uncapped_bottom() - pb.top;
|
||||
let balancing = pb.balance.is_some_and(|(page, h)| page + 1 == pb.pages.len() && h + 0.01 < column);
|
||||
if l0 == 0 || fit.l1 < n || fit.forced.is_some() || !rp.keep_next || !balancing || pb.web {
|
||||
return fit.l1;
|
||||
}
|
||||
let (Some(first), Some(last)) = (self.pl.lines.get(l0), self.pl.lines.last()) else { return fit.l1 };
|
||||
let tail = last.top + last.height - first.top + rooms.bottom;
|
||||
let need = tail
|
||||
+ gap_after(ctx, self.block, rp, self.label.is_some())
|
||||
+ next_first_line(ctx, self.block, self.width, 0, pb.next_starts_page, &mut ctx.counters.clone());
|
||||
// A need no column can hold is left alone, as `keep_together` leaves it.
|
||||
if pb.y + need <= pb.bottom + 0.01 || need > column + 0.01 {
|
||||
return fit.l1;
|
||||
}
|
||||
let mut l1 = n.saturating_sub(if rp.widow_control { 2 } else { 1 }).max(l0);
|
||||
// A row (text both sides of a floating object) stays together (`settled_end`).
|
||||
while l1 > l0 && self.pl.lines.get(l1).is_some_and(|l| l.beside) {
|
||||
l1 -= 1;
|
||||
}
|
||||
l1
|
||||
}
|
||||
|
||||
/// The end of the lines on this page after widow/orphan control, and keeping the rows beside
|
||||
/// floating objects together.
|
||||
/// Also says whether, balancing from Word 2013's layout, widow/orphan control alone moved every
|
||||
@@ -1079,8 +1112,11 @@ fn place_para_in_flow(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block:
|
||||
let lead = if f.l0 == 0 { first.top.max(0.0) + rooms.top } else { 0.0 };
|
||||
let notes = para_notes(ctx.doc, p, &f.pl);
|
||||
let mut fit = f.fit_lines(ctx, pb, ¬es, lead);
|
||||
let (end, widowed) = f.settled_end(ctx, pb, &fit);
|
||||
fit.l1 = end;
|
||||
let (settled, widowed) = f.settled_end(ctx, pb, &fit);
|
||||
fit.l1 = settled;
|
||||
fit.l1 = f.kept_tail_end(ctx, pb, rooms, &fit);
|
||||
let kept_over = fit.l1 < settled;
|
||||
let end = fit.l1;
|
||||
// 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 && f.fresh(pb) && !widowed;
|
||||
@@ -1091,8 +1127,9 @@ fn place_para_in_flow(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block:
|
||||
// Balancing: widow/orphan control moved all the lines that fit on to the next column
|
||||
// (or, short of room, the page after, which fails the try), where the lines of a
|
||||
// column's first paragraph would otherwise overflow it. Lines pushed back for a row
|
||||
// beside a floating object keep the overflow as before.
|
||||
if !overflow {
|
||||
// beside a floating object keep the overflow as before. A paragraph's tail kept with
|
||||
// the next one (`kept_tail_end`) moves on even from a column's top.
|
||||
if !overflow || kept_over {
|
||||
f.move_on(ctx, pb);
|
||||
continue;
|
||||
}
|
||||
@@ -1226,6 +1263,24 @@ fn space_after_kept(ctx: &Ctx, block: usize, rp: &wordcraft_doc::resolve::Resolv
|
||||
after
|
||||
}
|
||||
|
||||
/// The room the space after body paragraph `block` adds between it and the paragraph after it,
|
||||
/// beyond that paragraph's own space before (which [`next_first_line`] counts): the merged gap
|
||||
/// (the larger of the two, ISO/IEC 29500-1 §17.3.1.9), or both when they are summed. Nothing when
|
||||
/// contextual spacing or automatic spacing between list items drops it.
|
||||
fn gap_after(ctx: &Ctx, block: usize, rp: &wordcraft_doc::resolve::ResolvedPara, listed: bool) -> f32 {
|
||||
let after = space_after_kept(ctx, block, rp, listed);
|
||||
if after <= 0.0 {
|
||||
return 0.0;
|
||||
}
|
||||
let Some(Block::Para(next)) = ctx.doc.body.get(block + 1).map(|b| &**b) else { return after };
|
||||
let nrp = ctx.doc.styles.resolve_para(&next.props);
|
||||
// The next paragraph's contextual spacing, and automatic spacing between two list items,
|
||||
// drop its own space before.
|
||||
let dropped = (nrp.style == rp.style && nrp.contextual_spacing) || (listed && nrp.before_auto && ctx.has_label(next));
|
||||
let before = if dropped { 0.0 } else { nrp.space_before.max(0.0) };
|
||||
if ctx.doc.settings.sum_paragraph_spacing { after } else { (after - before).max(0.0) }
|
||||
}
|
||||
|
||||
/// The room the paragraphs after `block` need on the page for keep with next: enough of the
|
||||
/// next one to start there — its first line, two of its lines with widow/orphan control (it
|
||||
/// doesn't leave a single line at the bottom of a page; it moves over whole instead), all three
|
||||
@@ -1312,6 +1367,7 @@ mod tests {
|
||||
use wordcraft_doc::Pos;
|
||||
use wordcraft_doc::para::{Anchor, Float, LINE_BREAK, Wrap, WrapText};
|
||||
use wordcraft_doc::props::LineSpacing;
|
||||
use wordcraft_geom::Rect;
|
||||
|
||||
#[test]
|
||||
fn strict_balancing_remeasures_kept_lines_in_the_next_column() {
|
||||
|
||||
@@ -40,8 +40,9 @@ pub(crate) fn section_side(start: SectionStart, restart: Option<u32>, last: u32,
|
||||
/// 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).
|
||||
/// on; the case where its first paragraph begins on `prev` and runs over is treated the same way
|
||||
/// (inferred, not measured separately in Word). `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;
|
||||
|
||||
@@ -1025,6 +1025,12 @@ impl DocLayout {
|
||||
let here = para.x_of(li, pos.off)?;
|
||||
let mut best: Option<(usize, f32)> = None;
|
||||
for (off, x) in para.line_carets(li) {
|
||||
// Omitted runs retain byte offsets as zero-width markers. Keep their
|
||||
// visible edges as candidates without placing the caret inside a run.
|
||||
let span = para.left_out.partition_point(|range| range.end <= off);
|
||||
if para.left_out.get(span).is_some_and(|range| range.start < off) {
|
||||
continue;
|
||||
}
|
||||
let Some(x) = x else { continue };
|
||||
let ahead = if left { x < here - 0.01 } else { x > here + 0.01 };
|
||||
let d = (x - here).abs();
|
||||
|
||||
@@ -155,8 +155,9 @@ impl<'a> Builder<'a> {
|
||||
_ => wordcraft_fonts::FontDb::global().fallback_styled(dc, primary.id(), bold, italic).map(|f| FaceRef::of(&f)),
|
||||
};
|
||||
// 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.
|
||||
// that character's size, even when the run's font already draws the mark, so the two
|
||||
// stay in one shaping run, can compose or position together, and match their cluster
|
||||
// whole (#7865, #8571).
|
||||
let small = match cur {
|
||||
Some(k) if mark => k.small,
|
||||
_ => rc.small_caps && !rc.caps && c.is_lowercase(),
|
||||
@@ -346,13 +347,15 @@ impl<'a> Builder<'a> {
|
||||
(resolved.face, resolved.substituted || !family.eq_ignore_ascii_case(&r.font))
|
||||
});
|
||||
let primary_cs = resolved_cs.map(|(face, _)| face);
|
||||
// Chinese, Japanese and Korean characters use the run's East Asian font (`w:eastAsia`) when
|
||||
// it, or the font table alternate it is drawn in (#2702), is installed and has them.
|
||||
let wanted_ea = rc.font_ea.as_deref().filter(|f| !f.eq_ignore_ascii_case(&rc.font) && text.chars().any(east_asian)).map(|f| {
|
||||
let family = lookup_family(self.env.doc, f);
|
||||
let resolved = wordcraft_fonts::word::resolve(family, rc.bold, rc.italic);
|
||||
(f, resolved, resolved.substituted || !family.eq_ignore_ascii_case(f))
|
||||
});
|
||||
// Chinese, Japanese and Korean characters use the run's East Asian font (`w:eastAsiaTheme`
|
||||
// over `w:eastAsia`) when it, or the font table alternate it is drawn in (#2702), is
|
||||
// installed and has them.
|
||||
let wanted_ea =
|
||||
super::chars::east_asian_font(self.env.doc, rc).filter(|f| !f.eq_ignore_ascii_case(&rc.font) && text.chars().any(east_asian)).map(|f| {
|
||||
let family = lookup_family(self.env.doc, f);
|
||||
let resolved = wordcraft_fonts::word::resolve(family, rc.bold, rc.italic);
|
||||
(f, resolved, resolved.substituted || !family.eq_ignore_ascii_case(f))
|
||||
});
|
||||
let primary_ea = wanted_ea.filter(|(_, r, _)| !r.substituted).map(|(_, r, _)| r.face);
|
||||
// The levels by byte of `text`, from `lbase` on.
|
||||
let (levels, lbase): (&[u8], usize) = match dir {
|
||||
@@ -581,6 +584,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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -213,6 +213,62 @@ pub fn substitute_face(doc: &Document, font: &str) -> Option<FaceRef> {
|
||||
(r.substituted || family != font).then_some(r.face)
|
||||
}
|
||||
|
||||
const THEME_FONTS_PASSTHROUGH: &str = "wordcraft:theme.fonts";
|
||||
|
||||
/// The theme's East Asian face, falling back to its per-script font for the settings'
|
||||
/// East Asian theme language when the main `a:ea` face is empty.
|
||||
fn theme_ea_face(doc: &Document, major: bool) -> Option<&str> {
|
||||
let text = std::str::from_utf8(doc.passthrough.get(THEME_FONTS_PASSTHROUGH)?).ok()?;
|
||||
let key = if major { "major" } else { "minor" };
|
||||
let find = |kind: &str, which: &str| {
|
||||
text.lines().find_map(|line| {
|
||||
let mut parts = line.splitn(4, '\t');
|
||||
let (k, t, w, face) = (parts.next()?, parts.next()?, parts.next()?, parts.next()?);
|
||||
(k == key && t == kind && w == which && !face.trim().is_empty()).then_some(face)
|
||||
})
|
||||
};
|
||||
find("face", "ea").or_else(|| {
|
||||
let settings = craft_xml::parse(doc.passthrough.get("wordcraft:settings.orig")?).ok()?;
|
||||
let lang = settings.child(craft_xml::Local("themeFontLang"))?.attr_local("eastAsia")?;
|
||||
find("script", theme_ea_script(lang)?)
|
||||
})
|
||||
}
|
||||
|
||||
/// The East Asian scripts used by theme font entries. An explicit script takes precedence
|
||||
/// over the language's usual script, including Traditional Chinese outside Taiwan/Hong Kong.
|
||||
fn theme_ea_script(lang: &str) -> Option<&'static str> {
|
||||
let mut parts = lang.trim().split(['-', '_']);
|
||||
let language = parts.next()?;
|
||||
let rest: Vec<_> = parts.collect();
|
||||
if let Some(script) = rest.iter().find_map(|p| ["Hans", "Hant", "Jpan", "Hang"].into_iter().find(|s| s.eq_ignore_ascii_case(p))) {
|
||||
return Some(script);
|
||||
}
|
||||
if language.eq_ignore_ascii_case("ja") {
|
||||
Some("Jpan")
|
||||
} else if language.eq_ignore_ascii_case("ko") {
|
||||
Some("Hang")
|
||||
} else if language.eq_ignore_ascii_case("zh") {
|
||||
Some(if rest.iter().any(|p| ["TW", "HK", "MO"].iter().any(|r| r.eq_ignore_ascii_case(p))) { "Hant" } else { "Hans" })
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// The East Asian font effective for a run (`w:eastAsiaTheme` takes precedence over `w:eastAsia`,
|
||||
/// including an inherited `w:eastAsia`). Returns `None` when none is named or the theme slot
|
||||
/// points to an East Asian theme font with neither a main face nor a matching per-script face.
|
||||
pub(super) fn east_asian_font<'a>(doc: &'a Document, rc: &'a ResolvedChar) -> Option<&'a str> {
|
||||
use wordcraft_doc::props::ThemeFont;
|
||||
match rc.font_ea_theme {
|
||||
Some(ThemeFont::MajorEastAsia) => theme_ea_face(doc, true),
|
||||
Some(ThemeFont::MinorEastAsia) => theme_ea_face(doc, false),
|
||||
Some(ThemeFont::MajorAscii | ThemeFont::MajorHAnsi) => Some(doc.settings.major_font.as_str()).filter(|f| !f.trim().is_empty()),
|
||||
Some(ThemeFont::MinorAscii | ThemeFont::MinorHAnsi) => Some(doc.settings.minor_font.as_str()).filter(|f| !f.trim().is_empty()),
|
||||
Some(ThemeFont::MajorBidi | ThemeFont::MinorBidi) => None,
|
||||
None => rc.font_ea.as_deref().filter(|f| !f.trim().is_empty()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The face Chinese, Japanese and Korean text is drawn in when its East Asian font (`w:eastAsia`)
|
||||
/// `font_ea` isn't installed and the run's font is `font`; `None` when `font_ea` is installed. As
|
||||
/// layout draws it: an East Asian font is looked up by name alone (the roman-font rule of
|
||||
|
||||
@@ -70,6 +70,8 @@ pub(super) fn snap_chars(b: &mut Builder, text: &str, grid: &Grid) {
|
||||
g.dx += shift;
|
||||
}
|
||||
c.adv = adv;
|
||||
// The snapped advance no longer includes the shaped kerning adjustment.
|
||||
c.kern = 0.0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,14 +101,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 +131,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 +152,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
|
||||
}
|
||||
|
||||
@@ -61,6 +61,9 @@ struct Breaker<'e> {
|
||||
i: usize,
|
||||
top: f32,
|
||||
first: bool,
|
||||
/// Whether `[top - space_before, top]` holds laid-out space before (initially and after a
|
||||
/// Top-and-Bottom push), rather than a span cleared past a side-wrapping object (#8614, #8687).
|
||||
space_band: bool,
|
||||
/// The rest of the current row: spans on the far side of floating objects, left to right.
|
||||
row_rest: VecDeque<(f32, f32)>,
|
||||
row_first: usize,
|
||||
@@ -232,6 +235,7 @@ impl<'e> Breaker<'e> {
|
||||
i: 0,
|
||||
top: 0.0,
|
||||
first: true,
|
||||
space_band: true,
|
||||
row_rest: VecDeque::new(),
|
||||
row_first: 0,
|
||||
skipped: 0,
|
||||
@@ -268,13 +272,13 @@ impl<'e> Breaker<'e> {
|
||||
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 {
|
||||
// laid out again under it (#7143). Look `space_before` above `self.top` initially and
|
||||
// after a Top-and-Bottom push so stacked Top-and-Bottom objects re-apply `space_before`
|
||||
// too (#8687), but not after a side-wrapping push (`row_spans` or `skip_row`), where
|
||||
// the span above `self.top` was cleared past a side-wrapping object (#8614).
|
||||
if self.first && self.space_band && self.space_before > 0.0 {
|
||||
let before = self.space_before;
|
||||
let row = (self.top - before, self.est_h + before, self.table_h);
|
||||
let row = (self.top - before, self.est_h + before, self.table_h + before);
|
||||
if let Some(below) = self
|
||||
.exclusions
|
||||
.iter()
|
||||
@@ -282,8 +286,12 @@ impl<'e> Breaker<'e> {
|
||||
.filter(|e| e.intersects_row(row.0, row.1, row.2, lo, self.base_right))
|
||||
.map(|e| e.bottom)
|
||||
.reduce(f32::max)
|
||||
&& below + before > self.top
|
||||
&& guard < 50
|
||||
{
|
||||
self.top = self.top.max(below + before);
|
||||
self.top = below + before;
|
||||
guard += 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let row = (self.top, self.est_h, self.table_h);
|
||||
@@ -298,6 +306,7 @@ impl<'e> Breaker<'e> {
|
||||
}
|
||||
Err(below) if below > self.top && guard < 50 => {
|
||||
self.top = below;
|
||||
self.space_band = false;
|
||||
guard += 1;
|
||||
}
|
||||
Ok((None, _)) | Err(_) => {
|
||||
@@ -379,6 +388,7 @@ impl<'e> Breaker<'e> {
|
||||
self.top + even_row(self.lines.get_mut(self.row_first..).unwrap_or_default())
|
||||
} else {
|
||||
// Nothing on this row: go below the first object that ends, as when no span is wide enough.
|
||||
self.space_band = false;
|
||||
self.exclusions
|
||||
.iter()
|
||||
.filter(|e| e.intersects_row(self.top, self.est_h, self.table_h, sc.row_lo, self.base_right))
|
||||
@@ -392,7 +402,8 @@ impl<'e> Breaker<'e> {
|
||||
/// Returns how it ends.
|
||||
fn close_line(&mut self, pl: &mut ParaLayout, mut sc: Scan) -> LineEnd {
|
||||
if sc.end == LineEnd::Para || sc.end == LineEnd::Wrap {
|
||||
let xc = sc.x;
|
||||
let kern = if sc.end == LineEnd::Wrap && sc.j > sc.c0 { line_end_kern(pl, sc.j - 1) } else { 0.0 };
|
||||
let xc = sc.x - kern;
|
||||
resolve_tab(pl, &mut sc.pending_tab, &mut sc.xs, sc.c0, xc, &mut sc.x);
|
||||
}
|
||||
if sc.j >= self.n && sc.end != LineEnd::Wrap && !matches!(sc.end, LineEnd::LineBreak | LineEnd::PageBreak | LineEnd::ColumnBreak) {
|
||||
@@ -454,8 +465,8 @@ impl<'e> Breaker<'e> {
|
||||
let hyphen = (sc.end == LineEnd::Wrap && c1 > c0 && pl.hyph_after.binary_search(&((c1 - 1) as u32)).is_ok())
|
||||
.then(|| pl.clusters.get(c1 - 1).map(|c| hyphen_glyph(pl, c.style, &mut self.hcache)))
|
||||
.flatten();
|
||||
let end_x = match (sc.xs.last(), c1.checked_sub(1).and_then(|k| pl.clusters.get(k))) {
|
||||
(Some(lx), Some(c)) => lx + c.adv + hyphen.map_or(0.0, |h| h.2),
|
||||
let end_x = match (sc.xs.last(), c1.checked_sub(1).and_then(|k| pl.clusters.get(k).map(|c| (k, c)))) {
|
||||
(Some(lx), Some((k, c))) => lx + c.adv - line_end_kern(pl, k) + hyphen.map_or(0.0, |h| h.2),
|
||||
_ => sc.line_start_x,
|
||||
};
|
||||
sc.xs.push(end_x);
|
||||
@@ -951,11 +962,9 @@ impl Scan {
|
||||
self.x += w;
|
||||
}
|
||||
_ => {
|
||||
// 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)
|
||||
{
|
||||
// Its room grows from nothing with its text (a tab moved on from the line before
|
||||
// may still hold the width it had there).
|
||||
if let Some(c) = pl.clusters.get_mut(j) {
|
||||
c.adv = 0.0;
|
||||
}
|
||||
self.pending_tab = Some((j, stop, self.x));
|
||||
@@ -1096,7 +1105,7 @@ impl Scan {
|
||||
self.word_from = if c.kind == ClKind::Space { self.x - c.adv } else { self.x };
|
||||
} else if self.hyph_ok
|
||||
&& !pl.clusters.get(j + 1).is_some_and(|n| n.kind == ClKind::Text && n.g1 <= n.g0)
|
||||
&& self.x + hyphen_glyph(pl, c.style, &mut bk.hcache).2 <= self.right_edge + shrink + 0.01
|
||||
&& self.x - line_end_kern(pl, j) + hyphen_glyph(pl, c.style, &mut bk.hcache).2 <= self.right_edge + shrink + 0.01
|
||||
{
|
||||
self.last_break = Some(j);
|
||||
}
|
||||
|
||||
@@ -306,6 +306,7 @@ impl<'a> Shaped<'a> {
|
||||
big.font = f.clone();
|
||||
big.font_cs = f.clone();
|
||||
big.font_ea = Some(f.clone());
|
||||
big.font_ea_theme = None;
|
||||
}
|
||||
let before = self.b.clusters.len();
|
||||
self.b.shape(first, 0, &Arc::new(big), None);
|
||||
@@ -663,6 +664,22 @@ fn shown_text(cx: &Cx) -> Option<String> {
|
||||
Some(shown)
|
||||
}
|
||||
|
||||
/// Each run's end byte and the installed East Asian font (`w:eastAsiaTheme` over `w:eastAsia`)
|
||||
/// it resolves to, `None` when none is resolved or it 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 = super::chars::east_asian_font(cx.env.doc, &rc).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)]
|
||||
@@ -698,7 +715,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());
|
||||
|
||||
+29
-10
@@ -333,9 +333,26 @@ pub fn autofit_widths(cols: &[(f32, f32)], avail: f32) -> Vec<f32> {
|
||||
cols.iter().map(|c| c.0 + (c.1 - c.0) * k).collect()
|
||||
}
|
||||
|
||||
/// The first cell's left margin: how far its text sits inside the table's edge.
|
||||
pub(crate) fn first_cell_left_margin(ctx: &Ctx, t: &Table) -> f32 {
|
||||
first_cell_left_margin_in(t, default_margins(t, table_style(ctx, t).as_ref()))
|
||||
/// How far left of its offset (`w:tblpX`) a floating table placed by one has its edge. Before
|
||||
/// Word 2013 layout the first cell's text is at the offset, moved by the table's indent; from it
|
||||
/// the edge is, moved in by half its left border, the indent ignored (measured in Word for
|
||||
/// Windows).
|
||||
pub(crate) fn float_offset_shift(ctx: &Ctx, t: &Table) -> f32 {
|
||||
let style = table_style(ctx, t);
|
||||
if ctx.doc.settings.compat_mode < 15 {
|
||||
first_cell_left_margin_in(t, default_margins(t, style.as_ref())) - t.props.indent.unwrap_or(0.0)
|
||||
} else {
|
||||
-half_edge_border(t, &table_borders(t, style.as_ref()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Half the left border of a table's first cell, which Word (from mode 15) moves the table in by:
|
||||
/// the cell's own border, else its row's `w:tblPrEx`, else the table's (`borders`, with its style's).
|
||||
fn half_edge_border(t: &Table, borders: &Borders) -> f32 {
|
||||
let row = t.rows.first();
|
||||
let own = row.and_then(|r| r.cells.first()).and_then(|c| c.props.borders.and_then(|b| b.left));
|
||||
let exception = row.and_then(|r| r.props.exceptions.as_ref()).and_then(|e| e.borders).and_then(|b| b.left);
|
||||
own.or(exception).or(borders.left).filter(Border::is_visible).map_or(0.0, |b| b.width.clamp(0.0, 12.0) / 2.0)
|
||||
}
|
||||
|
||||
fn first_cell_left_margin_in(t: &Table, def: [f32; 4]) -> f32 {
|
||||
@@ -575,17 +592,15 @@ fn table_frame(ctx: &mut Ctx, t: &Table, avail: f32, depth: usize, style: Option
|
||||
let margins_def = default_margins(t, style);
|
||||
let indent = t.props.indent.unwrap_or(0.0);
|
||||
let tborders = table_borders(t, style);
|
||||
let first_cell = t.rows.first().and_then(|r| r.cells.first());
|
||||
// A right-to-left table (`w:bidiVisual`) mirrors: its first column stands at the right, its
|
||||
// start alignment and indent are measured from the right margin, and each cell's start
|
||||
// (left) margin and border are on its right.
|
||||
// (left) border is drawn on its right (cell margins stay on the sides they name).
|
||||
let rtl = t.props.bidi_visual;
|
||||
// How far in from the start margin the table's edge sits when it is start-aligned.
|
||||
let start_offset = if ctx.doc.settings.compat_mode >= 15 {
|
||||
// The border is centred on the edge, so half of it sits outside: Word moves the table in
|
||||
// by that half.
|
||||
let border = first_cell.and_then(|c| c.props.borders.and_then(|b| b.left)).or(tborders.left);
|
||||
indent + border.filter(Border::is_visible).map_or(0.0, |b| b.width.clamp(0.0, 12.0) / 2.0)
|
||||
indent + half_edge_border(t, &tborders)
|
||||
} else {
|
||||
indent - first_cell_left_margin_in(t, margins_def)
|
||||
};
|
||||
@@ -753,9 +768,13 @@ fn layout_table_rows(ctx: &mut Ctx, story: StoryRef, t: &Table, path: &[u32], av
|
||||
} else if turn.is_turned() {
|
||||
collapsed = false;
|
||||
// Turned text: its lines run along the cell's height. An exact row height sets
|
||||
// their length, and a minimum height does when the lines fit across the column;
|
||||
// otherwise they get the length the text needs unwrapped and the row grows to fit
|
||||
// (the second pass lays them out again if the row ends up taller).
|
||||
// their length, and a minimum height (`AtLeast`, or the combined minimum of a
|
||||
// vertical merge) does when the lines fit across the column; otherwise they get
|
||||
// the length the text needs unwrapped and the row grows to fit (the second pass
|
||||
// lays them out again if the row ends up taller). Checked in Word (#6528): in an
|
||||
// "At least" row, turned text wraps to the minimum height instead of growing the
|
||||
// row, and a word longer than that minimum runs past the row (tested at 0.3 cm)
|
||||
// without growing it.
|
||||
let snap = (ctx.counters.clone(), ctx.eq_count);
|
||||
let merged = merged_min_height(t, ri, g);
|
||||
let preferred = merged.or(row.props.height.filter(|h| h.is_finite() && *h > 0.0)).map(|h| h.clamp(4.0, TURNED_LIMIT));
|
||||
|
||||
@@ -207,8 +207,9 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc
|
||||
let mut tl = table::layout_table(ctx, StoryRef::Body, t, &[block as u32], width, 1);
|
||||
if let Some(f) = t.props.float.filter(|_| !pb.web) {
|
||||
// Before Word 2013 layout (compatibility mode 15) an offset places the first cell's text,
|
||||
// so the edge sits a cell margin further out.
|
||||
let legacy = if ctx.doc.settings.compat_mode < 15 { table::first_cell_left_margin(ctx, t) } else { 0.0 };
|
||||
// so the edge sits a cell margin further out (and the indent further); from it the edge,
|
||||
// half its border in.
|
||||
let legacy = table::float_offset_shift(ctx, t);
|
||||
let h: f32 = tl.rows.iter().map(|r| r.height).sum();
|
||||
if h <= pb.uncapped_bottom() - pb.top + 0.01 {
|
||||
place_floating_table(ctx, pb, &tl, &f, legacy, block, body_top);
|
||||
@@ -400,11 +401,12 @@ fn place_floating_table(ctx: &mut Ctx, pb: &mut PageBuilder, tl: &table::TableLa
|
||||
let x = float_table_x(pb, w, f, legacy, ctx.mirror);
|
||||
let mut obstacles = if f.overlap { Vec::new() } else { header_table_areas(ctx, pb) };
|
||||
obstacles.extend_from_slice(&pb.float_tables);
|
||||
// Moved below another, it keeps its distance from the text's edge, half its border in.
|
||||
let r = clear_of_float_tables(
|
||||
Rect::new(x, align_in(v_area, f.y, h, f.v_align), w, h),
|
||||
f,
|
||||
ctx.doc.settings.compat_mode >= 15,
|
||||
h_area.0,
|
||||
h_area.0 - legacy,
|
||||
&obstacles,
|
||||
);
|
||||
// Like Word, a table that doesn't fit below the text before it moves to the next page with
|
||||
@@ -485,8 +487,8 @@ fn float_table_h_area(pb: &PageBuilder, f: &TableFloat, mirror: bool) -> (f32, f
|
||||
}
|
||||
}
|
||||
|
||||
/// A floating table's left edge on the page (`legacy`: the first cell's left margin before Word
|
||||
/// 2013 layout, when an offset places the cell's text).
|
||||
/// A floating table's left edge on the page (`legacy`: how far left of an offset its edge stands,
|
||||
/// [`table::float_offset_shift`]).
|
||||
fn float_table_x(pb: &PageBuilder, w: f32, f: &TableFloat, legacy: f32, mirror: bool) -> f32 {
|
||||
let align = PageFrame::h_align(Some(&page_frame(pb, mirror)), f.h_align);
|
||||
let x = align_in(float_table_h_area(pb, f, mirror), f.x, w, align);
|
||||
|
||||
+871
-1
@@ -2058,6 +2058,29 @@ fn right_tab_past_the_right_indent_takes_its_number_up_to_the_stop() {
|
||||
assert!(close > 0, "no entry whose text ends within a digit of the indent");
|
||||
}
|
||||
|
||||
/// A centre tab moved onto the next line with its text starts with no room there, as a right
|
||||
/// tab does: it doesn't keep the width it had on the line before, so the text is centred on the
|
||||
/// stop (#8683).
|
||||
#[test]
|
||||
fn a_centre_tab_moved_to_the_next_line_centres_its_text_on_the_stop() {
|
||||
use wordcraft_doc::props::{TabAlign, TabLeader, TabStop};
|
||||
crate::test_fonts();
|
||||
for n in 74..=83 {
|
||||
let text = format!("{}\tWXYZWXWXYZ1.5", "x".repeat(n));
|
||||
let len = text.chars().count();
|
||||
let mut d = Document::from_text(&text);
|
||||
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| {
|
||||
p.tabs = Some(vec![TabStop { pos: 460.0, align: TabAlign::Center, leader: TabLeader::None }]);
|
||||
})
|
||||
.unwrap();
|
||||
let l = lay(&d);
|
||||
let start = l.caret(&Pos::body(0, n + 1)).unwrap().x;
|
||||
let end = l.caret(&Pos::body(0, len)).unwrap().x;
|
||||
let mid = (start + end) / 2.0;
|
||||
assert!((mid - (72.0 + 460.0)).abs() < 0.5, "n={n}: text after the centre tab is centred at {mid}, expected {}", 72.0 + 460.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// A left tab whose only stop is past the right indent wraps; on the next line it still can't
|
||||
/// reach that stop, so it takes no room there and its text starts at the indent instead of
|
||||
/// going to a line of its own.
|
||||
@@ -3871,6 +3894,51 @@ fn a_text_box_skips_the_min_height_probe_for_turned_text() {
|
||||
assert!(b.h > 80.0, "and so it runs on past the minimum height: {b:?}");
|
||||
}
|
||||
|
||||
/// A single word longer than an at-least row's minimum height (0.3 cm / ~8.5 pt) breaks across
|
||||
/// multiple lines instead of growing the row, and letters wider than that minimum overhang the
|
||||
/// row along its length, as long as the wrapped lines fit across the column.
|
||||
#[test]
|
||||
fn a_word_longer_than_min_height_does_not_grow_an_at_least_row() {
|
||||
use wordcraft_doc::props::HeightRule;
|
||||
crate::test_fonts();
|
||||
let min_h = 8.5;
|
||||
for turn in [TextDirection::Up, TextDirection::Down] {
|
||||
let mut d = Document::from_text("After");
|
||||
let mut t = Table::new(1, 1, 160.0);
|
||||
t.props.style = None;
|
||||
t.rows[0].props.height = Some(min_h);
|
||||
t.rows[0].props.height_rule = HeightRule::AtLeast;
|
||||
t.rows[0].cells[0].props.text_direction = turn;
|
||||
t.rows[0].cells[0].blocks = vec![wordcraft_doc::para_block(Paragraph::with_text("WWWW", Default::default()))];
|
||||
d.insert_block(StoryRef::Body, &Path::top(0), wordcraft_doc::Block::Table(t)).unwrap();
|
||||
let l = lay(&d);
|
||||
let (rect, clip) = l.pages[0]
|
||||
.items
|
||||
.iter()
|
||||
.find_map(|it| match it {
|
||||
Placed::Cell { rect, clip, cell: 0, .. } => Some((*rect, *clip)),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
assert!((rect.h - min_h).abs() < 0.01, "{turn:?}: cell grew past min height {min_h}: {rect:?}");
|
||||
assert!(!clip, "{turn:?}: an at-least row does not clip overflowing text");
|
||||
let (lines, extent) = l.pages[0]
|
||||
.items
|
||||
.iter()
|
||||
.find_map(|it| match it {
|
||||
Placed::Lines { para, l0, l1, path, .. } if path.0 == [0, 0, 0, 0] => {
|
||||
let lines = l1 - l0;
|
||||
let extent = para.lines.get(*l0..*l1).unwrap_or(&[]).iter().filter_map(|line| line.xs.last().copied()).fold(0.0f32, f32::max);
|
||||
Some((lines, extent))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
assert!(lines > 1, "{turn:?}: word should break across multiple lines, got {lines}");
|
||||
assert!(extent > min_h, "{turn:?}: letters should overhang the min height {min_h}, got {extent}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turned_text_wraps_to_merged_rows_height() {
|
||||
use wordcraft_doc::props::{HeightRule, VMerge};
|
||||
@@ -8896,6 +8964,188 @@ fn moved_kept_paragraph_lays_out_no_space_before_under_an_object_at_its_top() {
|
||||
assert!((top - bottom).abs() < 0.01, "the first line {top} starts at the rule's bottom {bottom}, with no space before laid out above it");
|
||||
}
|
||||
|
||||
/// #8614: when a side-wrapping object pushes the first line down before it is placed, the
|
||||
/// space-before Top-and-Bottom band must stay anchored to the first line's original top (0), not
|
||||
/// shift down with `self.top` into the paragraph's area and re-apply `space_before` below a
|
||||
/// Top-and-Bottom object ending there.
|
||||
#[test]
|
||||
fn side_wrapping_push_does_not_shift_space_before_band_into_para_area() {
|
||||
crate::test_fonts();
|
||||
use wordcraft_doc::para::{Anchor, Float, Wrap};
|
||||
use wordcraft_doc::props::LineSpacing;
|
||||
|
||||
const BEFORE: f32 = 12.0;
|
||||
|
||||
let build = |with_top_bottom: bool| {
|
||||
let mut d = Document::from_text("Anchor line.\nProbe line with several words in it.");
|
||||
for block in &mut d.body {
|
||||
if let wordcraft_doc::Block::Para(p) = Arc::make_mut(block) {
|
||||
p.props.space_before = Some(0.0);
|
||||
p.props.space_after = Some(0.0);
|
||||
p.props.line_spacing = Some(LineSpacing::Exactly(14.0));
|
||||
}
|
||||
}
|
||||
if let Some(wordcraft_doc::Block::Para(p)) = d.body.get_mut(1).map(Arc::make_mut) {
|
||||
p.props.space_before = Some(BEFORE);
|
||||
}
|
||||
let plain = lay(&d);
|
||||
let top_of = |l: &DocLayout, block: u32| {
|
||||
l.pages[0]
|
||||
.items
|
||||
.iter()
|
||||
.find_map(|i| match i {
|
||||
Placed::Lines { story: StoryRef::Body, path, y, .. } if path.0 == [block] => Some(*y),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap()
|
||||
};
|
||||
let anchor_y = top_of(&plain, 0);
|
||||
let probe_y = top_of(&plain, 1);
|
||||
|
||||
// Full-width side-wrapping object starting at the probe's original top and extending 30 pt
|
||||
// down, pushing the probe's first line to probe_y + 30.
|
||||
let side = Float { wrap: Wrap::Square, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, y: probe_y - anchor_y, ..Default::default() };
|
||||
d.insert_object(&Pos::body(0, 0), rect_shape(500.0, 30.0, side), &Default::default()).unwrap();
|
||||
|
||||
if with_top_bottom {
|
||||
// Top-and-Bottom object inside the side-wrapped vertical span (18..22 pt below probe_y),
|
||||
// below the original first line [0, 14] and above the Square object's bottom (30).
|
||||
let tb = Float {
|
||||
wrap: Wrap::TopAndBottom,
|
||||
h_rel: Anchor::Column,
|
||||
v_rel: Anchor::Paragraph,
|
||||
y: probe_y + 18.0 - anchor_y,
|
||||
..Default::default()
|
||||
};
|
||||
d.insert_object(&Pos::body(0, 0), rect_shape(144.0, 4.0, tb), &Default::default()).unwrap();
|
||||
}
|
||||
let l = lay(&d);
|
||||
top_of(&l, 1)
|
||||
};
|
||||
|
||||
let plain_wrap_top = build(false);
|
||||
let with_tb_top = build(true);
|
||||
assert!(
|
||||
(with_tb_top - plain_wrap_top).abs() < 0.01,
|
||||
"probe first line {with_tb_top} must stay at plain-wrap position {plain_wrap_top} without re-applying space_before"
|
||||
);
|
||||
}
|
||||
|
||||
/// #8687: when a Top-and-Bottom object pushes the first line down into a second Top-and-Bottom
|
||||
/// object, the paragraph's space before is laid out again below the second object too.
|
||||
#[test]
|
||||
fn stacked_top_and_bottom_objects_reapply_space_before() {
|
||||
crate::test_fonts();
|
||||
use wordcraft_doc::para::{Anchor, Float, Wrap};
|
||||
use wordcraft_doc::props::LineSpacing;
|
||||
|
||||
const BEFORE: f32 = 12.0;
|
||||
|
||||
let mut d = Document::from_text("Anchor line.\nProbe line with several words in it.");
|
||||
for block in &mut d.body {
|
||||
if let wordcraft_doc::Block::Para(p) = Arc::make_mut(block) {
|
||||
p.props.space_before = Some(0.0);
|
||||
p.props.space_after = Some(0.0);
|
||||
p.props.line_spacing = Some(LineSpacing::Exactly(14.0));
|
||||
}
|
||||
}
|
||||
if let Some(wordcraft_doc::Block::Para(p)) = d.body.get_mut(1).map(Arc::make_mut) {
|
||||
p.props.space_before = Some(BEFORE);
|
||||
}
|
||||
let plain = lay(&d);
|
||||
let top_of = |l: &DocLayout, block: u32| {
|
||||
l.pages[0]
|
||||
.items
|
||||
.iter()
|
||||
.find_map(|i| match i {
|
||||
Placed::Lines { story: StoryRef::Body, path, y, .. } if path.0 == [block] => Some(*y),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap()
|
||||
};
|
||||
let anchor_y = top_of(&plain, 0);
|
||||
let probe_y = top_of(&plain, 1);
|
||||
|
||||
// First Top-and-Bottom object ending 5 pt above the probe's original first line (inside its
|
||||
// 12 pt space before), pushing the line down to -5 + 12 = 7..21 pt below probe_y.
|
||||
let first =
|
||||
Float { wrap: Wrap::TopAndBottom, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, y: probe_y - 10.0 - anchor_y, ..Default::default() };
|
||||
d.insert_object(&Pos::body(0, 0), rect_shape(144.0, 5.0, first), &Default::default()).unwrap();
|
||||
|
||||
// Second Top-and-Bottom object from 17 to 27 pt below the probe's original first line,
|
||||
// below the unpushed first line's `est_h` (~15 pt) but reaching into the moved line [7, 21+].
|
||||
let second =
|
||||
Float { wrap: Wrap::TopAndBottom, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, y: probe_y + 17.0 - anchor_y, ..Default::default() };
|
||||
d.insert_object(&Pos::body(0, 0), rect_shape(144.0, 10.0, second), &Default::default()).unwrap();
|
||||
|
||||
let l = lay(&d);
|
||||
let top = top_of(&l, 1);
|
||||
let second_bottom = shapes(&l.pages[0].items).iter().map(|r| r.bottom()).fold(f32::NEG_INFINITY, f32::max);
|
||||
assert!(
|
||||
(top - (second_bottom + BEFORE)).abs() < 0.01,
|
||||
"probe first line {top} must start at second object bottom {second_bottom} + {BEFORE} space before"
|
||||
);
|
||||
}
|
||||
|
||||
/// #8614 / #8687: when a side-wrapping object pushes the first line down into a Top-and-Bottom
|
||||
/// object (via either `row_spans` or `skip_row`), the line moves below it without re-applying
|
||||
/// `space_before`.
|
||||
#[test]
|
||||
fn side_wrapping_push_into_top_and_bottom_does_not_reapply_space_before() {
|
||||
crate::test_fonts();
|
||||
use wordcraft_doc::para::{Anchor, Float, Wrap};
|
||||
use wordcraft_doc::props::LineSpacing;
|
||||
|
||||
const BEFORE: f32 = 12.0;
|
||||
|
||||
// 500 pt leaves no span (`row_spans` Err); 445 pt leaves a ~23 pt strip that `skip_row` skips.
|
||||
for side_width in [500.0, 445.0] {
|
||||
let mut d = Document::from_text("Anchor line.\nProbe line with several words in it.");
|
||||
for block in &mut d.body {
|
||||
if let wordcraft_doc::Block::Para(p) = Arc::make_mut(block) {
|
||||
p.props.space_before = Some(0.0);
|
||||
p.props.space_after = Some(0.0);
|
||||
p.props.line_spacing = Some(LineSpacing::Exactly(14.0));
|
||||
}
|
||||
}
|
||||
if let Some(wordcraft_doc::Block::Para(p)) = d.body.get_mut(1).map(Arc::make_mut) {
|
||||
p.props.space_before = Some(BEFORE);
|
||||
}
|
||||
let plain = lay(&d);
|
||||
let top_of = |l: &DocLayout, block: u32| {
|
||||
l.pages[0]
|
||||
.items
|
||||
.iter()
|
||||
.find_map(|i| match i {
|
||||
Placed::Lines { story: StoryRef::Body, path, y, .. } if path.0 == [block] => Some(*y),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap()
|
||||
};
|
||||
let anchor_y = top_of(&plain, 0);
|
||||
let probe_y = top_of(&plain, 1);
|
||||
|
||||
// Side-wrapping object from 0 to 30 pt below the probe's original first line, pushing the
|
||||
// first line down to [30, 44] below probe_y.
|
||||
let side = Float { wrap: Wrap::Square, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, y: probe_y - anchor_y, ..Default::default() };
|
||||
d.insert_object(&Pos::body(0, 0), rect_shape(side_width, 30.0, side), &Default::default()).unwrap();
|
||||
|
||||
// Top-and-Bottom object from 32 to 36 pt below probe_y: below the original first line
|
||||
// [0, 14] and reaching into the side-wrapped line [30, 44].
|
||||
let tb =
|
||||
Float { wrap: Wrap::TopAndBottom, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, y: probe_y + 32.0 - anchor_y, ..Default::default() };
|
||||
d.insert_object(&Pos::body(0, 0), rect_shape(144.0, 4.0, tb), &Default::default()).unwrap();
|
||||
|
||||
let l = lay(&d);
|
||||
let top = top_of(&l, 1);
|
||||
let tb_bottom = shapes(&l.pages[0].items).iter().map(|r| r.bottom()).fold(f32::NEG_INFINITY, f32::max);
|
||||
assert!(
|
||||
(top - tb_bottom).abs() < 0.01,
|
||||
"side_width={side_width}: probe first line {top} must start at Top-and-Bottom bottom {tb_bottom} without re-applying {BEFORE} space before"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn float_follows_its_paragraph_to_the_next_page() {
|
||||
crate::test_fonts();
|
||||
@@ -10172,7 +10422,6 @@ fn a_line_breaks_after_the_space_of_an_opening_bracket() {
|
||||
assert!(lines.iter().any(|l| l.trim_end().ends_with('(')), "no line ends with the bracket: {lines:?}");
|
||||
}
|
||||
|
||||
/// The lines of the body's first paragraph, as text.
|
||||
/// The text of every laid-out line.
|
||||
fn body_lines(l: &DocLayout, text: &str) -> Vec<String> {
|
||||
l.pages
|
||||
@@ -12858,6 +13107,211 @@ fn columns_before_a_continuous_break_are_balanced() {
|
||||
}
|
||||
}
|
||||
|
||||
/// #6829's case: Letter page, three columns, exact 14 pt lines. 135 one-line filler paragraphs,
|
||||
/// then P (5 lines, kept with the next) with `space_after` after it, then Q, then a section after
|
||||
/// Q starting continuously, so the columns of the section ending at Q are balanced.
|
||||
fn continued_tail_doc(space_after: f32) -> (Document, usize) {
|
||||
use wordcraft_doc::props::LineSpacing;
|
||||
use wordcraft_doc::section::{SectionProps, SectionStart};
|
||||
let lb = wordcraft_doc::para::LINE_BREAK;
|
||||
let filler = 135;
|
||||
let mut text: Vec<String> = (0..filler).map(|i| format!("F{i}")).collect();
|
||||
text.push("P1".into());
|
||||
text.push("Q".into());
|
||||
text.push("After".into());
|
||||
let mut d = Document::from_text(&text.join("\n"));
|
||||
for block in &mut d.body {
|
||||
if let Block::Para(para) = Arc::make_mut(block) {
|
||||
para.props.line_spacing = Some(LineSpacing::Exactly(14.0));
|
||||
para.props.space_before = Some(0.0);
|
||||
para.props.space_after = Some(0.0);
|
||||
}
|
||||
}
|
||||
let p = d.para_mut(StoryRef::Body, &Path::top(filler)).unwrap();
|
||||
p.insert_text(2, &format!("{lb}P2{lb}P3{lb}P4{lb}P5"), &Default::default()).unwrap();
|
||||
p.props.keep_next = Some(true);
|
||||
p.props.space_after = Some(space_after);
|
||||
let mut s = SectionProps::default();
|
||||
s.columns.count = 3;
|
||||
d.para_mut(StoryRef::Body, &Path::top(filler + 1)).unwrap().section = Some(Box::new(s));
|
||||
d.last_section.start = SectionStart::Continuous;
|
||||
(d, filler)
|
||||
}
|
||||
|
||||
/// Body paragraph `block`'s pieces in `l`: (page, x, top, line count).
|
||||
fn pieces_of(l: &DocLayout, block: usize) -> Vec<(usize, f32, f32, usize)> {
|
||||
l.pages
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(pi, pg)| {
|
||||
pg.items.iter().filter_map(move |it| match it {
|
||||
Placed::Lines { story: StoryRef::Body, path, l0, l1, x, y, .. } if path.0[..] == [block as u32] => Some((pi, *x, *y, l1 - l0)),
|
||||
_ => None,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// #6829: in balanced columns, the last lines of a paragraph begun on the page before stay with
|
||||
/// the paragraph after it when the paragraph is kept with the next (Word 16.0, compatibility
|
||||
/// mode 15: three columns, exact 14 pt lines, the tail P4–P5 and Q all in column 1).
|
||||
#[test]
|
||||
fn balanced_columns_keep_a_continued_tail_with_the_next_paragraph() {
|
||||
crate::test_fonts();
|
||||
let (d, filler) = continued_tail_doc(0.0);
|
||||
let l = lay(&d);
|
||||
let pieces = pieces_of(&l, filler);
|
||||
assert_eq!(pieces.len(), 2, "P begins on page 1 and ends on page 2: {pieces:?}");
|
||||
let (tail_page, tail_x, tail_top, tail_lines) = pieces[1];
|
||||
assert_eq!((pieces[0].0, tail_page, tail_lines), (0, 1, 2), "P4 and P5 on page 2: {pieces:?}");
|
||||
let q = para_boxes(&l)[filler + 1];
|
||||
assert_eq!(q.0, 1, "Q on page 2: {q:?}");
|
||||
assert!((q.1 - tail_x).abs() < 0.5, "Q in the column of P4 and P5: Q {q:?}, P {pieces:?}");
|
||||
assert!((q.2 - (tail_top + 28.0)).abs() < 0.5, "Q right under P5: Q {q:?}, P {pieces:?}");
|
||||
}
|
||||
|
||||
/// #6829: the space after the continued paragraph counts too. With 28 pt after P, leaving room
|
||||
/// for P4–P5 and Q's first line alone takes Q past the end of the column, and the tail stays
|
||||
/// behind while Q moves on. The tail must go over with Q, and the columns grow to hold both.
|
||||
#[test]
|
||||
fn balanced_columns_keep_a_continued_tail_with_the_space_after_it() {
|
||||
crate::test_fonts();
|
||||
let (d, filler) = continued_tail_doc(28.0);
|
||||
let l = lay(&d);
|
||||
let pieces = pieces_of(&l, filler);
|
||||
assert_eq!(pieces.len(), 2, "P begins on page 1 and ends on page 2: {pieces:?}");
|
||||
let (tail_page, tail_x, tail_top, tail_lines) = pieces[1];
|
||||
assert_eq!((pieces[0].0, tail_page, tail_lines), (0, 1, 2), "P4 and P5 on page 2: {pieces:?}");
|
||||
let q = para_boxes(&l)[filler + 1];
|
||||
assert_eq!(q.0, 1, "Q on page 2: {q:?}");
|
||||
assert!((q.1 - tail_x).abs() < 0.5, "Q in the column of P4 and P5: Q {q:?}, P {pieces:?}");
|
||||
assert!((q.2 - (tail_top + 28.0 + 28.0)).abs() < 0.5, "Q under P5's space after: Q {q:?}, P {pieces:?}");
|
||||
}
|
||||
|
||||
/// #6829: the lines going over with the next paragraph keep their row together. Text on the far
|
||||
/// side of a floating object is part of the same row (`settled_end`), and the end
|
||||
/// `kept_tail_end` picks must not split it: the whole row goes over with the next paragraph.
|
||||
#[test]
|
||||
fn balanced_columns_keep_a_continued_tail_row_together() {
|
||||
crate::test_fonts();
|
||||
use wordcraft_doc::para::{Anchor, Float, Wrap};
|
||||
use wordcraft_doc::props::LineSpacing;
|
||||
use wordcraft_doc::section::{SectionProps, SectionStart};
|
||||
let lb = wordcraft_doc::para::LINE_BREAK;
|
||||
let filler = 135;
|
||||
let mut text: Vec<String> = (0..filler).map(|i| format!("F{i}")).collect();
|
||||
text.push("P1".into());
|
||||
text.push("Q1".into());
|
||||
text.push("After".into());
|
||||
let mut d = Document::from_text(&text.join("\n"));
|
||||
for block in &mut d.body {
|
||||
if let Block::Para(para) = Arc::make_mut(block) {
|
||||
para.props.line_spacing = Some(LineSpacing::Exactly(14.0));
|
||||
para.props.space_before = Some(0.0);
|
||||
para.props.space_after = Some(0.0);
|
||||
}
|
||||
}
|
||||
let p = d.para_mut(StoryRef::Body, &Path::top(filler)).unwrap();
|
||||
p.insert_text(2, &format!("{lb}P2{lb}P3{lb}word word word word word"), &Default::default()).unwrap();
|
||||
p.props.keep_next = Some(true);
|
||||
let q = d.para_mut(StoryRef::Body, &Path::top(filler + 1)).unwrap();
|
||||
q.insert_text(2, &format!("{lb}Q2{lb}Q3{lb}Q4{lb}Q5"), &Default::default()).unwrap();
|
||||
let mut s = SectionProps::default();
|
||||
s.columns.count = 3;
|
||||
d.para_mut(StoryRef::Body, &Path::top(filler + 1)).unwrap().section = Some(Box::new(s));
|
||||
d.last_section.start = SectionStart::Continuous;
|
||||
// A float in the middle of the column, anchored at P's tail: each of its first rows holds a
|
||||
// word on each side of it.
|
||||
let f = Float { wrap: Wrap::Square, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, x: 36.0, ..Default::default() };
|
||||
d.insert_object(&Pos::body(filler, 9), rect_shape(60.0, 42.0, f), &Default::default()).unwrap();
|
||||
let l = lay(&d);
|
||||
let mut continued = false;
|
||||
let mut row = false;
|
||||
for (pi, pg) in l.pages.iter().enumerate() {
|
||||
for it in &pg.items {
|
||||
let Placed::Lines { story: StoryRef::Body, path, para, l0, l1, .. } = it else { continue };
|
||||
if path.0[..] != [filler as u32] || *l0 == 0 {
|
||||
continue;
|
||||
}
|
||||
continued = true;
|
||||
if pi == 1 {
|
||||
row |= para.lines[*l0..].iter().any(|l| l.beside);
|
||||
}
|
||||
if *l1 < para.lines.len() {
|
||||
assert!(!para.lines[*l1].beside, "a piece ends in the middle of a row: l0 {l0}, l1 {l1} of {}", para.lines.len());
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(continued, "P continues on page 2");
|
||||
assert!(row, "the float splits a row beside the tail on page 2");
|
||||
assert_eq!(para_boxes(&l)[filler + 1].0, 1, "Q on page 2");
|
||||
}
|
||||
|
||||
/// Lines of body paragraph `block` placed in `l`, over all its pieces.
|
||||
fn placed_lines(l: &DocLayout, block: usize) -> usize {
|
||||
pieces_of(l, block).iter().map(|p| p.3).sum()
|
||||
}
|
||||
|
||||
/// #6829: when the tail of a continued paragraph and the next paragraph could never fit one
|
||||
/// column (a 60-line Q kept together), the tail stays where it is: nothing is pushed over to a
|
||||
/// third page and the columns are balanced on page 2 as without the rule.
|
||||
#[test]
|
||||
fn a_continued_tail_that_cannot_fit_with_the_next_paragraph_stays_in_place() {
|
||||
crate::test_fonts();
|
||||
let lb = wordcraft_doc::para::LINE_BREAK;
|
||||
let (mut d, filler) = continued_tail_doc(0.0);
|
||||
let q = d.para_mut(StoryRef::Body, &Path::top(filler + 1)).unwrap();
|
||||
let more: String = (2..=60).map(|i| format!("{lb}Q{i}")).collect();
|
||||
q.insert_text(1, &more, &Default::default()).unwrap();
|
||||
q.props.keep_lines = Some(true);
|
||||
let l = lay(&d);
|
||||
assert_eq!(l.pages.len(), 2, "everything on two pages");
|
||||
assert_eq!(placed_lines(&l, filler), 5, "P is placed whole");
|
||||
assert_eq!(placed_lines(&l, filler + 1), 60, "Q is placed whole");
|
||||
assert!(pieces_of(&l, filler + 1).iter().all(|p| p.0 == 1), "Q on page 2");
|
||||
assert!(pieces_of(&l, filler)[1..].iter().all(|p| p.0 == 1), "P's tail on page 2");
|
||||
}
|
||||
|
||||
/// #6829: when the rule cannot be satisfied at any height, the balancing's fallback (the original
|
||||
/// full-height columns) keeps the original layout and every paragraph is placed: a 49-line
|
||||
/// paragraph kept with the next fills column 1 of page 2, then Q and 91 one-line paragraphs
|
||||
/// fill the page.
|
||||
#[test]
|
||||
fn balancing_fallback_places_every_paragraph() {
|
||||
crate::test_fonts();
|
||||
use wordcraft_doc::props::LineSpacing;
|
||||
use wordcraft_doc::section::{SectionProps, SectionStart};
|
||||
let lb = wordcraft_doc::para::LINE_BREAK;
|
||||
let (filler, after) = (135, 91);
|
||||
let mut text: Vec<String> = (0..filler).map(|i| format!("F{i}")).collect();
|
||||
text.push("P1".into());
|
||||
text.push("Q".into());
|
||||
text.extend((0..after).map(|i| format!("A{i}")));
|
||||
text.push("Next".into());
|
||||
let mut d = Document::from_text(&text.join("\n"));
|
||||
for block in &mut d.body {
|
||||
if let Block::Para(para) = Arc::make_mut(block) {
|
||||
para.props.line_spacing = Some(LineSpacing::Exactly(14.0));
|
||||
para.props.space_before = Some(0.0);
|
||||
para.props.space_after = Some(0.0);
|
||||
}
|
||||
}
|
||||
let p = d.para_mut(StoryRef::Body, &Path::top(filler)).unwrap();
|
||||
let more: String = (2..=49).map(|i| format!("{lb}P{i}")).collect();
|
||||
p.insert_text(2, &more, &Default::default()).unwrap();
|
||||
p.props.keep_next = Some(true);
|
||||
let last = filler + 1 + after;
|
||||
let mut s = SectionProps::default();
|
||||
s.columns.count = 3;
|
||||
d.para_mut(StoryRef::Body, &Path::top(last)).unwrap().section = Some(Box::new(s));
|
||||
d.last_section.start = SectionStart::Continuous;
|
||||
let l = lay(&d);
|
||||
for block in 0..=last + 1 {
|
||||
let want = if block == filler { 49 } else { 1 };
|
||||
assert_eq!(placed_lines(&l, block), want, "block {block} is placed");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn columns_before_a_page_break_or_a_column_break_are_not_balanced() {
|
||||
crate::test_fonts();
|
||||
@@ -18305,6 +18759,186 @@ fn continuous_section_first_paragraph_running_over_keeps_first_page_header_hidde
|
||||
assert!(l.pages[next..].iter().all(|p| p.hf_slot == crate::HfSlot::Default));
|
||||
}
|
||||
|
||||
/// A continuous section starting mid-page has no first page of its own, so on its second page
|
||||
/// `header_table_areas` checks its default header rather than its first-page header.
|
||||
#[test]
|
||||
fn continuous_section_second_page_ignores_first_page_header_table() {
|
||||
use wordcraft_doc::para::Anchor;
|
||||
use wordcraft_doc::props::{HeightRule, LineSpacing, TableFloat};
|
||||
use wordcraft_doc::section::SectionStart;
|
||||
for start in [SectionStart::Continuous, SectionStart::NextPage] {
|
||||
let mut paras: Vec<String> = (0..10).map(|i| format!("Section 1 {i}")).collect();
|
||||
paras.extend((0..24).map(|i| format!("Section 2 {i}")));
|
||||
let mut d = Document::from_text(¶s.join("\n"));
|
||||
for block in &mut d.body {
|
||||
let Block::Para(p) = Arc::make_mut(block) else { panic!("paragraph") };
|
||||
p.props =
|
||||
ParaProps { space_before: Some(0.0), space_after: Some(0.0), line_spacing: Some(LineSpacing::Exactly(20.0)), ..Default::default() };
|
||||
}
|
||||
d.settings.compat_mode = 15;
|
||||
let make_table = |y, height| {
|
||||
let mut t = Table::new(1, 2, 300.0);
|
||||
t.props.cell_margins = Some([0.0; 4]);
|
||||
t.props.float = Some(TableFloat { h_rel: Anchor::Page, v_rel: Anchor::Page, x: 72.0, y, overlap: false, ..Default::default() });
|
||||
t.rows[0].props.height = Some(height);
|
||||
t.rows[0].props.height_rule = HeightRule::Exact;
|
||||
t
|
||||
};
|
||||
let first_hdr = d.add_part(wordcraft_doc::PartKind::Header, vec![Arc::new(Block::Table(make_table(60.0, 80.0)))]);
|
||||
let s1 = d.last_section.clone();
|
||||
d.para_mut(StoryRef::Body, &Path::top(9)).unwrap().section = Some(Box::new(s1));
|
||||
d.last_section.start = start;
|
||||
d.last_section.title_page = true;
|
||||
d.last_section.headers.first = Some(first_hdr);
|
||||
d.body.push(Arc::new(Block::Table(make_table(100.0, 48.0))));
|
||||
let l = lay(&d);
|
||||
let begins = l.caret(&Pos::body(10, 0)).unwrap().page;
|
||||
let target = match start {
|
||||
SectionStart::Continuous => {
|
||||
assert_eq!(l.caret(&Pos::body(9, 0)).unwrap().page, begins, "section 2 starts mid-page");
|
||||
begins + 1
|
||||
}
|
||||
_ => begins,
|
||||
};
|
||||
let cell_top = l.pages[target]
|
||||
.items
|
||||
.iter()
|
||||
.filter_map(|it| match it {
|
||||
Placed::Cell { rect, .. } => Some(rect.y),
|
||||
_ => None,
|
||||
})
|
||||
.fold(f32::MAX, f32::min);
|
||||
let expected = if start == SectionStart::Continuous { 100.0 } else { 140.0 };
|
||||
assert!((cell_top - expected).abs() < 0.01, "{start:?}: body floating table top {cell_top} on page {target}, expected {expected}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The same for `footer_table_wraps`: body lines on a continuous section's second page do not wrap
|
||||
/// around a floating table in the section's first-page footer.
|
||||
#[test]
|
||||
fn continuous_section_second_page_ignores_first_page_footer_table_wrap() {
|
||||
use wordcraft_doc::para::Anchor;
|
||||
use wordcraft_doc::props::{HeightRule, LineSpacing, TableFloat};
|
||||
use wordcraft_doc::section::SectionStart;
|
||||
const FLOAT_TOP: f32 = 100.0;
|
||||
const TABLE_HEIGHT: f32 = 80.0;
|
||||
const TABLE_WIDTH: f32 = 468.0;
|
||||
for start in [SectionStart::Continuous, SectionStart::NextPage] {
|
||||
let mut paras: Vec<String> = (0..10).map(|i| format!("Section 1 {i}")).collect();
|
||||
let long = "Body wrap word ".repeat(22);
|
||||
paras.extend((0..14).map(|_| long.clone()));
|
||||
let mut d = Document::from_text(¶s.join("\n"));
|
||||
for block in &mut d.body[10..] {
|
||||
let Block::Para(p) = Arc::make_mut(block) else { panic!("paragraph") };
|
||||
p.props =
|
||||
ParaProps { space_before: Some(0.0), space_after: Some(0.0), line_spacing: Some(LineSpacing::Exactly(24.0)), ..Default::default() };
|
||||
}
|
||||
let mut table = Table::new(1, 1, TABLE_WIDTH);
|
||||
table.props.cell_margins = Some([0.0; 4]);
|
||||
table.props.float = Some(TableFloat { y: FLOAT_TOP, h_rel: Anchor::Page, v_rel: Anchor::Page, ..Default::default() });
|
||||
table.rows[0].props.height = Some(TABLE_HEIGHT);
|
||||
table.rows[0].props.height_rule = HeightRule::Exact;
|
||||
let first_ftr = d.add_part(wordcraft_doc::PartKind::Footer, vec![Arc::new(Block::Table(table))]);
|
||||
let s1 = d.last_section.clone();
|
||||
d.para_mut(StoryRef::Body, &Path::top(9)).unwrap().section = Some(Box::new(s1));
|
||||
d.last_section.start = start;
|
||||
d.last_section.title_page = true;
|
||||
d.last_section.footers.first = Some(first_ftr);
|
||||
let l = lay(&d);
|
||||
let begins = l.caret(&Pos::body(10, 0)).unwrap().page;
|
||||
let target = match start {
|
||||
SectionStart::Continuous => {
|
||||
assert_eq!(l.caret(&Pos::body(9, 0)).unwrap().page, begins, "section 2 starts mid-page");
|
||||
begins + 1
|
||||
}
|
||||
_ => begins,
|
||||
};
|
||||
assert!(l.pages.len() > target, "{start:?}: expected page {target}");
|
||||
let margin_left = d.last_section.margin_left;
|
||||
let beside: Vec<_> = (10..d.body.len() as u32)
|
||||
.flat_map(|b| line_boxes(&l, target, b, margin_left))
|
||||
.filter(|(_, top, _, bottom)| *bottom > FLOAT_TOP + 0.01 && *top < FLOAT_TOP + TABLE_HEIGHT - 0.01)
|
||||
.collect();
|
||||
assert!(!beside.is_empty(), "{start:?}: no body lines beside footer table band on page {target}");
|
||||
if start == SectionStart::Continuous {
|
||||
assert!(
|
||||
beside.iter().all(|(left, ..)| (*left - margin_left).abs() < 0.01),
|
||||
"{start:?}: continuous second page wrapped around first-page footer table: {beside:?}"
|
||||
);
|
||||
} else {
|
||||
assert!(
|
||||
beside.iter().all(|(left, ..)| *left >= TABLE_WIDTH - 0.01),
|
||||
"{start:?}: new-page section failed to wrap around first-page footer table: {beside:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The same `begins_section` rule governs `footer_story` (first-page versus default footer), both
|
||||
/// when the continuous section starts mid-page with separate paragraphs and when its first
|
||||
/// paragraph runs over onto the next page.
|
||||
#[test]
|
||||
fn continuous_section_first_page_footer_is_not_shown_on_its_second_page() {
|
||||
use wordcraft_doc::section::SectionStart;
|
||||
for start in [SectionStart::Continuous, SectionStart::NextPage] {
|
||||
let text = (0..140).map(|i| format!("Paragraph {i}")).collect::<Vec<_>>().join("\n");
|
||||
let mut d = Document::from_text(&text);
|
||||
let part = |d: &mut Document, t: &str| {
|
||||
d.add_part(wordcraft_doc::PartKind::Footer, vec![wordcraft_doc::para_block(Paragraph::with_text(t, Default::default()))])
|
||||
};
|
||||
let (one, first, two) = (part(&mut d, "ONE"), part(&mut d, "FIRST"), part(&mut d, "TWO"));
|
||||
let mut s1 = d.last_section.clone();
|
||||
s1.footers.default = Some(one);
|
||||
d.para_mut(StoryRef::Body, &Path::top(19)).unwrap().section = Some(Box::new(s1));
|
||||
d.last_section.start = start;
|
||||
d.last_section.title_page = true;
|
||||
d.last_section.footers.first = Some(first);
|
||||
d.last_section.footers.default = Some(two);
|
||||
let l = lay(&d);
|
||||
let begins = l.caret(&Pos::body(20, 0)).unwrap().page;
|
||||
let shown: Vec<_> = l.pages.iter().map(|p| p.footer_story).collect();
|
||||
assert!(l.pages.len() > begins + 2, "{start:?}: the second section runs over several pages");
|
||||
match start {
|
||||
SectionStart::Continuous => {
|
||||
assert_eq!(l.caret(&Pos::body(19, 0)).unwrap().page, begins, "the second section starts part-way down a page");
|
||||
assert_eq!(shown[begins], Some(one), "{start:?}: the page where it starts keeps the first section's footer");
|
||||
assert!(
|
||||
shown[begins + 1..].iter().all(|f| *f == Some(two)),
|
||||
"{start:?}: then its default footer, never its first-page one: {shown:?}"
|
||||
);
|
||||
}
|
||||
_ => {
|
||||
assert_eq!(shown[begins], Some(first), "{start:?}: a section on a new page shows its first-page footer there");
|
||||
assert!(shown[begins + 1..].iter().all(|f| *f == Some(two)), "{start:?}: {shown:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut paras: Vec<String> = (0..44).map(|i| format!("Paragraph {i}")).collect();
|
||||
paras.push("word ".repeat(1200));
|
||||
paras.extend((0..60).map(|i| format!("After {i}")));
|
||||
let mut d = Document::from_text(¶s.join("\n"));
|
||||
let part = |d: &mut Document, t: &str| {
|
||||
d.add_part(wordcraft_doc::PartKind::Footer, vec![wordcraft_doc::para_block(Paragraph::with_text(t, Default::default()))])
|
||||
};
|
||||
let (one, first, two) = (part(&mut d, "ONE"), part(&mut d, "FIRST"), part(&mut d, "TWO"));
|
||||
let mut s1 = d.last_section.clone();
|
||||
s1.footers.default = Some(one);
|
||||
d.para_mut(StoryRef::Body, &Path::top(43)).unwrap().section = Some(Box::new(s1));
|
||||
d.last_section.start = SectionStart::Continuous;
|
||||
d.last_section.title_page = true;
|
||||
d.last_section.footers.first = Some(first);
|
||||
d.last_section.footers.default = Some(two);
|
||||
let l = lay(&d);
|
||||
let begins = l.caret(&Pos::body(44, 0)).unwrap().page;
|
||||
assert_eq!(l.caret(&Pos::body(43, 0)).unwrap().page, begins, "the second section starts part-way down a page");
|
||||
let next = begins + 1;
|
||||
assert!(l.pages.get(next).is_some_and(|p| p.first_block == 44), "its first paragraph runs over onto the next page");
|
||||
let shown: Vec<_> = l.pages.iter().map(|p| p.footer_story).collect();
|
||||
assert_eq!(shown[begins], Some(one));
|
||||
assert!(shown[next..].iter().all(|f| *f == Some(two)), "{shown:?}");
|
||||
}
|
||||
|
||||
/// Sections starting continuously one after another still go onto new pages: a paragraph that
|
||||
/// doesn't fit below the text above it moves on rather than running off the page (#3907). A
|
||||
/// hundred one-line sections lay out like a hundred plain paragraphs.
|
||||
@@ -18860,6 +19494,76 @@ fn turned_cell_float_keeps_its_along_text_offset() {
|
||||
}
|
||||
}
|
||||
|
||||
/// #6567: when a wrapping float (such as a page-tall `wrapTopAndBottom` frame) pushes its anchor
|
||||
/// paragraph's first line to the bottom of the page, sibling paragraph-relative floats with
|
||||
/// negative vertical offsets are measured from the displaced paragraph line rather than placed
|
||||
/// above the page from the pre-wrap origin.
|
||||
#[test]
|
||||
fn negative_offset_floats_in_a_paragraph_pushed_down_by_a_wrapping_float_stay_on_the_page() {
|
||||
use wordcraft_doc::para::{Anchor, Float, FloatAlign, Wrap};
|
||||
let mut doc = Document::from_text("");
|
||||
doc.last_section.page_w = 595.3;
|
||||
doc.last_section.page_h = 841.9;
|
||||
let mut para = Paragraph::new();
|
||||
let title = Float {
|
||||
wrap: Wrap::InFrontOfText,
|
||||
h_rel: Anchor::Margin,
|
||||
h_align: Some(FloatAlign::Center),
|
||||
v_rel: Anchor::Paragraph,
|
||||
y: -652.55,
|
||||
..Default::default()
|
||||
};
|
||||
let row = Float { wrap: Wrap::InFrontOfText, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, x: 36.0, y: -460.75, ..Default::default() };
|
||||
let frame = Float { wrap: Wrap::TopAndBottom, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, y: -43.11, ..Default::default() };
|
||||
para.insert_object(para.len(), rect_shape(378.5, 105.75, title), &Default::default()).unwrap();
|
||||
para.insert_object(para.len(), rect_shape(194.55, 38.45, row), &Default::default()).unwrap();
|
||||
para.insert_object(para.len(), rect_shape(556.46, 802.52, frame), &Default::default()).unwrap();
|
||||
doc.body = vec![wordcraft_doc::para_block(para)];
|
||||
|
||||
let l = lay(&doc);
|
||||
assert_eq!(l.pages.len(), 1);
|
||||
let placed = shapes(&l.pages[0].items);
|
||||
assert_eq!(placed.len(), 3, "{placed:?}");
|
||||
let frame_rect = placed.iter().find(|r| (r.h - 802.52).abs() < 0.1).unwrap();
|
||||
let title_rect = placed.iter().find(|r| (r.h - 105.75).abs() < 0.1).unwrap();
|
||||
let row_rect = placed.iter().find(|r| (r.h - 38.45).abs() < 0.1).unwrap();
|
||||
let line_top = first_line_top(&l.pages[0].items);
|
||||
assert!((frame_rect.y - (72.0 - 43.11)).abs() < 0.5, "frame stays at the top of the page: {frame_rect:?}");
|
||||
assert!((title_rect.y - (line_top - 652.55)).abs() < 0.5, "title measured from displaced line {line_top}: {title_rect:?}");
|
||||
assert!((row_rect.y - (line_top - 460.75)).abs() < 0.5, "row measured from displaced line {line_top}: {row_rect:?}");
|
||||
assert!(title_rect.y > frame_rect.y && row_rect.bottom() < frame_rect.bottom(), "{placed:?}");
|
||||
let frame = l.object(&Pos::body(0, 2 * wordcraft_doc::para::OBJ.len_utf8()), 0).unwrap();
|
||||
let title = l.object(&Pos::body(0, 0), 0).unwrap();
|
||||
assert!((title.origin.y - line_top).abs() < 0.5, "moved float's offset starts at the pushed line: {title:?}");
|
||||
assert!((frame.rect.y - frame.origin.y + 43.11).abs() < 0.5, "unmoved wrapping float keeps its origin: {frame:?}");
|
||||
}
|
||||
|
||||
/// #6567 review: a wrapping float above its paragraph that would land on the first line when
|
||||
/// placed from it again isn't moved there: that line was laid out without it in the way.
|
||||
#[test]
|
||||
fn a_wrapping_float_isnt_moved_onto_a_first_line_laid_out_without_it() {
|
||||
crate::test_fonts();
|
||||
use wordcraft_doc::para::{Anchor, Float, Wrap};
|
||||
let mut doc = Document::from_text("Words in the first line of the paragraph.");
|
||||
let frame = Float { wrap: Wrap::TopAndBottom, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, ..Default::default() };
|
||||
let square = Float { wrap: Wrap::Square, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, y: -10.0, ..Default::default() };
|
||||
doc.insert_object(&Pos::body(0, 0), rect_shape(150.0, 50.0, square), &Default::default()).unwrap();
|
||||
doc.insert_object(&Pos::body(0, 0), rect_shape(200.0, 100.0, frame), &Default::default()).unwrap();
|
||||
let l = lay(&doc);
|
||||
let items = &l.pages[0].items;
|
||||
let square = shapes(items).into_iter().find(|r| (r.h - 50.0).abs() < 0.1).unwrap();
|
||||
let (x, y, height) = items
|
||||
.iter()
|
||||
.find_map(|i| match i {
|
||||
Placed::Lines { x, y, para, story: StoryRef::Body, .. } => para.lines.first().map(|l| (*x + l.left, *y, l.height)),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
assert!(y > 72.0 + 99.0, "the frame pushes the first line down: {y}");
|
||||
let overlaps = square.y < y + height && square.bottom() > y && square.x < x + 1.0 && square.right() > x;
|
||||
assert!(!overlaps, "the float {square:?} covers the first line's text at ({x}, {y})");
|
||||
}
|
||||
|
||||
/// A caption kept with the next paragraph (`keepNext`) before a table goes over with the table
|
||||
/// when the table's repeated header row and the start of its first row don't fit under it, as in
|
||||
/// Word, instead of staying alone at the foot of the page: keep with next asked a table for a
|
||||
@@ -19192,6 +19896,97 @@ fn header_text_covers_the_whole_band_of_centred_and_right_lines() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A floating table placed by an offset from the margin (measured in Word for Windows): before
|
||||
/// Word 2013 its first cell's text is at the offset, moved by `w:tblInd`; from it its edge is,
|
||||
/// moved in by half its left border, and `w:tblInd` doesn't move it.
|
||||
#[test]
|
||||
fn a_floating_table_placed_by_an_offset_takes_its_indent_before_word_2013_only() {
|
||||
crate::test_fonts();
|
||||
use wordcraft_doc::para::Anchor;
|
||||
use wordcraft_doc::props::TableFloat;
|
||||
let text_x = |mode: u32, indent: Option<f32>| {
|
||||
let mut t = Table::new(1, 2, 300.0);
|
||||
t.props.fixed = true;
|
||||
t.props.indent = indent;
|
||||
t.props.cell_margins = Some([0.0, 5.4, 0.0, 5.4]);
|
||||
t.props.borders = Some(wordcraft_doc::props::Borders::all(wordcraft_doc::props::Border::single(0.5)));
|
||||
t.props.float = Some(TableFloat { h_rel: Anchor::Margin, v_rel: Anchor::Paragraph, ..Default::default() });
|
||||
for c in &mut t.rows[0].cells {
|
||||
c.blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Cell", Default::default()))];
|
||||
}
|
||||
let mut d = Document::from_text("Below");
|
||||
d.settings.compat_mode = mode;
|
||||
d.insert_block(StoryRef::Body, &Path::top(0), wordcraft_doc::Block::Table(t)).unwrap();
|
||||
lay(&d).pages[0]
|
||||
.items
|
||||
.iter()
|
||||
.find_map(|i| match i {
|
||||
Placed::Lines { path, x, .. } if path.0 == [0, 0, 0, 0] => Some(*x),
|
||||
_ => None,
|
||||
})
|
||||
.expect("the first cell's text")
|
||||
};
|
||||
let margin = 72.0;
|
||||
assert!((text_x(14, None) - margin).abs() < 0.01, "mode 14: {}", text_x(14, None));
|
||||
assert!((text_x(14, Some(-5.4)) - (margin - 5.4)).abs() < 0.01, "mode 14, indent: {}", text_x(14, Some(-5.4)));
|
||||
assert!((text_x(15, None) - (margin + 0.25 + 5.4)).abs() < 0.01, "mode 15: {}", text_x(15, None));
|
||||
assert!((text_x(15, Some(-5.4)) - (margin + 0.25 + 5.4)).abs() < 0.01, "mode 15, indent: {}", text_x(15, Some(-5.4)));
|
||||
}
|
||||
|
||||
/// From Word 2013 a table moves in by half its first cell's left border, and a first row's
|
||||
/// `w:tblPrEx` border is that border (measured in Word for Windows): with an 8 pt table border and
|
||||
/// a 2 pt exception the first cell's text is at 78.38, 1 pt in; without the exception at 81.38.
|
||||
/// The same inline and floating, and for every row.
|
||||
#[test]
|
||||
fn a_first_rows_exception_border_is_the_half_border_a_table_moves_in_by() {
|
||||
crate::test_fonts();
|
||||
use wordcraft_doc::para::Anchor;
|
||||
use wordcraft_doc::props::TableFloat;
|
||||
let text_x = |float: bool, exception: bool| {
|
||||
let mut t = Table::new(2, 2, 300.0);
|
||||
t.props.fixed = true;
|
||||
t.props.style = None;
|
||||
t.props.cell_margins = Some([0.0, 5.4, 0.0, 5.4]);
|
||||
t.props.borders = Some(Borders { left: Some(Border::single(8.0)), ..Default::default() });
|
||||
if float {
|
||||
t.props.float = Some(TableFloat { h_rel: Anchor::Margin, v_rel: Anchor::Paragraph, ..Default::default() });
|
||||
}
|
||||
if exception {
|
||||
t.rows[0].props.exceptions = Some(Box::new(wordcraft_doc::props::TableProps {
|
||||
borders: Some(Borders { left: Some(Border::single(2.0)), ..Default::default() }),
|
||||
..Default::default()
|
||||
}));
|
||||
}
|
||||
for r in &mut t.rows {
|
||||
for c in &mut r.cells {
|
||||
c.blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Cell", Default::default()))];
|
||||
}
|
||||
}
|
||||
let mut d = Document::from_text("Below");
|
||||
d.settings.compat_mode = 15;
|
||||
d.insert_block(StoryRef::Body, &Path::top(0), wordcraft_doc::Block::Table(t)).unwrap();
|
||||
let l = lay(&d);
|
||||
let at = |row: u32| {
|
||||
l.pages[0]
|
||||
.items
|
||||
.iter()
|
||||
.find_map(|i| match i {
|
||||
Placed::Lines { path, x, .. } if path.0 == [0, row, 0, 0] => Some(*x),
|
||||
_ => None,
|
||||
})
|
||||
.expect("the first cell's text")
|
||||
};
|
||||
(at(0), at(1))
|
||||
};
|
||||
for float in [false, true] {
|
||||
for (exception, want) in [(false, 72.0 + 4.0 + 5.4), (true, 72.0 + 1.0 + 5.4)] {
|
||||
let (first, second) = text_x(float, exception);
|
||||
assert!((first - want).abs() < 0.01, "float {float}, exception {exception}: {first}");
|
||||
assert!((second - want).abs() < 0.01, "float {float}, exception {exception}, row 2: {second}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reading_layout_keeps_a_negatively_indented_table_in_the_column() {
|
||||
crate::test_fonts();
|
||||
@@ -19473,3 +20268,78 @@ fn evict_unused_caps_stale_entries_across_repeated_edits() {
|
||||
assert!(c.len() <= base + 1025, "stale cache entries must be bounded (got {}, base {base})", c.len());
|
||||
}
|
||||
}
|
||||
|
||||
/// #8613: a Top-and-Bottom object ending above a paragraph's applied space before cannot affect
|
||||
/// it, so paragraphs below keep empty exclusions and hit the cache when shifted vertically, and
|
||||
/// paragraphs below it in a box are not laid out twice.
|
||||
#[test]
|
||||
fn top_and_bottom_float_above_space_before_keeps_cache_hits_on_shift() {
|
||||
crate::test_fonts();
|
||||
use wordcraft_doc::para::{Anchor, Float, Wrap};
|
||||
use wordcraft_doc::props::LineSpacing;
|
||||
|
||||
let mut d = Document::from_text(&"line\n".repeat(12));
|
||||
for block in &mut d.body {
|
||||
if let wordcraft_doc::Block::Para(p) = Arc::make_mut(block) {
|
||||
p.props.line_spacing = Some(LineSpacing::Exactly(12.0));
|
||||
p.props.space_before = Some(0.0);
|
||||
p.props.space_after = Some(0.0);
|
||||
}
|
||||
}
|
||||
if let Some(wordcraft_doc::Block::Para(p)) = d.body.get_mut(4).map(Arc::make_mut) {
|
||||
p.props.space_before = Some(12.0);
|
||||
}
|
||||
let f = Float { wrap: Wrap::TopAndBottom, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, ..Default::default() };
|
||||
d.insert_object(&Pos::body(0, 0), rect_shape(144.0, 10.0, f), &Default::default()).unwrap();
|
||||
|
||||
let mut c = LayoutCache::new();
|
||||
let before = layout(&d, &mut c, &LayoutOptions::default());
|
||||
let y_before = before.caret(&Pos::body(6, 0)).unwrap().top;
|
||||
let misses = c.misses;
|
||||
|
||||
d.insert_text(&Pos::body(2, 0), &"word ".repeat(30), &Default::default()).unwrap();
|
||||
let after = layout(&d, &mut c, &LayoutOptions::default());
|
||||
let y_after = after.caret(&Pos::body(6, 0)).unwrap().top;
|
||||
assert!(y_after > y_before + 10.0, "paragraphs below shifted down ({y_before} -> {y_after})");
|
||||
assert_eq!(c.misses, misses + 1, "only the edited paragraph should miss the cache");
|
||||
}
|
||||
|
||||
/// #8613: in table cells and other boxes, paragraphs below a Top-and-Bottom float (and clear of
|
||||
/// its space-before band) get empty exclusions, so they are laid out once and hit the cache when
|
||||
/// shifted vertically.
|
||||
#[test]
|
||||
fn top_and_bottom_float_in_cell_keeps_cache_hits_on_shift() {
|
||||
crate::test_fonts();
|
||||
use wordcraft_doc::para::{Anchor, Float, Wrap};
|
||||
use wordcraft_doc::props::LineSpacing;
|
||||
|
||||
let mut d = Document::new();
|
||||
let mut t = Table::new(1, 1, 468.0);
|
||||
t.props.fixed = true;
|
||||
t.rows[0].cells[0].blocks = (0..6)
|
||||
.map(|i| {
|
||||
let mut p = Paragraph::with_text(&format!("cell line {i}"), Default::default());
|
||||
p.props.line_spacing = Some(LineSpacing::Exactly(12.0));
|
||||
p.props.space_before = Some(0.0);
|
||||
p.props.space_after = Some(0.0);
|
||||
wordcraft_doc::para_block(p)
|
||||
})
|
||||
.collect();
|
||||
d.body = vec![Arc::new(wordcraft_doc::Block::Table(t))];
|
||||
let cell_pos = |para: usize| Pos { story: StoryRef::Body, path: Path(vec![0, 0, 0, para as u32]), off: 0 };
|
||||
let f = Float { wrap: Wrap::TopAndBottom, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, ..Default::default() };
|
||||
d.insert_object(&cell_pos(0), rect_shape(100.0, 10.0, f), &Default::default()).unwrap();
|
||||
|
||||
let mut c = LayoutCache::new();
|
||||
let before = layout(&d, &mut c, &LayoutOptions::default());
|
||||
let y_before = before.caret(&cell_pos(4)).unwrap().top;
|
||||
// Paragraph 0 holds the float so it lays out twice; paragraphs 1..6 sit below it and lay out once each.
|
||||
assert_eq!(c.misses, 7, "paragraphs below the float should be laid out only once");
|
||||
let misses = c.misses;
|
||||
|
||||
d.insert_text(&cell_pos(1), &"word ".repeat(30), &Default::default()).unwrap();
|
||||
let after = layout(&d, &mut c, &LayoutOptions::default());
|
||||
let y_after = after.caret(&cell_pos(4)).unwrap().top;
|
||||
assert!(y_after > y_before + 10.0, "cell paragraphs below shifted down ({y_before} -> {y_after})");
|
||||
assert_eq!(c.misses, misses + 1, "only the edited cell paragraph should miss the cache");
|
||||
}
|
||||
|
||||
@@ -133,6 +133,106 @@ 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");
|
||||
}
|
||||
|
||||
/// A `w:eastAsiaTheme` slot on a style or run takes precedence over an inherited named East Asian
|
||||
/// font (`w:eastAsia`) without ideographs: Word draws the ideographs in the theme face instead, so
|
||||
/// it still keeps the automatic space unless the theme slot itself names an installed font without
|
||||
/// ideographs. Conversely, a named `w:eastAsia` on a run replaces an inherited theme slot.
|
||||
#[test]
|
||||
fn east_asian_theme_slot_overrides_inherited_named_font() {
|
||||
crate::test_fonts();
|
||||
use wordcraft_doc::props::ThemeFont;
|
||||
|
||||
// Base default names an installed font without ideographs (`Source Serif 4`).
|
||||
// A style or run setting `minorEastAsia` overrides it: with no non-CJK `a:ea` face, spaces stay.
|
||||
let mut d = Document::from_text("法院94年A字");
|
||||
Arc::make_mut(&mut d.styles).default_chr.font_ea = Some("Source Serif 4".to_string());
|
||||
let len = para0(&mut d).text.len();
|
||||
para0(&mut d).format(0, len, &|c: &mut CharProps| c.font_ea_theme = Some(ThemeFont::MinorEastAsia)).unwrap();
|
||||
let q = quarter(&d);
|
||||
assert_eq!(gaps(&d), [0.0, q, 0.0, after(&d, 7), q, after(&d, 11), 0.0], "theme slot overrides inherited font_ea");
|
||||
|
||||
// When the theme's `a:ea` face (in `wordcraft:theme.fonts`) itself is an installed font without
|
||||
// ideographs, the space is suppressed.
|
||||
let mut themed_no_cjk = d.clone();
|
||||
themed_no_cjk.passthrough.insert("wordcraft:theme.fonts".into(), Arc::new(b"minor\tface\tea\tSource Serif 4\n".to_vec()));
|
||||
assert!(gaps(&themed_no_cjk).iter().all(|g| *g == 0.0), "theme a:ea without ideographs: {:?}", gaps(&themed_no_cjk));
|
||||
|
||||
// A Latin theme slot (`minorHAnsi`) resolves to `settings.minor_font`: if installed and lacking
|
||||
// ideographs, it also suppresses the space.
|
||||
let mut latin_slot = d.clone();
|
||||
latin_slot.settings.minor_font = "Source Serif 4".to_string();
|
||||
para0(&mut latin_slot).format(0, len, &|c: &mut CharProps| c.font_ea_theme = Some(ThemeFont::MinorHAnsi)).unwrap();
|
||||
assert!(gaps(&latin_slot).iter().all(|g| *g == 0.0), "Latin theme slot without ideographs: {:?}", gaps(&latin_slot));
|
||||
|
||||
// A named `w:eastAsia` without `w:eastAsiaTheme` on a run overrides an inherited theme slot.
|
||||
let mut overridden = Document::from_text("法院94年A字");
|
||||
Arc::make_mut(&mut overridden.styles).default_chr.font_ea_theme = Some(ThemeFont::MinorEastAsia);
|
||||
para0(&mut overridden).format(0, len, &|c: &mut CharProps| c.font_ea = Some("Source Serif 4".to_string())).unwrap();
|
||||
assert!(gaps(&overridden).iter().all(|g| *g == 0.0), "named font_ea overrides inherited theme slot: {:?}", gaps(&overridden));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn east_asian_theme_script_fonts_follow_the_theme_language() {
|
||||
crate::test_fonts();
|
||||
use wordcraft_doc::props::ThemeFont;
|
||||
|
||||
for (lang, script) in [("zh-CN", "Hans"), ("zh-TW", "Hant"), ("zh-Hant-CN", "Hant"), ("ja-JP", "Jpan"), ("ko-KR", "Hang")] {
|
||||
for (scheme, slot) in [("major", ThemeFont::MajorEastAsia), ("minor", ThemeFont::MinorEastAsia)] {
|
||||
let mut d = Document::from_text("漢A漢");
|
||||
Arc::make_mut(&mut d.styles).default_chr.font_ea = Some("宋体".into());
|
||||
para0(&mut d).format(0, 7, &|c: &mut CharProps| c.font_ea_theme = Some(slot)).unwrap();
|
||||
let settings = format!(
|
||||
r#"<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:themeFontLang w:eastAsia="{lang}"/></w:settings>"#
|
||||
);
|
||||
d.passthrough.insert("wordcraft:settings.orig".into(), Arc::new(settings.into_bytes()));
|
||||
d.passthrough.insert("wordcraft:theme.fonts".into(), Arc::new(format!("{scheme}\tface\tea\tSource Serif 4\n").into_bytes()));
|
||||
let main = gaps(&d);
|
||||
assert!(main.iter().all(|g| *g == 0.0));
|
||||
// The same installed face without ideographs suppresses spacing when selected by script.
|
||||
d.passthrough.insert(
|
||||
"wordcraft:theme.fonts".into(),
|
||||
Arc::new(format!("{scheme}\tface\tea\t\n{scheme}\tscript\t{script}\tSource Serif 4\n").into_bytes()),
|
||||
);
|
||||
assert_eq!(gaps(&d), main, "{scheme}: {lang}/{script}");
|
||||
|
||||
// A nonempty main face takes precedence over the script entry.
|
||||
d.passthrough.insert(
|
||||
"wordcraft:theme.fonts".into(),
|
||||
Arc::new(format!("{scheme}\tscript\t{script}\tSource Serif 4\n{scheme}\tface\tea\tMissing CJK Face 8749\n").into_bytes()),
|
||||
);
|
||||
assert!(gaps(&d).iter().any(|g| *g > 0.0), "{scheme}: main face wins");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_field_result_is_classed_by_the_text_it_shows() {
|
||||
crate::test_fonts();
|
||||
|
||||
@@ -106,7 +106,8 @@ fn cell_letterhead_pulls_an_outside_picture_to_the_outer_left_edge() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Confinement follows the particular cell, including asymmetric margins mirrored for RTL.
|
||||
/// Confinement follows the particular cell, including asymmetric margins and RTL column
|
||||
/// mirroring (cell margins themselves stay on the sides they name).
|
||||
#[test]
|
||||
fn cell_float_outer_edges_include_asymmetric_and_mirrored_margins() {
|
||||
for rtl in [false, true] {
|
||||
|
||||
@@ -101,6 +101,34 @@ fn in_small_capitals_a_letter_and_its_marks_go_together_to_a_face_that_has_them_
|
||||
}
|
||||
}
|
||||
|
||||
/// In small capitals a mark after a lower-case letter shares the letter's 0.8-size shaping run
|
||||
/// even when the run's font already draws every mark, so it composes and positions with the
|
||||
/// drawn capital instead of splitting into a separate full-size run (#8571).
|
||||
#[test]
|
||||
fn in_small_capitals_a_mark_the_run_font_draws_shares_its_letters_size_and_run() {
|
||||
let serif = serif();
|
||||
let (lower, upper, mark) = ('e', 'E', '\u{301}');
|
||||
assert!(serif.covers(lower) && serif.covers(upper) && serif.covers(mark), "{SERIF} has e, E and U+0301");
|
||||
let text = format!("{lower}{mark} {upper}{mark}");
|
||||
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 lower_mark = lower.len_utf8();
|
||||
let upper_at = text.find(upper).expect("upper-case letter is in the text");
|
||||
let upper_mark = upper_at + upper.len_utf8();
|
||||
assert_eq!(face_at(¶, 0).id(), serif.id(), "lower-case letter stays in the run's font");
|
||||
assert_eq!(face_at(¶, lower_mark).id(), serif.id(), "mark stays in the run's font");
|
||||
assert_eq!(style_at(lower_mark), style_at(0), "mark after lower-case letter shares its small-caps run");
|
||||
assert_eq!(style_at(upper_mark), style_at(upper_at), "mark after upper-case letter shares its full-size run");
|
||||
assert!(
|
||||
para.styles[style_at(lower_mark) as usize].size < para.styles[style_at(upper_at) as usize].size,
|
||||
"mark after lower-case letter is drawn smaller than the upper-case run"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mark_the_font_composes_with_its_letter_stays_in_the_run_font() {
|
||||
let serif = serif();
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use crate::*;
|
||||
use wordcraft_doc::Pos;
|
||||
use wordcraft_doc::props::LineSpacing;
|
||||
use wordcraft_doc::section::{DocGrid, DocGridType};
|
||||
|
||||
@@ -97,3 +98,39 @@ fn character_grid_places_east_asian_text_on_the_pitch() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_exact_character_grid_line_fits_all_its_cells_with_kerning() {
|
||||
crate::test_fonts();
|
||||
let text = "AVAVAVAVAVAVAVAVAVAV";
|
||||
let mut grid = with_grid(text, DocGridType::SnapToChars, 0);
|
||||
let styles = std::sync::Arc::make_mut(&mut grid.styles);
|
||||
styles.default_chr.font = Some("Inter".into());
|
||||
styles.default_chr.kern = Some(1.0);
|
||||
|
||||
let set_width = |doc: &mut Document, width: f32| {
|
||||
let indent = doc.last_section.text_width() - width;
|
||||
doc.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| p.indent_right = Some(indent)).unwrap();
|
||||
};
|
||||
|
||||
// In proportional text the fifth letter still needs its unkerned width at a line break.
|
||||
let mut plain = grid.clone();
|
||||
plain.last_section.doc_grid = None;
|
||||
let wide = lay(&plain);
|
||||
let para = wide.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
|
||||
let paired: f32 = para.clusters[..5].iter().map(|c| c.adv).sum();
|
||||
let kern = para.clusters[4].kern;
|
||||
assert!(kern < -0.02, "the test font must kern the pair across the break");
|
||||
set_width(&mut plain, paired - kern / 2.0);
|
||||
assert_eq!(super::body_lines(&lay(&plain), text)[0], "AVAV");
|
||||
|
||||
let size = para::Grid::of(&grid, &grid.last_section).font_size;
|
||||
grid.last_section.doc_grid.as_mut().unwrap().char_space = DocGrid::char_space_for(20.0, size);
|
||||
let pitch = grid.last_section.grid_char_pitch(size).unwrap();
|
||||
set_width(&mut grid, 5.0 * pitch);
|
||||
for kern in [0.0, 1.0] {
|
||||
std::sync::Arc::make_mut(&mut grid.styles).default_chr.kern = Some(kern);
|
||||
let got = super::body_lines(&lay(&grid), text);
|
||||
assert_eq!(got[0], "AVAVA", "kerning threshold {kern}: {got:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,13 +28,13 @@ fn a_word_broken_by_letters_ends_without_its_kerning_pair() {
|
||||
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";
|
||||
/// Inter under `family` (a 5-byte name) with its `GPOS` hidden and an old-style `kern` table
|
||||
/// that kerns `(left, right)` by `units` (and nothing else): a shaper splits such a pair between
|
||||
/// the two glyphs, half in the first one's advance and half in the second one's advance and offset.
|
||||
fn legacy_kern_family(family: &'static str, left: char, right: char, units: i16) -> &'static str {
|
||||
assert_eq!(family.len(), "Inter".len());
|
||||
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 (a, v) = (inter.glyph_for(left) as u16, inter.glyph_for(right) 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;
|
||||
@@ -76,7 +76,7 @@ fn legacy_kern_family(units: i16) -> &'static str {
|
||||
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 (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);
|
||||
@@ -84,7 +84,7 @@ fn legacy_kern_family(units: i16) -> &'static str {
|
||||
}
|
||||
}
|
||||
wordcraft_fonts::FontDb::global().add_font(data);
|
||||
FAMILY
|
||||
family
|
||||
}
|
||||
|
||||
/// A letter ending a line whose kerning pair with the letter before it the shaper split between
|
||||
@@ -95,7 +95,7 @@ fn legacy_kern_family(units: i16) -> &'static str {
|
||||
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 family = legacy_kern_family("Kernx", 'A', 'V', -300);
|
||||
let doc = |indent_right: f32| {
|
||||
let mut d = Document::from_text(text);
|
||||
let st = Arc::make_mut(&mut d.styles);
|
||||
@@ -112,3 +112,277 @@ fn a_letter_ending_a_line_keeps_its_pair_with_the_letter_before() {
|
||||
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);
|
||||
}
|
||||
|
||||
fn first_para(d: &Document) -> Arc<ParaLayout> {
|
||||
lay(d).pages.into_iter().flat_map(|p| p.items).find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wrapped_line_end_caret_and_alignment_drop_the_line_end_pair() {
|
||||
let text = "AVAVAVAVAVAVAVAVAVAV";
|
||||
let doc = |indent_right: f32, align: Align| {
|
||||
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);
|
||||
p.align = Some(align);
|
||||
})
|
||||
.unwrap();
|
||||
d
|
||||
};
|
||||
let base = first_para(&doc(0.0, Align::Left));
|
||||
let kern = base.clusters[4].kern;
|
||||
assert!(kern < -0.1, "the test font kerns \"AV\": {kern}");
|
||||
let paired: f32 = base.clusters[..5].iter().map(|c| c.adv).sum();
|
||||
let alone = paired - kern;
|
||||
let unkerned_last = base.clusters[4].adv - kern;
|
||||
// Slight slack past the five unkerned letters so right and centre alignments move the line.
|
||||
let slack = 6.0;
|
||||
let indent_right = 468.0 - (alone + slack);
|
||||
|
||||
let left = first_para(&doc(indent_right, Align::Left));
|
||||
let l0 = &left.lines[0];
|
||||
assert_eq!(l0.c1, 5);
|
||||
assert!((l0.end_x() - alone).abs() < 0.01, "end_x {} should match unkerned {alone}, not {paired}", l0.end_x());
|
||||
assert!((left.x_of(0, l0.stop).unwrap() - alone).abs() < 0.01);
|
||||
|
||||
let right = first_para(&doc(indent_right, Align::Right));
|
||||
let r0 = &right.lines[0];
|
||||
assert_eq!(r0.c1, 5);
|
||||
let r_end = r0.cl_left(4).unwrap() + unkerned_last;
|
||||
assert!((r_end - r0.right).abs() < 0.01, "right-aligned unkerned end {r_end} should sit at right edge {}", r0.right);
|
||||
|
||||
let center = first_para(&doc(indent_right, Align::Center));
|
||||
let c0 = ¢er.lines[0];
|
||||
assert_eq!(c0.c1, 5);
|
||||
let left_gap = c0.cl_left(0).unwrap() - c0.left;
|
||||
let right_gap = c0.right - (c0.cl_left(4).unwrap() + unkerned_last);
|
||||
assert!((left_gap - right_gap).abs() < 0.01, "centred gaps differ: left {left_gap} vs right {right_gap}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_positive_kerning_pair_at_line_end_stays_inside_the_right_edge() {
|
||||
crate::test_fonts();
|
||||
let text = "AVAVAVAVAVAVAVAVAVAV";
|
||||
let family = legacy_kern_family("Kernp", 'A', 'V', 300);
|
||||
let doc = |indent_right: f32, align: Align| {
|
||||
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);
|
||||
p.align = Some(align);
|
||||
})
|
||||
.unwrap();
|
||||
d
|
||||
};
|
||||
let base = first_para(&doc(0.0, Align::Left));
|
||||
let kern = base.clusters[4].kern;
|
||||
assert!(kern > 0.5, "the test font positively kerns \"AV\": {kern}");
|
||||
let paired: f32 = base.clusters[..5].iter().map(|c| c.adv).sum();
|
||||
let alone = paired - kern;
|
||||
let unkerned_last = base.clusters[4].adv - kern;
|
||||
let width = (paired + alone) / 2.0;
|
||||
let indent_right = 468.0 - width;
|
||||
|
||||
let left = first_para(&doc(indent_right, Align::Left));
|
||||
let l0 = &left.lines[0];
|
||||
assert_eq!(l0.c1, 5);
|
||||
assert!(l0.end_x() <= l0.right + 0.01, "end_x {} ran past right edge {}", l0.end_x(), l0.right);
|
||||
assert!((l0.end_x() - alone).abs() < 0.01);
|
||||
|
||||
let right = first_para(&doc(indent_right, Align::Right));
|
||||
let r0 = &right.lines[0];
|
||||
assert_eq!(r0.c1, 5);
|
||||
assert!(r0.cl_left(0).unwrap() > 0.01, "right-aligned line failed to shift right");
|
||||
assert!((r0.cl_left(4).unwrap() + unkerned_last - r0.right).abs() < 0.01);
|
||||
|
||||
let center = first_para(&doc(indent_right, Align::Center));
|
||||
let c0 = ¢er.lines[0];
|
||||
assert_eq!(c0.c1, 5);
|
||||
let left_gap = c0.cl_left(0).unwrap() - c0.left;
|
||||
let right_gap = c0.right - (c0.cl_left(4).unwrap() + unkerned_last);
|
||||
assert!(left_gap > 0.01 && (left_gap - right_gap).abs() < 0.01, "centred gaps: left {left_gap} vs right {right_gap}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_justified_line_adjusts_spaces_without_the_line_end_pair() {
|
||||
crate::test_fonts();
|
||||
// Distributed alignment stretches gaps across clusters directly using `content_end`.
|
||||
let text = "AVAVAVAVAVAVAVAVAVAV";
|
||||
for (family, units) in [("Kerdn", -300i16), ("Kerdp", 300i16)] {
|
||||
let family = legacy_kern_family(family, 'A', 'V', units);
|
||||
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);
|
||||
p.align = Some(Align::Distribute);
|
||||
})
|
||||
.unwrap();
|
||||
d
|
||||
};
|
||||
let base = first_para(&doc(0.0));
|
||||
let kern = base.clusters[4].kern;
|
||||
assert!((kern.signum() as i16) == units.signum(), "{family}: {kern}");
|
||||
let paired: f32 = base.clusters[..5].iter().map(|c| c.adv).sum();
|
||||
let alone = paired - kern;
|
||||
let unkerned_last = base.clusters[4].adv - kern;
|
||||
let width = if units < 0 { alone + 4.0 } else { (paired + alone) / 2.0 };
|
||||
let para = first_para(&doc(468.0 - width));
|
||||
let l0 = ¶.lines[0];
|
||||
assert_eq!(l0.c1, 5, "{family}: expected wrap after 5th letter");
|
||||
assert!(l0.cl_left(4).unwrap() > base.clusters[..4].iter().map(|c| c.adv).sum::<f32>() + 0.01);
|
||||
let end = l0.cl_left(4).unwrap() + unkerned_last;
|
||||
assert!((end - l0.right).abs() < 0.01, "{family}: distributed end {end} should meet right edge {}", l0.right);
|
||||
assert!((l0.end_x() - l0.right).abs() < 0.01);
|
||||
}
|
||||
|
||||
// Justified line with spaces breaking mid-word (`word_wrap = false`): both stretching and
|
||||
// shrinking adjust spaces against the unkerned line end.
|
||||
let j_text = "a b AVAVAVAVAVAVAVAVAVAV";
|
||||
for (family, units) in [("Kerjn", -300i16), ("Kerjp", 300i16)] {
|
||||
let family = legacy_kern_family(family, 'A', 'V', units);
|
||||
let doc = |indent_right: f32| {
|
||||
let mut d = Document::from_text(j_text);
|
||||
d.settings.compat_mode = wordcraft_doc::COMPAT_MODE_CURRENT;
|
||||
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);
|
||||
p.align = Some(Align::Justify);
|
||||
p.word_wrap = Some(false);
|
||||
})
|
||||
.unwrap();
|
||||
d
|
||||
};
|
||||
let base = first_para(&doc(0.0));
|
||||
// "a b AVAVA" is clusters 0..9; cluster 8 is 'A', cluster 9 is 'V'.
|
||||
let kern = base.clusters[8].kern;
|
||||
assert!((kern.signum() as i16) == units.signum(), "{family}: {kern}");
|
||||
let paired: f32 = base.clusters[..9].iter().map(|c| c.adv).sum();
|
||||
let alone = paired - kern;
|
||||
let unkerned_a = base.clusters[8].adv - kern;
|
||||
let width = if units < 0 { alone + 4.0 } else { (paired + alone) / 2.0 };
|
||||
let para = first_para(&doc(468.0 - width));
|
||||
let l0 = ¶.lines[0];
|
||||
assert_eq!(l0.c1, 9, "{family}: expected wrap after 9th cluster");
|
||||
let space_w = l0.cl_left(2).unwrap() - l0.cl_left(1).unwrap();
|
||||
assert!(space_w > base.clusters[1].adv + 0.01, "{family}: spaces should widen, got {space_w} vs {}", base.clusters[1].adv);
|
||||
let end = l0.cl_left(8).unwrap() + unkerned_a;
|
||||
assert!((end - l0.right).abs() < 0.01, "{family}: justified end {end} should meet right edge {}", l0.right);
|
||||
assert!((l0.end_x() - l0.right).abs() < 0.01);
|
||||
|
||||
if units < 0 {
|
||||
let shrunk = first_para(&doc(468.0 - (alone - 0.5)));
|
||||
let s0 = &shrunk.lines[0];
|
||||
assert_eq!(s0.c1, 9, "{family}: expected shrunk wrap after 9th cluster");
|
||||
let s_space = s0.cl_left(2).unwrap() - s0.cl_left(1).unwrap();
|
||||
assert!(s_space < base.clusters[1].adv - 0.01, "{family}: spaces should shrink, got {s_space} vs {}", base.clusters[1].adv);
|
||||
let s_end = s0.cl_left(8).unwrap() + unkerned_a;
|
||||
assert!((s_end - s0.right).abs() < 0.01, "{family}: shrunk end {s_end} should meet right edge {}", s0.right);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_hyphenation_uses_the_unkerned_width_before_a_negative_pair() {
|
||||
crate::test_fonts();
|
||||
let text = "word consideration";
|
||||
let family = legacy_kern_family("Kerhy", 'n', 's', -300);
|
||||
let doc = |indent_right: f32| {
|
||||
let mut d = Document::from_text(text);
|
||||
d.settings.auto_hyphenation = true;
|
||||
d.settings.hyphenation_zone = 0.0;
|
||||
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 base = first_para(&doc(0.0));
|
||||
let k = *base
|
||||
.hyph_after
|
||||
.iter()
|
||||
.find(|&&k| {
|
||||
let i = k as usize;
|
||||
text.get(base.clusters[i].start..base.clusters[i].end) == Some("n")
|
||||
&& base.clusters.get(i + 1).and_then(|c| text.get(c.start..c.end)) == Some("s")
|
||||
})
|
||||
.expect("expected automatic hyphenation point at \"con-sideration\"");
|
||||
let k = k as usize;
|
||||
let kern = base.clusters[k].kern;
|
||||
assert!(kern < -0.5, "the test font kerns \"ns\": {kern}");
|
||||
let paired_no_hyph: f32 = base.clusters[..=k].iter().map(|c| c.adv).sum();
|
||||
// Wide enough for "word con-" with room to spare so we can measure the hyphen advance.
|
||||
let probe = first_para(&doc(468.0 - (paired_no_hyph + 12.0)));
|
||||
assert_eq!(probe.lines[0].c1, k + 1);
|
||||
let hyph_w = probe.lines[0].hyphen.expect("probe should hyphenate at \"con-\"").2;
|
||||
let paired = paired_no_hyph + hyph_w;
|
||||
let alone = paired - kern;
|
||||
|
||||
// Between the kerned and unkerned widths (plus hyphen): "con-" would overrun the margin
|
||||
// once the "ns" pair is dropped, so the line must fall back to the earlier space.
|
||||
let mid = first_para(&doc(468.0 - (paired + alone) / 2.0));
|
||||
let m0 = &mid.lines[0];
|
||||
assert!(m0.hyphen.is_none(), "hyphenated line {} overran right edge {}", m0.end_x(), m0.right);
|
||||
assert_eq!(m0.stop, "word ".len(), "expected fallback to space break, got {:?}", &text[..m0.stop]);
|
||||
|
||||
// Wide enough for the unkerned letters plus hyphen: the break at "con-" fits inside the margin.
|
||||
let fit = first_para(&doc(468.0 - (alone + 0.004)));
|
||||
let f0 = &fit.lines[0];
|
||||
assert_eq!(f0.c1, k + 1);
|
||||
assert!(f0.hyphen.is_some());
|
||||
assert!(f0.end_x() <= f0.right + 0.01, "end_x {} ran past right edge {}", f0.end_x(), f0.right);
|
||||
assert!((f0.end_x() - alone).abs() < 0.01);
|
||||
}
|
||||
|
||||
@@ -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,13 @@ fn write_attempt(doc: &Document, lay: &DocLayout, opts: &PdfOptions, pages: &[us
|
||||
}
|
||||
}
|
||||
surface.finish();
|
||||
for annotation in annotations {
|
||||
kp.add_annotation(annotation);
|
||||
for (annotation, tag) in annotations {
|
||||
if opts.tagged {
|
||||
let annot_id = kp.add_tagged_annotation(annotation);
|
||||
ex.attach_link_annotation(tag, annot_id);
|
||||
} else {
|
||||
kp.add_annotation(annotation);
|
||||
}
|
||||
}
|
||||
kp.finish();
|
||||
}
|
||||
|
||||
@@ -18,6 +18,29 @@ mod objects;
|
||||
pub(crate) use objects::ObjectLookup;
|
||||
mod text;
|
||||
|
||||
/// Where a link annotation's `OBJR` attaches in the structure tree.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) enum LinkTag {
|
||||
/// Inside an existing `Tag::Link` group at `(para, child)` in `Exporter::tags`, with
|
||||
/// reading-order position `at` as fallback.
|
||||
Group { para: usize, child: usize, at: (usize, usize) },
|
||||
/// Outside any paragraph (for example a header or footer artifact), as its own `Link`
|
||||
/// structure element placed at reading-order position `at`.
|
||||
Standalone((usize, usize)),
|
||||
}
|
||||
|
||||
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)>,
|
||||
/// Reading-order position ([`TagEntry::at`]) where this link was drawn.
|
||||
pub(crate) at: (usize, usize),
|
||||
}
|
||||
|
||||
pub(crate) struct Exporter<'a> {
|
||||
pub(crate) doc: &'a Document,
|
||||
pub(crate) lay: &'a DocLayout,
|
||||
@@ -42,8 +65,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.
|
||||
@@ -194,10 +219,58 @@ 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));
|
||||
}
|
||||
}
|
||||
|
||||
/// Attach a link annotation's `OBJR` identifier to its `Tag::Link` group, or add a standalone
|
||||
/// `Div -> Link` entry holding just the `OBJR` when the link has no paragraph group (such as
|
||||
/// a link drawn inside a header or footer artifact).
|
||||
pub(crate) fn attach_link_annotation(&mut self, tag: LinkTag, annot_id: Identifier) {
|
||||
if let LinkTag::Group { para, child, .. } = tag
|
||||
&& let Some(Node::Group(g)) = self.tags.get_mut(para).and_then(|e| e.children.get_mut(child))
|
||||
{
|
||||
g.children.insert(0, Node::Leaf(annot_id));
|
||||
return;
|
||||
}
|
||||
let at = match tag {
|
||||
LinkTag::Group { at, .. } | LinkTag::Standalone(at) => at,
|
||||
};
|
||||
let g = TagGroup::with_children(Tag::Link, vec![Node::Leaf(annot_id)]);
|
||||
self.tags.push(TagEntry { kind: Tag::Div.into(), children: vec![Node::Group(g)], source: None, at });
|
||||
}
|
||||
|
||||
/// 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, 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)),
|
||||
@@ -231,6 +304,9 @@ impl Exporter<'_> {
|
||||
/// Draws the content of a single page (background, watermark, headers, footers, body items, and comments) onto the surface.
|
||||
pub(crate) fn page(&mut self, s: &mut Surface, page: &Page, w: f32, h: f32) {
|
||||
self.at = (self.at.0.saturating_add(1), 0);
|
||||
// A paragraph's continuation gets its own entry so this page's header links and the
|
||||
// previous page's footer links are read before the continued text.
|
||||
self.tag_index.clear();
|
||||
if let Some(c) = self.doc.settings.page_color
|
||||
&& let Some(p) = rect_path(&Rect::new(0.0, 0.0, w, h))
|
||||
{
|
||||
@@ -253,7 +329,17 @@ impl Exporter<'_> {
|
||||
let dopts = self.opts.display_options();
|
||||
// What the items share (the authors' colours, the clipped cells) is worked out once per page.
|
||||
let shown = ItemDisplay::new(self.doc, page);
|
||||
for it in page.header.iter().chain(page.footer.iter()) {
|
||||
self.at.1 = 0;
|
||||
for it in &page.header {
|
||||
let draws = shown.draws(it, &dopts);
|
||||
self.tagged(s, Role::Artifact(ArtifactType::Other), None, |me, s| {
|
||||
for d in &draws {
|
||||
me.draw(s, d);
|
||||
}
|
||||
});
|
||||
}
|
||||
self.at.1 = usize::MAX;
|
||||
for it in &page.footer {
|
||||
let draws = shown.draws(it, &dopts);
|
||||
self.tagged(s, Role::Artifact(ArtifactType::Other), None, |me, s| {
|
||||
for d in &draws {
|
||||
@@ -262,7 +348,7 @@ impl Exporter<'_> {
|
||||
});
|
||||
}
|
||||
for (i, it) in page.items.iter().enumerate() {
|
||||
self.at.1 = page.reading.get(i).copied().unwrap_or(i);
|
||||
self.at.1 = page.reading.get(i).copied().unwrap_or(i).saturating_add(1).min(usize::MAX - 1);
|
||||
let draws = shown.draws(it, &dopts);
|
||||
match it {
|
||||
Placed::Lines { story, path, para, .. } => {
|
||||
@@ -326,7 +412,7 @@ impl Exporter<'_> {
|
||||
p.text_without(&dropped)
|
||||
}
|
||||
|
||||
/// The structure entry for a paragraph (created on first sight, in reading order).
|
||||
/// The structure entry for a paragraph on this page (created on first sight, in reading order).
|
||||
fn entry(&mut self, story: StoryRef, path: &DocPath, pl: &wordcraft_layout::para::ParaLayout) -> usize {
|
||||
if let Some(i) = self.tag_index.get(&(story, path.clone())) {
|
||||
return *i;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::{
|
||||
Annotation, ClKind, DocPath, Exporter, Fit, HashMap, LineEnd, LinkAnnotation, Outline, OutlineNode, Placed, Point, StoryRef, Target,
|
||||
Annotation, ClKind, DocPath, Exporter, Fit, HashMap, LineEnd, LinkAnnotation, LinkTag, Outline, OutlineNode, Placed, Point, StoryRef, Target,
|
||||
XyzDestination, krilla, write,
|
||||
};
|
||||
|
||||
@@ -53,24 +53,26 @@ 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, LinkTag)> {
|
||||
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,
|
||||
}
|
||||
let Some(t) = self.link_target(&link.target) else { continue };
|
||||
let tag = match link.tag {
|
||||
Some((para, child)) => LinkTag::Group { para, child, at: link.at },
|
||||
None => LinkTag::Standalone(link.at),
|
||||
};
|
||||
v.push(Annotation::new_link(LinkAnnotation::new(rect, t), Some(target.clone())));
|
||||
v.push((Annotation::new_link(LinkAnnotation::new(rect, t), Some(link.target.clone())), 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| prev.at == self.at && 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, at: self.at });
|
||||
self.last_link = Some(self.links.len() - 1);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
@@ -3788,3 +3789,265 @@ fn an_all_blank_row_keeps_its_cells() {
|
||||
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");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_and_footer_link_annotations_are_tagged_on_every_page() {
|
||||
use hayro_syntax::object::{Array, Dict, Name, Object};
|
||||
|
||||
let header_props = CharProps { link: Some("https://header.example.com".into()), ..Default::default() };
|
||||
let footer_props = CharProps { link: Some("https://footer.example.com".into()), ..Default::default() };
|
||||
let body_props = CharProps { link: Some("https://body.example.com".into()), ..Default::default() };
|
||||
|
||||
let mut d = Document::new();
|
||||
d.core.title = "Header and footer links".into();
|
||||
let header_id = d.add_part(wordcraft_doc::PartKind::Header, vec![para_block(Paragraph::with_text("Header site", header_props))]);
|
||||
let footer_id = d.add_part(wordcraft_doc::PartKind::Footer, vec![para_block(Paragraph::with_text("Footer site", footer_props))]);
|
||||
d.last_section.headers.default = Some(header_id);
|
||||
d.last_section.footers.default = Some(footer_id);
|
||||
|
||||
let mut p1 = Paragraph::with_text("Visit ", CharProps::default());
|
||||
p1.insert_text(p1.len(), "Body", &body_props).unwrap();
|
||||
let mut p2 = Paragraph::with_text("Second page", CharProps::default());
|
||||
p2.props.page_break_before = Some(true);
|
||||
d.body = vec![para_block(p1), para_block(p2)];
|
||||
|
||||
let bytes = export(&d, &PdfOptions { compress: false, tagged: true, ..Default::default() }).unwrap();
|
||||
let pdf = hayro_syntax::Pdf::new(bytes).unwrap();
|
||||
assert_eq!(pdf.pages().len(), 2, "expected two pages");
|
||||
|
||||
// Collect every link annotation across both pages and check /StructParent on each.
|
||||
let mut expected_annots: Vec<(usize, String, i32)> = Vec::new();
|
||||
for (page_idx, page) in pdf.pages().iter().enumerate() {
|
||||
let annots = page.raw().get::<Array>(b"Annots").expect("page Annots");
|
||||
for annot in annots.iter::<Dict>() {
|
||||
let sp = annot.get::<i32>(b"StructParent").expect("link annotation missing /StructParent");
|
||||
let id = format!("{:?}", annot.obj_id().expect("indirect annotation"));
|
||||
expected_annots.push((page_idx, id, sp));
|
||||
}
|
||||
}
|
||||
assert_eq!(expected_annots.len(), 5, "page 1 has header+body+footer links, page 2 has header+footer links");
|
||||
|
||||
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_eq!(links.len(), expected_annots.len(), "every link annotation needs a /Link structure element: {links:?}");
|
||||
for (page_idx, annot_id, _) in &expected_annots {
|
||||
assert!(
|
||||
links.iter().any(|(_, objr)| objr.as_deref() == Some(annot_id.as_str())),
|
||||
"page {page_idx} annotation {annot_id} has no /Link OBJR in StructTreeRoot: {links:?}"
|
||||
);
|
||||
}
|
||||
// The 4 header/footer links stay outside artifact content (OBJR only); the body link also holds its MCID.
|
||||
assert_eq!(links.iter().filter(|(mcid, _)| !*mcid).count(), 4, "header/footer links hold only OBJR: {links:?}");
|
||||
assert_eq!(links.iter().filter(|(mcid, _)| *mcid).count(), 1, "body link holds MCID and OBJR: {links:?}");
|
||||
|
||||
// Verify /ParentTree maps every annotation's /StructParent to a /Link structure element.
|
||||
let parent_tree = struct_tree.get::<Dict>(b"ParentTree").expect("ParentTree");
|
||||
let nums = parent_tree.get::<Array>(b"Nums").expect("ParentTree Nums");
|
||||
let num_items: Vec<Object> = nums.iter::<Object>().collect();
|
||||
for (page_idx, annot_id, sp) in &expected_annots {
|
||||
let mut parent_role = None;
|
||||
for pair in num_items.as_chunks::<2>().0 {
|
||||
if let [Object::Number(k), Object::Dict(elem)] = pair
|
||||
&& k.as_i64() == i64::from(*sp)
|
||||
{
|
||||
parent_role = elem.get::<Name>(b"S").map(|s| s.as_str().to_string());
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
parent_role.as_deref(),
|
||||
Some("Link"),
|
||||
"page {page_idx} annotation {annot_id} /StructParent {sp} must point to /Link in /ParentTree"
|
||||
);
|
||||
}
|
||||
|
||||
// Verify reading order under Document: page 1 header link -> body P -> page 1 footer link -> page 2 header link -> body P -> page 2 footer link.
|
||||
let mut tops: Vec<Dict> = match struct_tree.get::<Object>(b"K") {
|
||||
Some(Object::Array(a)) => a.iter::<Dict>().collect(),
|
||||
Some(Object::Dict(d)) => vec![d],
|
||||
_ => Vec::new(),
|
||||
};
|
||||
while let [only] = tops.as_slice()
|
||||
&& only.get::<Name>(b"S").is_some_and(|s| s.as_str() == "Document")
|
||||
{
|
||||
tops = match only.get::<Object>(b"K") {
|
||||
Some(Object::Array(a)) => a.iter::<Dict>().collect(),
|
||||
Some(Object::Dict(d)) => vec![d],
|
||||
_ => Vec::new(),
|
||||
};
|
||||
}
|
||||
let top_roles: Vec<String> = tops.iter().map(|d| d.get::<Name>(b"S").map(|s| s.as_str().to_string()).unwrap_or_default()).collect();
|
||||
assert_eq!(top_roles, vec!["Div", "P", "Div", "Div", "P", "Div"], "header link before body, footer link after body");
|
||||
}
|
||||
|
||||
/// A paragraph's continuation must follow the footer and header between its pages.
|
||||
#[test]
|
||||
fn spanning_paragraph_links_follow_page_reading_order() {
|
||||
use hayro_syntax::object::{Array, Dict, Name, Object};
|
||||
|
||||
let mut d = Document::new();
|
||||
let linked = |text: &str, target: &str| {
|
||||
Paragraph::with_text(text, CharProps { link: Some(format!("https://{target}.example.com")), ..Default::default() })
|
||||
};
|
||||
let header = d.add_part(wordcraft_doc::PartKind::Header, vec![para_block(linked("Header", "header"))]);
|
||||
let footer = d.add_part(wordcraft_doc::PartKind::Footer, vec![para_block(linked("Footer", "footer"))]);
|
||||
d.last_section.headers.default = Some(header);
|
||||
d.last_section.footers.default = Some(footer);
|
||||
d.body = vec![para_block(linked("First page\u{c}Second page", "body"))];
|
||||
|
||||
let bytes = export(&d, &PdfOptions { compress: false, tagged: true, ..Default::default() }).unwrap();
|
||||
let pdf = hayro_syntax::Pdf::new(bytes).unwrap();
|
||||
assert_eq!(pdf.pages().len(), 2);
|
||||
let mut expected = Vec::new();
|
||||
for page in pdf.pages().iter() {
|
||||
let annots: Vec<Dict> = page.raw().get::<Array>(b"Annots").unwrap().iter::<Dict>().collect();
|
||||
assert_eq!(annots.len(), 3, "each page has header, body and footer links");
|
||||
// Header and footer are drawn before the body, but read around it.
|
||||
for i in [0, 2, 1] {
|
||||
expected.push(format!("{:?}", annots[i].obj_id().unwrap()));
|
||||
}
|
||||
}
|
||||
fn collect(o: Object<'_>, out: &mut Vec<String>) {
|
||||
match o {
|
||||
Object::Array(a) => a.iter::<Object>().for_each(|o| collect(o, out)),
|
||||
Object::Dict(d) => {
|
||||
if d.get::<Name>(b"Type").is_some_and(|t| t.as_ref() == b"OBJR") {
|
||||
out.push(format!("{:?}", d.get::<Dict>(b"Obj").unwrap().obj_id().unwrap()));
|
||||
} else if let Some(k) = d.get::<Object>(b"K") {
|
||||
collect(k, out);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let root = pdf.xref().get::<Dict>(pdf.xref().root_id()).unwrap();
|
||||
let tree = root.get::<Dict>(b"StructTreeRoot").unwrap();
|
||||
let mut actual = Vec::new();
|
||||
collect(tree.get::<Object>(b"K").unwrap(), &mut actual);
|
||||
assert_eq!(actual, expected, "links must follow page reading order across a split paragraph");
|
||||
}
|
||||
|
||||
@@ -16,7 +16,8 @@ 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-html = { workspace = true }
|
||||
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 +77,7 @@ craft-ui-test-kit = { workspace = true }
|
||||
craft = { workspace = true, features = ["ui-testing"] }
|
||||
|
||||
[build-dependencies]
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", features = ["subset"] }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", features = ["subset"] }
|
||||
serde_json = { workspace = true }
|
||||
toml = "1"
|
||||
|
||||
|
||||
@@ -266,7 +266,9 @@ fn main() {
|
||||
}
|
||||
let mem_after_typing = memory_mb();
|
||||
|
||||
// Edit/Undo burst: 40 discrete paragraph insertions followed by 40 undos.
|
||||
// Edit/Undo burst: 40 discrete short-text insertions (" {k}") at the current caret (the first
|
||||
// table cell when the document has a table, otherwise the target paragraph), each in its own
|
||||
// undo group, followed by 40 undos.
|
||||
let mut edit_burst = Vec::new();
|
||||
let mut undo_burst = Vec::new();
|
||||
for k in 0..40 {
|
||||
|
||||
@@ -2,8 +2,8 @@ use super::services::Services;
|
||||
use super::state::{AutoSaveBlock, PromptSave, keeps_everything};
|
||||
use super::{
|
||||
DEFAULT_TAB, MAX_DICTIONARY, MAX_RECENT, SaveInFlight, Session, Status, Value, WordApp, applied_font, canvas, chrome, crop, dialogs, documents,
|
||||
file_dialogs, i18n, json, panes, paste_picture, printing, push_recent_font, read_aloud, recent_fonts_from, ribbon, system_clipboard, table_pen,
|
||||
theme, updates_ui, window_ui, windows, zotero,
|
||||
file_dialogs, i18n, json, panes, printing, push_recent_font, read_aloud, recent_fonts_from, ribbon, system_clipboard, table_pen, theme,
|
||||
updates_ui, window_ui, windows, zotero,
|
||||
};
|
||||
use craft::platform::clock::monotonic_ms;
|
||||
use craft::theme::ComponentSet;
|
||||
@@ -133,9 +133,13 @@ impl WordApp {
|
||||
user_origin: false,
|
||||
read_aloud_error: None,
|
||||
autosave_path: None,
|
||||
autosave_choice: None,
|
||||
read_from: None,
|
||||
saves_in_flight: Vec::new(),
|
||||
fallback_chooser: false,
|
||||
font_generation: wordcraft_fonts::FontDb::global().generation(),
|
||||
#[cfg(test)]
|
||||
font_catalog: None,
|
||||
recovery_seen: false,
|
||||
no_document: None,
|
||||
parked: Default::default(),
|
||||
|
||||
@@ -54,17 +54,19 @@ const GATED_UI_COMMANDS: &[(&str, &str)] = &[
|
||||
];
|
||||
|
||||
/// Word feature catalog entries whose command is not yet registered in `registry`: each gets a
|
||||
/// catalog entry without a chord (preventing unregistered-command warnings) and a disabled state
|
||||
/// until an engine command takes its id.
|
||||
fn unimplemented_catalog_commands(registry: &wordcraft_engine::Registry) -> impl Iterator<Item = (&'static str, &'static str)> + '_ {
|
||||
/// catalog entry with its ribbon path and no default chord, plus a disabled state until an engine
|
||||
/// command takes its id.
|
||||
fn unimplemented_catalog_commands(
|
||||
registry: &wordcraft_engine::Registry,
|
||||
) -> impl Iterator<Item = (&'static str, &'static str, [&'static str; 2])> + '_ {
|
||||
let mut seen = HashSet::new();
|
||||
wordcraft_engine::catalog::CATALOG.lines().filter_map(move |line| {
|
||||
let mut parts = line.split('|');
|
||||
let _tab = parts.next()?;
|
||||
let _group = parts.next()?;
|
||||
let tab = parts.next()?;
|
||||
let group = parts.next()?;
|
||||
let feature = parts.next()?;
|
||||
let id = parts.next()?;
|
||||
(registry.get(id).is_none() && seen.insert(id)).then_some((id, feature))
|
||||
(registry.get(id).is_none() && seen.insert(id)).then_some((id, feature, [tab, group]))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -116,7 +118,7 @@ impl CommandStatesCache {
|
||||
.chain(GATED_UI_COMMANDS.iter().map(|(id, _)| *id))
|
||||
.map(|id| (id, CommandRef::new(id), None))
|
||||
.collect();
|
||||
let unimplemented = unimplemented_catalog_commands(®istry).map(|(id, _)| (id, CommandRef::new(id), None)).collect();
|
||||
let unimplemented = unimplemented_catalog_commands(®istry).map(|(id, ..)| (id, CommandRef::new(id), None)).collect();
|
||||
let commands_dialog = (CommandRef::with_params("ui.dialog", json!({"name": "commands"})), None);
|
||||
let unavailable_hint = crate::widgets::command_hint("", "", Some("")).map(Arc::from);
|
||||
CommandStatesCache { registry, lang, registered, ui_commands, unimplemented, commands_dialog, unavailable_hint, hints: HashMap::new() }
|
||||
@@ -217,9 +219,9 @@ impl WordApp {
|
||||
for (id, label) in GATED_UI_COMMANDS {
|
||||
defs.push(CommandDef::new(CommandRef::new(*id), tl!(*label), Scope::app()));
|
||||
}
|
||||
for (id, feature) in unimplemented_catalog_commands(®istry) {
|
||||
for (id, feature, path) in unimplemented_catalog_commands(®istry) {
|
||||
if seen.insert(id) {
|
||||
defs.push(CommandDef::new(CommandRef::new(id), tl!(feature), Scope::app()));
|
||||
defs.push(CommandDef::new(CommandRef::new(id), tl!(feature), Scope::app()).with_path(path.map(str::to_owned).into()));
|
||||
}
|
||||
}
|
||||
// Word's Alt chords (Alt+Q, Alt+F7, Ctrl+Alt+1…) fire while the person types in the page:
|
||||
|
||||
@@ -5,10 +5,10 @@ use craft::quit::{CloseAnswer, CloseScope};
|
||||
|
||||
use super::command_board::command_enabled;
|
||||
use super::{
|
||||
MAX_RECENT, SaveInFlight, Value, WordApp, applied_font, chrome, crop, dialogs, file_dialogs, i18n, json, keeps_everything, panes, paste_picture,
|
||||
printing, push_recent_font, system_clipboard, table_pen, theme, zotero,
|
||||
MAX_RECENT, SaveInFlight, Value, WordApp, applied_font, chrome, crop, dialogs, file_dialogs, i18n, json, keeps_everything, panes, printing,
|
||||
push_recent_font, system_clipboard, table_pen, theme, zotero,
|
||||
};
|
||||
use crate::colors;
|
||||
use crate::{colors, paste_picture};
|
||||
|
||||
/// The document's own save stamps: zoom, last-modified-by, created, modified and revision.
|
||||
type SaveStamps = (Option<wordcraft_doc::Zoom>, String, String, String, u32);
|
||||
@@ -71,24 +71,16 @@ impl WordApp {
|
||||
// PLAN: assumed shell-w8's `begin_closing(scope, documents, then, params) -> Result<Value, String>` opens the prompt.
|
||||
return self.begin_closing(CloseScope::Close, vec![self.session.document_id()], id.to_string(), params);
|
||||
}
|
||||
// The ribbon and context-menu Paste commands send no text: read the system clipboard's, as
|
||||
// Ctrl+V's paste event carries it (#584), and its HTML and RTF, which egui's paste event
|
||||
// doesn't carry (#687).
|
||||
// All ordinary Paste controls use the same system clipboard formats.
|
||||
let mut params = params;
|
||||
if let Some(r) = system_clipboard::fill(self, id, &mut params) {
|
||||
return r;
|
||||
}
|
||||
// Paste without system clipboard text: a picture there is newer than our own copy (copying
|
||||
// here replaces it with text), so it wins (#45).
|
||||
if id == "edit.paste"
|
||||
&& params.get("text").is_none()
|
||||
&& let Some(r) = paste_picture::paste(self)
|
||||
{
|
||||
return r;
|
||||
}
|
||||
let bitmap_if_empty = match system_clipboard::fill(self, id, &mut params) {
|
||||
system_clipboard::PasteFill::Continue => false,
|
||||
system_clipboard::PasteFill::BitmapIfEmpty => true,
|
||||
system_clipboard::PasteFill::Handled(result) => return result,
|
||||
};
|
||||
let applied = applied_font(id, ¶ms);
|
||||
let previous = std::mem::replace(&mut self.user_origin, true);
|
||||
let r = self.execute_user(id, params);
|
||||
let r = if bitmap_if_empty { self.execute_command(id, params, true) } else { self.execute_user(id, params) };
|
||||
self.user_origin = previous;
|
||||
// A save error already on the status line is the reason to see; the refusal shows otherwise.
|
||||
if let (Some(e), true) = (refused, r.is_ok()) {
|
||||
@@ -158,6 +150,10 @@ impl WordApp {
|
||||
/// 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> {
|
||||
self.execute_command(id, params, false)
|
||||
}
|
||||
|
||||
fn execute_command(&mut self, id: &str, params: Value, bitmap_if_empty: bool) -> Result<Value, String> {
|
||||
self.clear_command_targets(id);
|
||||
if let Some(error) = self.document_required_error(id) {
|
||||
return Err(error);
|
||||
@@ -176,7 +172,11 @@ impl WordApp {
|
||||
return Err(e.into());
|
||||
}
|
||||
if id == "file.autosave" {
|
||||
return self.set_autosave(¶ms);
|
||||
let r = self.set_autosave(¶ms);
|
||||
if let Err(e) = &r {
|
||||
self.status(e.clone());
|
||||
}
|
||||
return r;
|
||||
}
|
||||
if let Some(r) = table_pen::toggle(self, id, ¶ms) {
|
||||
return r;
|
||||
@@ -283,11 +283,17 @@ impl WordApp {
|
||||
let math_session = self.session.math.as_ref().map(|m| m.session);
|
||||
let composing_before = !self.canvas.ime_preedit.is_empty();
|
||||
let old_path = self.session.path.clone();
|
||||
let r = if self.ime_origin {
|
||||
self.session.run_ime(id, ¶ms).map_err(|e| e.to_string())
|
||||
} else {
|
||||
self.session.run(id, ¶ms).map_err(|e| e.to_string())
|
||||
};
|
||||
let r = if self.ime_origin { self.session.run_ime(id, ¶ms) } else { self.session.run(id, ¶ms) };
|
||||
// Only the engine's no-content result can fall back. Protection and insertion failures
|
||||
// still report their own error, and the empty paste did not create an undo step.
|
||||
if bitmap_if_empty
|
||||
&& matches!(&r, Err(wordcraft_engine::CmdError::ClipboardEmpty))
|
||||
&& let Some(clip) = system_clipboard::handle(self)
|
||||
&& let Some(png) = paste_picture::bitmap_png(&clip).inspect_err(|e| self.status(e.clone()))?
|
||||
{
|
||||
return paste_picture::insert_bitmap(self, &png);
|
||||
}
|
||||
let r = r.map_err(|e| e.to_string());
|
||||
if self.session.ime_body_epoch() != body_epoch {
|
||||
self.canvas.ime_interrupted_preedit |= composing_before;
|
||||
// The body (or the whole document) was replaced under the same id — setText, a
|
||||
@@ -326,13 +332,8 @@ impl WordApp {
|
||||
self.recovery_seen = true;
|
||||
self.sync_document();
|
||||
}
|
||||
// An explicit save to the document's own file lets AutoSave keep writing there.
|
||||
if let Ok(v) = &r
|
||||
&& matches!(id, "file.save" | "file.saveAs")
|
||||
&& v.get("saved").and_then(Value::as_bool) == Some(true)
|
||||
&& v.get("path").and_then(Value::as_str).map(std::path::Path::new) == self.session.path.as_deref()
|
||||
{
|
||||
self.autosave_path = self.session.path.clone();
|
||||
if let Ok(v) = &r {
|
||||
self.note_file_on_disk(id, ¶ms, v);
|
||||
}
|
||||
// A Markdown file edited in the formatted view was written out again, not kept as it was.
|
||||
if let Ok(v) = &r
|
||||
@@ -349,6 +350,9 @@ impl WordApp {
|
||||
if self.autosave_path.as_ref() == Some(&old) {
|
||||
self.autosave_path = self.session.path.clone();
|
||||
}
|
||||
if self.read_from.as_ref() == Some(&old) {
|
||||
self.read_from = self.session.path.clone();
|
||||
}
|
||||
let old = old.to_string_lossy();
|
||||
self.ui.recent.retain(|r| *r != old);
|
||||
}
|
||||
@@ -434,6 +438,25 @@ impl WordApp {
|
||||
r
|
||||
}
|
||||
|
||||
/// Which file on disk the document is in, after `file.save`, `file.saveAs` or `file.open`.
|
||||
fn note_file_on_disk(&mut self, id: &str, params: &Value, v: &Value) {
|
||||
// A save makes the file eligible for AutoSave without changing the document's switch choice.
|
||||
if matches!(id, "file.save" | "file.saveAs")
|
||||
&& v.get("saved").and_then(Value::as_bool) == Some(true)
|
||||
&& v.get("path").and_then(Value::as_str).map(std::path::Path::new) == self.session.path.as_deref()
|
||||
{
|
||||
self.autosave_path = self.session.path.clone();
|
||||
self.read_from = self.session.path.clone();
|
||||
}
|
||||
// A file read from disk may have AutoSave turned on for it; one opened from bytes only
|
||||
// names a file it never read.
|
||||
// `file.open` without a path only asks for the picker, and `data` that isn't a string is
|
||||
// ignored (the file is read from disk).
|
||||
if id == "file.open" && params.get("path").and_then(Value::as_str).is_some() && v.get("alreadyOpen").and_then(Value::as_bool) == Some(false) {
|
||||
self.read_from = if params.get("data").and_then(Value::as_str).is_some() { None } else { self.session.path.clone() };
|
||||
}
|
||||
}
|
||||
|
||||
fn after_command(&mut self, id: &str) {
|
||||
self.canvas.glide.restart(craft::platform::clock::monotonic_ms());
|
||||
if id == "view.outline" {
|
||||
@@ -848,6 +871,8 @@ impl WordApp {
|
||||
};
|
||||
return Some(self.answer_save_changes(answer));
|
||||
}
|
||||
// The app menu's Quit (⌘Q): asks about each unsaved document, as the Dock's Quit does.
|
||||
"ui.quit" => json!({"quit": self.quit()}),
|
||||
"ui.openFileDialog" => {
|
||||
self.open_dialog();
|
||||
json!({})
|
||||
@@ -1298,6 +1323,7 @@ pub(crate) fn works_without_document(id: &str) -> bool {
|
||||
| "ui.animations"
|
||||
| "ui.language"
|
||||
| "ui.saveChanges"
|
||||
| "ui.quit"
|
||||
| "ui.openFileDialog"
|
||||
| "ui.printCancel"
|
||||
| "ui.fileBrowser"
|
||||
|
||||
@@ -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
|
||||
@@ -541,9 +551,27 @@ impl WordApp {
|
||||
if let Some(result) = self.raise_closing() {
|
||||
return Ok(result);
|
||||
}
|
||||
if self.closes_only_its_window("file.close", params) {
|
||||
// `save: true` still writes the document, which stays open in the other windows.
|
||||
if params.get("save").and_then(Value::as_bool) == Some(true)
|
||||
&& let Some(pending) = self.save_for_close()?
|
||||
{
|
||||
return Ok(pending);
|
||||
}
|
||||
}
|
||||
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 +606,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
|
||||
@@ -662,7 +708,8 @@ impl WordApp {
|
||||
}
|
||||
|
||||
/// Why AutoSave can't cover the document, or `None` when it can: it writes only a file the
|
||||
/// user saved to in this session, in a format that keeps everything, and never in the browser
|
||||
/// user saved to in this session or explicitly enabled after opening it from disk. The format
|
||||
/// must keep everything, and AutoSave never writes in the browser
|
||||
/// (a page can't write to the user's files; saving there is a download, #176).
|
||||
pub fn autosave_block(&self) -> Option<AutoSaveBlock> {
|
||||
if self.browser_saves() {
|
||||
@@ -673,7 +720,8 @@ impl WordApp {
|
||||
let name = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
|
||||
return Some(AutoSaveBlock::Format { name });
|
||||
}
|
||||
if !self.saved_here() {
|
||||
let opened_and_enabled = self.autosave_choice == Some(true) && self.read_from.as_ref() == Some(path);
|
||||
if !self.saved_here() && !opened_and_enabled {
|
||||
return Some(AutoSaveBlock::NotSavedHere);
|
||||
}
|
||||
None
|
||||
@@ -681,17 +729,30 @@ impl WordApp {
|
||||
|
||||
/// Whether AutoSave covers the document: it is on and nothing blocks it ([`Self::autosave_block`]).
|
||||
pub fn autosaves(&self) -> bool {
|
||||
self.autosave && self.autosave_block().is_none()
|
||||
self.autosave && self.autosave_choice != Some(false) && self.autosave_block().is_none()
|
||||
}
|
||||
|
||||
/// What the AutoSave switch can't lift: [`Self::autosave_block`], less a file read from disk
|
||||
/// here, which the switch turns on (#3307). A document opened from bytes stays blocked.
|
||||
pub fn autosave_switch_block(&self) -> Option<AutoSaveBlock> {
|
||||
self.autosave_block().filter(|b| *b != AutoSaveBlock::NotSavedHere || self.read_from != self.session.path)
|
||||
}
|
||||
|
||||
/// `file.autosave` (the AutoSave switch, and scripts): `value` turns AutoSave on or off;
|
||||
/// without it, it toggles what the switch shows. Turning it on for a document AutoSave can't
|
||||
/// cover is an error that says why, instead of a switch that is on but saves nothing (#196).
|
||||
/// Turning it on for a file only opened here is the go-ahead a save gives (#3307), when the
|
||||
/// document was read from that file; turning it off withdraws the go-ahead for this document.
|
||||
pub(super) fn set_autosave(&mut self, params: &Value) -> Result<Value, String> {
|
||||
let on = params.get("value").and_then(Value::as_bool).unwrap_or(!self.autosaves());
|
||||
if on && let Some(block) = self.autosave_block() {
|
||||
let on = match params.get("value") {
|
||||
None => !self.autosaves(),
|
||||
Some(Value::Bool(on)) => *on,
|
||||
Some(_) => return Err("`value` must be true or false".into()),
|
||||
};
|
||||
if on && let Some(block) = self.autosave_switch_block() {
|
||||
return Err(block.reason());
|
||||
}
|
||||
self.autosave_choice = Some(on);
|
||||
self.autosave = on;
|
||||
self.session.autosave = on;
|
||||
Ok(json!({"value": on}))
|
||||
@@ -705,6 +766,7 @@ impl WordApp {
|
||||
if let Err(e) = self.session.run("file.save", &json!({})) {
|
||||
log::warn!("AutoSave failed: {e}");
|
||||
self.autosave_path = None;
|
||||
self.autosave_choice = None;
|
||||
self.status(i18n::fmt(tl!("AutoSave failed: {error}. Save the document to turn AutoSave back on."), &[("error", &e.to_string())]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,6 +46,7 @@ mod navigation;
|
||||
mod pages;
|
||||
mod reading;
|
||||
mod reading_metrics;
|
||||
mod revision_tip;
|
||||
pub(crate) mod rulers;
|
||||
mod source;
|
||||
mod story;
|
||||
|
||||
@@ -30,7 +30,7 @@ struct BalloonItems {
|
||||
}
|
||||
|
||||
/// Comment balloons in the markup area right of each page, joined to their anchors, with each comment's replies in
|
||||
/// its card. Clicking a card selects it, like Word: its text becomes editable in place, with Reply, Resolve and
|
||||
/// its card. Clicking a card selects it, like Word: a double click makes its text editable in place, with Reply, Resolve and
|
||||
/// Delete (the same commands as the Comments pane).
|
||||
pub(crate) fn balloons(app: &mut WordApp, ui: &mut Ui, out: &craft::pages::ui::PageViewOutput, layout: &DocLayout) {
|
||||
app.canvas.balloon_rects.clear();
|
||||
@@ -63,6 +63,26 @@ pub(crate) fn balloons(app: &mut WordApp, ui: &mut Ui, out: &craft::pages::ui::P
|
||||
for edit in shown.edits {
|
||||
apply(app, &cards, edit);
|
||||
}
|
||||
open_edit_on_double_click(app, ui);
|
||||
}
|
||||
|
||||
/// A double click on the selected card's own text opens its comment for editing, as craft's comments pane does. A click
|
||||
/// that lands in a field or on a button (Reply, Resolve, the menu) is not one.
|
||||
// lean: mouse only; a keyboard path (Enter/F2 on the selected card) is a follow-up.
|
||||
fn open_edit_on_double_click(app: &mut WordApp, ui: &Ui) {
|
||||
let Some(id) = app.canvas.selected_balloon() else { return };
|
||||
if app.canvas.comments.editing.is_some() || ui.ctx().egui_wants_keyboard_input() {
|
||||
return;
|
||||
}
|
||||
let at = ui.input(|i| i.pointer.button_double_clicked(egui::PointerButton::Primary).then(|| i.pointer.interact_pos())).flatten();
|
||||
let Some(at) = at else { return };
|
||||
let on_card = app.canvas.balloon_rects.iter().any(|(i, r)| *i == id && r.contains(at));
|
||||
if !on_card || !crate::app::command_board::command_enabled(app, "review.editComment") {
|
||||
return;
|
||||
}
|
||||
let Some(c) = app.session.doc.comments.get(&id) else { return };
|
||||
let text = app.session.doc.plain_text(StoryRef::Part(c.part));
|
||||
app.canvas.comments.edit(thread_id(id), 0, text);
|
||||
}
|
||||
|
||||
/// Applies what a card reported through the commands the Comments pane uses.
|
||||
@@ -243,25 +263,17 @@ fn write_back(app: &mut WordApp, id: u32) {
|
||||
let _ = crate::panes::commit_reply(app, id);
|
||||
}
|
||||
|
||||
/// Makes comment `id` the selected card with its own text open for editing, writing back the draft of the one edited
|
||||
/// before. The card selects itself on a click; this opens its edit so the field has the keyboard.
|
||||
/// Makes comment `id` the selected card, writing back the draft of the one edited before. As in Word, selecting a card
|
||||
/// puts no message into edit (that hides its Reply); an edit starts on a double click on the selected card.
|
||||
fn focus_balloon(app: &mut WordApp, id: u32) {
|
||||
let before = app.canvas.comments.editing.as_ref().and_then(|(t, ..)| app_id(*t)).filter(|b| *b != id);
|
||||
if let Some(before) = before {
|
||||
write_back(app, before);
|
||||
}
|
||||
// Where comments can't change (a read-only document) the card is selected with no edit open: nothing is typed.
|
||||
let editable = crate::app::command_board::command_enabled(app, "review.editComment");
|
||||
let text = app.session.doc.comments.get(&id).filter(|_| editable).map(|c| app.session.doc.plain_text(StoryRef::Part(c.part)));
|
||||
let thread = thread_id(id);
|
||||
let comments = &mut app.canvas.comments;
|
||||
comments.selected = craft::behavior::Selection::single(thread);
|
||||
if comments.editing.as_ref().is_none_or(|(t, ..)| *t != thread) {
|
||||
comments.editing = text.map(|t| (thread, 0, t));
|
||||
}
|
||||
app.canvas.comments.selected = craft::behavior::Selection::single(thread_id(id));
|
||||
}
|
||||
|
||||
/// Select a comment's balloon (its text gets the keyboard), writing back any edit in the one selected before.
|
||||
/// Select a comment's balloon (no edit opens), writing back any edit in the one selected before.
|
||||
pub fn select_balloon(app: &mut WordApp, id: u32) {
|
||||
if app.canvas.selected_balloon() == Some(id) {
|
||||
return;
|
||||
|
||||
@@ -9,6 +9,7 @@ use craft::ui::canvas::{CanvasTool, ToolAction, ToolContext, ToolPath, ToolPoint
|
||||
use craft::ui::primitives::Draw;
|
||||
|
||||
use super::links::{field_showing_code, follow_link, is_generated_bookmark_link, link_under};
|
||||
use super::revision_tip::revision_under;
|
||||
use super::story::{enters_header_footer, in_text_box, part_kind, text_box_host};
|
||||
use super::{CanvasState, DocLayout, PartKind, Pos, Pos2, StoryRef, WordApp, json};
|
||||
use crate::objects::ObjectGesture;
|
||||
@@ -163,12 +164,23 @@ impl<'a> PageTextTool<'a> {
|
||||
let (page, x, y) = page_of(self.body.pages, pos)?;
|
||||
let layout = &*self.layout;
|
||||
// A linked picture or shape under the pointer comes first: it lies over the text (#5267).
|
||||
let story = app.session.sel.focus.story;
|
||||
// The text is the story under the pointer, as for the tracked change tip that follows.
|
||||
let story = pointer_story(app, layout, page, x, y, app.session.sel.focus.story);
|
||||
let link = crate::objects::link_at(app, layout, self.body, pos)
|
||||
.or_else(|| layout.hit(page, x, y, story).and_then(|at| link_under(app, layout, page, x, y, &at)))?;
|
||||
let target = if is_generated_bookmark_link(&link) { tl!("Current Document").to_string() } else { link };
|
||||
Some(format!("{target}\n{}", crate::i18n::fmt(tl!("{key}+Click to follow link"), &[("key", self.link_key)])))
|
||||
}
|
||||
|
||||
/// The tip for the tracked change under `pos`: its kind, author and time (#7887).
|
||||
fn revision_tip(&self, pos: Pos2) -> Option<String> {
|
||||
let (page, x, y) = page_of(self.body.pages, pos)?;
|
||||
let layout = &*self.layout;
|
||||
// The story under the pointer, as a click there takes it: a note or text box over the body.
|
||||
let story = pointer_story(&*self.app, layout, page, x, y, self.app.session.sel.focus.story);
|
||||
let at = layout.hit(page, x, y, story)?;
|
||||
revision_under(&*self.app, layout, page, x, y, &at)
|
||||
}
|
||||
}
|
||||
|
||||
impl CanvasTool for PageTextTool<'_> {
|
||||
@@ -249,7 +261,8 @@ impl CanvasTool for PageTextTool<'_> {
|
||||
|
||||
fn hover(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) {
|
||||
// PLAN: assumed `ToolContext::tip(&mut self, tip: impl Into<Tooltip>)` (canvas-w1, S-L238).
|
||||
if let Some(tip) = self.link_tip(pointer.pos) {
|
||||
// A link's tip comes first: following the link is what a click there can do.
|
||||
if let Some(tip) = self.link_tip(pointer.pos).or_else(|| self.revision_tip(pointer.pos)) {
|
||||
cx.tip(tip);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
//! The hover tip on a tracked change (#7887): what kind of change it is, who made it and when.
|
||||
|
||||
use super::{DocLayout, Pos, WordApp};
|
||||
use wordcraft_doc::props::CharProps;
|
||||
use wordcraft_layout::display::MarkupOptions;
|
||||
|
||||
/// The tip for the tracked change under the pointer at (x, y) on `page`, where `pos` is the caret
|
||||
/// position the point hits: its kind, its author and its time, a line each. Only changes the page
|
||||
/// marks count: none with markup hidden, insertions, deletions and moves while Show Markup shows
|
||||
/// them, formatting changes while it shows formatting. As with a link, the point must be on a
|
||||
/// character, not beside, above or below it: on the changed character itself, or anywhere in the
|
||||
/// text of a paragraph whose own formatting changed (its alignment, indents…) when the character
|
||||
/// has no change of its own.
|
||||
pub(super) fn revision_under(app: &WordApp, layout: &DocLayout, page: usize, x: f32, y: f32, pos: &Pos) -> Option<String> {
|
||||
let session = &app.session;
|
||||
if !session.view.show_markup {
|
||||
return None;
|
||||
}
|
||||
let markup = &session.prefs.markup;
|
||||
let doc = &session.doc;
|
||||
let para = doc.para_at(pos)?;
|
||||
let para_change = para.props.fmt_change.as_ref().filter(|_| markup.formatting).map(|c| (c.rev, tl!("Formatted")));
|
||||
let at = wordcraft_geom::Point::new(x, y);
|
||||
// The caret falls between characters: the one under the point is on either side of it.
|
||||
[(pos.off, para.next_boundary(pos.off)), (para.prev_boundary(pos.off), pos.off)].into_iter().filter(|(a, b)| a < b).find_map(|(a, b)| {
|
||||
let (rev, kind) = change_of(para.props_of_char(a), markup, |i| doc.move_name(Some(i)).is_some()).or(para_change)?;
|
||||
let rev = doc.revisions.get(usize::try_from(rev).ok()?)?;
|
||||
let (from, to) = (Pos { off: a, ..pos.clone() }, Pos { off: b, ..pos.clone() });
|
||||
let hit = layout.selection_rects(doc, &from, &to, page).into_iter().any(|(pi, r)| pi == page && r.contains(at));
|
||||
hit.then(|| tip(kind, &rev.author, &crate::local_time::revision_time(rev)))
|
||||
})
|
||||
}
|
||||
|
||||
/// The revision a character's marks point to and what to call it, when the markup shown marks it.
|
||||
/// A deletion lies over an insertion it removes (inserted, then deleted by someone else): the
|
||||
/// deletion is the change the page shows.
|
||||
fn change_of(props: &CharProps, markup: &MarkupOptions, is_move: impl Fn(u32) -> bool) -> Option<(u32, &'static str)> {
|
||||
if markup.insertions_deletions {
|
||||
if let Some(i) = props.del {
|
||||
return Some((i, if is_move(i) { tl!("Moved from") } else { tl!("Deleted") }));
|
||||
}
|
||||
if let Some(i) = props.ins {
|
||||
return Some((i, if is_move(i) { tl!("Moved to") } else { tl!("Inserted") }));
|
||||
}
|
||||
}
|
||||
props.fmt_change.as_ref().filter(|_| markup.formatting).map(|c| (c.rev, tl!("Formatted")))
|
||||
}
|
||||
|
||||
/// The tip's lines: the change's kind, its author (or "Author" when the file names none, as the
|
||||
/// balloons do) and its time, left out when the file gives none.
|
||||
fn tip(kind: &str, author: &str, when: &str) -> String {
|
||||
let author = if author.trim().is_empty() { tl!("Author") } else { author };
|
||||
let mut lines = vec![kind, author];
|
||||
if !when.is_empty() {
|
||||
lines.push(when);
|
||||
}
|
||||
lines.join("\n")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use wordcraft_doc::props::PropChange;
|
||||
|
||||
/// A deletion over an insertion is the change shown; formatting counts only while the markup
|
||||
/// shows formatting, and insertions and deletions only while it shows them.
|
||||
#[test]
|
||||
fn the_shown_markup_picks_the_change() {
|
||||
let all = MarkupOptions { insertions_deletions: true, formatting: true, ..Default::default() };
|
||||
let no_move = |_| false;
|
||||
let both = CharProps { ins: Some(0), del: Some(1), ..Default::default() };
|
||||
assert_eq!(change_of(&both, &all, no_move), Some((1, "Deleted")));
|
||||
assert_eq!(change_of(&both, &all, |i| i == 1), Some((1, "Moved from")));
|
||||
let inserted = CharProps { ins: Some(2), ..Default::default() };
|
||||
assert_eq!(change_of(&inserted, &all, no_move), Some((2, "Inserted")));
|
||||
assert_eq!(change_of(&inserted, &all, |_| true), Some((2, "Moved to")));
|
||||
let formatted = CharProps { fmt_change: PropChange::boxed(3, CharProps::default()), ..Default::default() };
|
||||
assert_eq!(change_of(&formatted, &all, no_move), Some((3, "Formatted")));
|
||||
assert_eq!(change_of(&formatted, &MarkupOptions { formatting: false, ..all.clone() }, no_move), None);
|
||||
assert_eq!(change_of(&inserted, &MarkupOptions { insertions_deletions: false, ..all.clone() }, no_move), None);
|
||||
assert_eq!(change_of(&CharProps::default(), &all, no_move), None);
|
||||
}
|
||||
|
||||
/// The tip's lines; an unnamed author reads "Author", and a missing time is left out.
|
||||
#[test]
|
||||
fn the_tip_names_kind_author_and_time() {
|
||||
assert_eq!(tip("Inserted", "Ada", "2026-11-20 14:05"), "Inserted\nAda\n2026-11-20 14:05");
|
||||
assert_eq!(tip("Deleted", " ", ""), "Deleted\nAuthor");
|
||||
}
|
||||
}
|
||||
@@ -60,19 +60,10 @@ pub(crate) fn page_rulers(app: &mut WordApp, ui: &mut Ui, out: &craft::pages::ui
|
||||
.map(|cg| cg.gaps.iter().map(|&(l, r)| if rtl { (col_end - r, col_end - l) } else { (l - col_x, r - col_x) }).collect())
|
||||
.unwrap_or_default();
|
||||
|
||||
let row_cells = caret_row(app, layout, pi);
|
||||
let borders_page: Vec<f32> =
|
||||
row_cells.first().map(|f| std::iter::once(f.x).chain(row_cells.iter().map(|b| b.right())).collect()).unwrap_or_default();
|
||||
// While a column marker is dragged the markers show where the preview puts their borders (the ruler draws them
|
||||
// where it is told), so the grabbed marker follows the pointer and the ones right of it move along.
|
||||
let caret_row_idx = app.session.sel.focus.path.cell().map(|(_, r, _)| r);
|
||||
let row = crate::table_resize::ruler_row(app, layout, pi);
|
||||
// Both the ruler markers and Alt widths use the preview of the caret row's actual grid lines.
|
||||
let mods = crate::table_resize::mods_now(ui.ctx());
|
||||
let borders: Vec<f32> = borders_page
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(line, &x)| to_start(crate::table_resize::caret_drag(app, pi).and_then(|d| d.ruler_line_x(mods, caret_row_idx, line)).unwrap_or(x)))
|
||||
.collect();
|
||||
let row_y = row_cells.first().map_or(0.0, |b| b.y + b.h / 2.0);
|
||||
let borders: Vec<f32> = row.as_ref().map(|r| r.positions(app, pi, mods).into_iter().map(to_start).collect()).unwrap_or_default();
|
||||
let bottoms = row_bottoms(app, layout, pi);
|
||||
let rows: Vec<f32> = bottoms.iter().map(|(_, b)| b.bottom()).collect();
|
||||
// A section whose columns `column_drag` refuses shows its gaps without grips.
|
||||
@@ -159,10 +150,13 @@ pub(crate) fn page_rulers(app: &mut WordApp, ui: &mut Ui, out: &craft::pages::ui
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(d) = output.ruler.column {
|
||||
let at = borders_page.get(d.border.index).map(|&x| (x, row_y));
|
||||
let to = (to_page(d.border.position), row_y);
|
||||
table_drag(app, layout, pi, BorderDrag { phase: d.phase, edge: Edge::Column(d.border.index), at, to, mods: d.mods });
|
||||
if let Some(d) = output.ruler.column
|
||||
&& let Some(row) = &row
|
||||
&& let Some(&(line, x)) = row.borders.get(d.border.index)
|
||||
{
|
||||
let at = Some((x, row.y));
|
||||
let to = (to_page(d.border.position), row.y);
|
||||
table_drag(app, layout, pi, BorderDrag { phase: d.phase, edge: Edge::Column(line), at, to, mods: d.mods });
|
||||
}
|
||||
if let Some(d) = output.row {
|
||||
let at = bottoms.get(d.index).map(|(_, b)| (b.x + b.w / 2.0, b.bottom()));
|
||||
@@ -382,14 +376,6 @@ pub(crate) fn text_area(app: &WordApp, layout: &DocLayout, page: usize) -> Optio
|
||||
Some((b.x + left, (b.w - left - right).max(0.0)))
|
||||
}
|
||||
|
||||
/// The caret row's cells on `page`, left to right.
|
||||
fn caret_row(app: &WordApp, layout: &DocLayout, page: usize) -> Vec<wordcraft_geom::Rect> {
|
||||
let Some((_, r, _)) = app.session.sel.focus.path.cell() else { return Vec::new() };
|
||||
let mut row: Vec<wordcraft_geom::Rect> = cells(app, layout, page).into_iter().filter(|(row, ..)| *row == r).map(|(.., b)| b).collect();
|
||||
row.sort_by(|a, b| a.x.total_cmp(&b.x));
|
||||
row
|
||||
}
|
||||
|
||||
/// Each row of the caret's table on `page` with the cell its bottom is taken from: its shortest box, as a vertically
|
||||
/// merged cell's box spans all its rows, and of those the leftmost.
|
||||
fn row_bottoms(app: &WordApp, layout: &DocLayout, page: usize) -> Vec<(usize, wordcraft_geom::Rect)> {
|
||||
|
||||
@@ -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.
|
||||
@@ -775,6 +793,24 @@ fn the_text_pointer_stays_off_the_grey_around_the_page() {
|
||||
assert_ne!(h.output().platform_output.cursor_icon, egui::CursorIcon::Default, "press and move in one frame keep the text pointer");
|
||||
h.event(egui::Event::PointerButton { pos: beside, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() });
|
||||
h.step();
|
||||
|
||||
// A Ctrl/⌘ press in the grey area is ignored: no unit selection starts and the pointer stays an arrow.
|
||||
let ctrl = egui::Modifiers::COMMAND;
|
||||
h.event(egui::Event::PointerMoved(beside));
|
||||
h.step();
|
||||
h.event(egui::Event::ModifiersChanged(ctrl));
|
||||
h.event(egui::Event::PointerButton { pos: beside, button: egui::PointerButton::Primary, pressed: true, modifiers: ctrl });
|
||||
h.step();
|
||||
assert!(h.state().canvas.unit_drag.is_none(), "a Ctrl/⌘ press in the grey area does not start a unit selection");
|
||||
assert!(!h.state().canvas.dragging, "a Ctrl/⌘ press in the grey area does not start a drag");
|
||||
assert!(h.state().session.sel.is_collapsed(), "a Ctrl/⌘ press in the grey area does not select text");
|
||||
assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Default, "arrow during a Ctrl/⌘ press in the grey area");
|
||||
h.event(egui::Event::PointerMoved(further_beside));
|
||||
h.step();
|
||||
assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Default, "arrow during a Ctrl/⌘ drag in the grey area");
|
||||
h.event(egui::Event::PointerButton { pos: further_beside, button: egui::PointerButton::Primary, pressed: false, modifiers: ctrl });
|
||||
h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE));
|
||||
h.step();
|
||||
}
|
||||
|
||||
/// #4410: with the Format Painter armed, a double-click on a word paints that word, and the
|
||||
@@ -2604,6 +2640,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]
|
||||
|
||||
@@ -46,6 +46,20 @@ fn click_at(h: &mut H, at: Pos2) {
|
||||
steps(h, 3);
|
||||
}
|
||||
|
||||
/// A primary double click at `at`: two clicks a few frames apart, inside egui's double click delay.
|
||||
fn double_click_at(h: &mut H, at: Pos2) {
|
||||
// Let the click before it age out, or the pair would count as a triple click.
|
||||
steps(h, 40);
|
||||
h.event(egui::Event::PointerMoved(at));
|
||||
for _ in 0..2 {
|
||||
h.event(button(at, egui::PointerButton::Primary, true));
|
||||
h.app_frame();
|
||||
h.event(button(at, egui::PointerButton::Primary, false));
|
||||
h.app_frame();
|
||||
}
|
||||
steps(h, 3);
|
||||
}
|
||||
|
||||
/// A primary drag from `from` to `to` in six moves.
|
||||
fn drag_between(h: &mut H, from: Pos2, to: Pos2) {
|
||||
h.event(egui::Event::PointerMoved(from));
|
||||
@@ -195,7 +209,7 @@ fn ruler_tab_stops_are_set_moved_and_cleared_with_the_pointer() {
|
||||
let step = 4.5_f32;
|
||||
let near = |stops: &[(f32, TabAlign)], want: f32| stops.len() == 1 && stops[0].1 == TabAlign::Center && (stops[0].0 - want).abs() <= step;
|
||||
// Lets the double-click time pass before the next press.
|
||||
let settle = |h: &mut H| steps(h, 30);
|
||||
let settle = |h: &mut H| steps(h, 40);
|
||||
let stops = |h: &H| {
|
||||
let s = &h.state().session;
|
||||
let para = s.doc.para_at(&s.sel.focus).expect("a paragraph");
|
||||
@@ -253,19 +267,27 @@ fn comment_harness() -> (H, u32) {
|
||||
a.run("select.text", json!({"text": "text"})).unwrap();
|
||||
let id = a.run("review.newComment", json!({"text": "Original"})).unwrap()["id"].as_u64().unwrap() as u32;
|
||||
a.run("view.commentsPane", json!({"value": false})).unwrap();
|
||||
(window(a), id)
|
||||
(window_dt(a, Some(1.0 / 60.0)), id)
|
||||
}
|
||||
|
||||
/// Click comment `id`'s balloon (from no selected balloon): the card is selected and its own
|
||||
/// edit has the keyboard in its field.
|
||||
/// Click comment `id`'s balloon (from no selected balloon): the card is selected with no edit open (as in Word), then
|
||||
/// a double click opens its message for editing, and takes the keyboard in its field.
|
||||
fn click_balloon(h: &mut H, id: u32) {
|
||||
h.state_mut().canvas.comments.selected = craft::behavior::Selection::default();
|
||||
steps(h, 2);
|
||||
let card = h.state().canvas.balloon_rects.iter().find(|(i, _)| *i == id).map(|(_, r)| *r).expect("the comment has a balloon");
|
||||
click_at(h, card.left_top() + vec2(30.0, 8.0));
|
||||
assert_eq!(h.state().canvas.selected_balloon(), Some(id), "the click selected the balloon");
|
||||
// The selected card opens its own edit, a framework text field, which takes the keyboard by a click in it
|
||||
// (none opens where comments can't change).
|
||||
select_balloon_card(h, id);
|
||||
open_edit(h, id);
|
||||
}
|
||||
|
||||
/// Double-clicks comment `id`'s card to open message 0 for editing, unless a draft is already open (a refused one
|
||||
/// is kept), and clicks into its field. Nothing opens where comments can't change.
|
||||
fn open_edit(h: &mut H, id: u32) {
|
||||
if crate::app::command_board::command_enabled(h.state(), "review.editComment") {
|
||||
if h.state().canvas.comments.editing.is_none() {
|
||||
let card = h.state().canvas.balloon_rects.iter().find(|(i, _)| *i == id).map(|(_, r)| *r).expect("the comment has a balloon");
|
||||
double_click_at(h, card.left_top() + vec2(30.0, 8.0));
|
||||
assert!(h.state().canvas.comments.editing.is_some(), "a double click on the card opens its edit");
|
||||
}
|
||||
steps(h, 2);
|
||||
}
|
||||
use egui::accesskit::Role;
|
||||
let field = h
|
||||
.query_by_role_and_label(Role::MultilineTextInput, "Edit")
|
||||
@@ -277,6 +299,15 @@ fn click_balloon(h: &mut H, id: u32) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Clicks comment `id`'s card (from no selected balloon): it is selected with no edit open, so Reply shows.
|
||||
fn select_balloon_card(h: &mut H, id: u32) {
|
||||
h.state_mut().canvas.comments.selected = craft::behavior::Selection::default();
|
||||
steps(h, 2);
|
||||
let card = h.state().canvas.balloon_rects.iter().find(|(i, _)| *i == id).map(|(_, r)| *r).expect("the comment has a balloon");
|
||||
click_at(h, card.left_top() + vec2(30.0, 8.0));
|
||||
assert_eq!(h.state().canvas.selected_balloon(), Some(id), "the click selected the balloon");
|
||||
}
|
||||
|
||||
/// Types `text` into the field that has the keyboard.
|
||||
fn type_in(h: &mut H, text: &str) {
|
||||
h.event(egui::Event::Text(text.into()));
|
||||
@@ -327,7 +358,7 @@ fn an_empty_comment_balloon_deletes() {
|
||||
}
|
||||
let id = a.run("review.newComment", json!({})).unwrap()["id"].as_u64().unwrap() as u32;
|
||||
a.run("view.commentsPane", json!({"value": false})).unwrap();
|
||||
let mut h = window(a);
|
||||
let mut h = window_dt(a, Some(1.0 / 60.0));
|
||||
click_balloon(&mut h, id);
|
||||
let resolve = h.get_by_label("Resolve").rect().center();
|
||||
click_at(&mut h, resolve);
|
||||
@@ -382,7 +413,7 @@ fn a_refused_comment_edit_keeps_the_draft() {
|
||||
#[test]
|
||||
fn replying_to_a_comment_from_its_balloon_posts_the_reply() {
|
||||
let (mut h, id) = comment_harness();
|
||||
click_balloon(&mut h, id);
|
||||
select_balloon_card(&mut h, id);
|
||||
h.get_by_label("Reply").click();
|
||||
steps(&mut h, 3);
|
||||
type_in(&mut h, "A reply");
|
||||
@@ -858,3 +889,91 @@ fn a_right_click_keeps_selected_cells_only_on_them() {
|
||||
assert_menu(&h, &["Split Cells"], true);
|
||||
assert_menu(&h, &["Merge Cells"], false);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------
|
||||
// Tracked change tips
|
||||
// ---------------------------------------------------------------------------------------
|
||||
|
||||
/// #7887: resting the pointer on a tracked insertion shows a tip with the change's kind, its
|
||||
/// author and its time; beside the change, or with markup hidden, there is none.
|
||||
#[test]
|
||||
fn hovering_a_tracked_change_shows_its_author_and_time() {
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("Plain words here")), Default::default());
|
||||
a.session.author = "Ada Reviewer".into();
|
||||
a.run("caret.docStart", json!({})).unwrap();
|
||||
a.run("review.trackChanges", json!({"value": true})).unwrap();
|
||||
a.run("text.insert", json!({"text": "Inserted "})).unwrap();
|
||||
assert_eq!(a.session.doc.revisions.len(), 1, "one tracked insertion");
|
||||
// A fixed time with no UTC time beside it, as a file's change has, so it shows as written
|
||||
// whatever the machine's zone (`local_time` covers the changes made here).
|
||||
a.session.doc.revisions[0].date = "2026-11-20T14:05:00Z".into();
|
||||
a.session.doc.revisions[0].date_utc = None;
|
||||
let mut h = window(a);
|
||||
let point_at = |h: &mut H, off: usize| {
|
||||
let c = h.state_mut().session.layout().caret(&Pos { story: StoryRef::Body, path: wordcraft_doc::Path::top(0), off }).unwrap();
|
||||
let at = screen(h, c.x, c.top + c.height / 2.0);
|
||||
h.event(egui::Event::PointerMoved(at));
|
||||
super::rest_for_tip(h);
|
||||
};
|
||||
let tips = |h: &H| h.query_all_by_label_contains("Inserted Ada Reviewer 2026-11-20 14:05").count();
|
||||
// Between "Inserted" and its "e", then on "words", which was there before tracking began.
|
||||
point_at(&mut h, 2);
|
||||
assert!(tips(&h) > 0, "the inserted text's tip says it was inserted, by whom and when");
|
||||
point_at(&mut h, "Inserted Plain w".len());
|
||||
assert_eq!(tips(&h), 0, "text that wasn't changed has no tip");
|
||||
h.state_mut().session.view.show_markup = false;
|
||||
point_at(&mut h, 2);
|
||||
assert_eq!(tips(&h), 0, "with markup hidden the change isn't marked, so it has no tip");
|
||||
}
|
||||
|
||||
/// #7887: a paragraph whose own formatting changed while tracking (here its alignment) shows a
|
||||
/// Formatted tip on its text, while the markup shows formatting.
|
||||
#[test]
|
||||
fn hovering_a_paragraph_with_tracked_formatting_shows_formatted() {
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("A centred line")), Default::default());
|
||||
a.session.author = "Ada Reviewer".into();
|
||||
a.run("review.trackChanges", json!({"value": true})).unwrap();
|
||||
a.run("para.alignCenter", json!({})).unwrap();
|
||||
assert!(a.session.doc.body[0].as_para().is_some_and(|p| p.props.fmt_change.is_some()), "the alignment is a tracked change");
|
||||
let mut h = window(a);
|
||||
let point_at = |h: &mut H| {
|
||||
let c = h.state_mut().session.layout().caret(&Pos { story: StoryRef::Body, path: wordcraft_doc::Path::top(0), off: 4 }).unwrap();
|
||||
let at = screen(h, c.x, c.top + c.height / 2.0);
|
||||
h.event(egui::Event::PointerMoved(at));
|
||||
super::rest_for_tip(h);
|
||||
};
|
||||
let tips = |h: &H| h.query_all_by_label_contains("Formatted Ada Reviewer").count();
|
||||
point_at(&mut h);
|
||||
assert!(tips(&h) > 0, "the paragraph's text shows its formatting change");
|
||||
h.state_mut().session.prefs.markup.formatting = false;
|
||||
// The canvas asks for a tip again only when the pointer moves: away to the toggle and back.
|
||||
h.event(egui::Event::PointerGone);
|
||||
point_at(&mut h);
|
||||
assert_eq!(tips(&h), 0, "with formatting markup off the change isn't marked, so it has no tip");
|
||||
}
|
||||
|
||||
/// #7887 review: a link in a footnote shows its tip while the caret is in the body. The hover
|
||||
/// looks in the story under the pointer, so the link's tip still comes before the tracked
|
||||
/// change tip there.
|
||||
#[test]
|
||||
fn a_footnote_link_shows_its_tip_with_the_caret_in_the_body() {
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("Body text")), Default::default());
|
||||
a.run("caret.docEnd", json!({})).unwrap();
|
||||
a.run("review.trackChanges", json!({"value": true})).unwrap();
|
||||
a.run("references.footnote", json!({"text": "Note link"})).unwrap();
|
||||
let note = a.session.sel.focus.story;
|
||||
let pos = |off: usize| json!({"story": note, "path": [0], "off": off});
|
||||
a.run("select.range", json!({"anchor": pos(5), "focus": pos(9)})).unwrap();
|
||||
a.run("insert.link", json!({"url": "https://example.com/note"})).unwrap();
|
||||
a.run("caret.set", json!({"pos": {"block": 0, "off": 2}})).unwrap();
|
||||
assert_eq!(a.session.sel.focus.story, StoryRef::Body);
|
||||
// The whole page in the window, footnote area and all.
|
||||
a.run("view.zoom", json!({"value": 40})).unwrap();
|
||||
let mut h = window(a);
|
||||
let c = h.state_mut().session.layout().caret(&Pos { story: note, path: wordcraft_doc::Path::top(0), off: 7 }).unwrap();
|
||||
let at = screen(&mut h, c.x, c.top + c.height / 2.0);
|
||||
h.event(egui::Event::PointerMoved(at));
|
||||
super::rest_for_tip(&mut h);
|
||||
assert!(h.query_all_by_label_contains("https://example.com/note").count() > 0, "the footnote's link shows its tip (pointer at {at:?})");
|
||||
assert_eq!(h.query_all_by_label_contains("Inserted ").count(), 0, "not the tracked insertion's tip");
|
||||
}
|
||||
|
||||
@@ -76,16 +76,43 @@ fn new_app() -> WordApp {
|
||||
WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), crate::Services::default())
|
||||
}
|
||||
|
||||
/// A saved .docx (so AutoSave can cover it) in the harness.
|
||||
fn autosave_harness() -> (egui_kittest::Harness<'static, WordApp>, std::path::PathBuf) {
|
||||
let dir = std::env::temp_dir().join(format!("wordcraft-ui-autosave-label-{}", std::process::id()));
|
||||
/// How [`autosave_harness`] has the saved file in its window.
|
||||
#[derive(Debug, PartialEq)]
|
||||
enum Reopen {
|
||||
/// The window that saved it.
|
||||
No,
|
||||
/// Opened in a fresh window, read from disk.
|
||||
FromDisk,
|
||||
/// Opened in a fresh window from its bytes, which only names the file.
|
||||
FromBytes,
|
||||
}
|
||||
|
||||
/// A saved .docx (so AutoSave can cover it), or the same file opened in a fresh window as
|
||||
/// `reopen` says, with the title bar drawn over it. `files` answers a later Save As pick.
|
||||
fn autosave_harness(
|
||||
reopen: Reopen,
|
||||
files: &std::sync::Arc<craft::host::ScriptedFiles>,
|
||||
) -> (egui_kittest::Harness<'static, WordApp>, std::path::PathBuf) {
|
||||
let dir = std::env::temp_dir().join(format!("wordcraft-ui-autosave-label-{}-{reopen:?}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("draft.docx");
|
||||
let mut a = new_app();
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), crate::Services::default())
|
||||
.with_host(std::sync::Arc::new(craft::host::Host::builder(crate::APP).files(files.clone()).build()));
|
||||
a.run("text.insert", json!({"text": "Hello"})).unwrap();
|
||||
a.run("file.save", json!({"path": path.to_string_lossy()})).unwrap();
|
||||
assert!(a.autosaves(), "a saved .docx is covered by AutoSave");
|
||||
if reopen != Reopen::No {
|
||||
a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), crate::Services::default())
|
||||
.with_host(std::sync::Arc::new(craft::host::Host::builder(crate::APP).files(files.clone()).build()));
|
||||
if reopen == Reopen::FromBytes {
|
||||
let data = wordcraft_engine::cmd::insert::base64_encode(&std::fs::read(&path).unwrap());
|
||||
a.execute("file.open", json!({"path": path.to_string_lossy(), "data": data})).unwrap();
|
||||
} else {
|
||||
a.run("file.open", json!({"path": path.to_string_lossy()})).unwrap();
|
||||
}
|
||||
assert!(!a.autosaves(), "an opened file waits for the user's go-ahead");
|
||||
}
|
||||
let h = harness(a);
|
||||
(h, dir)
|
||||
}
|
||||
@@ -93,7 +120,8 @@ fn autosave_harness() -> (egui_kittest::Harness<'static, WordApp>, std::path::Pa
|
||||
/// #3370: clicking the AutoSave switch label toggles AutoSave on and off.
|
||||
#[test]
|
||||
fn clicking_the_autosave_label_toggles_autosave() {
|
||||
let (mut h, dir) = autosave_harness();
|
||||
let files = std::sync::Arc::new(craft::host::ScriptedFiles::new());
|
||||
let (mut h, dir) = autosave_harness(Reopen::No, &files);
|
||||
assert!(h.state().autosaves());
|
||||
h.get_by_label("AutoSave").click();
|
||||
crate::test_harness::frames(&mut h, 2);
|
||||
@@ -104,6 +132,35 @@ fn clicking_the_autosave_label_toggles_autosave() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// #3307: a file opened, not saved, in this window had the switch greyed out, and clicking it
|
||||
/// asked for Save As. Clicking it now turns AutoSave on for that file.
|
||||
#[test]
|
||||
fn clicking_autosave_on_an_opened_file_turns_it_on() {
|
||||
let files = std::sync::Arc::new(craft::host::ScriptedFiles::new());
|
||||
let (mut h, dir) = autosave_harness(Reopen::FromDisk, &files);
|
||||
h.get_by_label("AutoSave").click();
|
||||
crate::test_harness::frames(&mut h, 2);
|
||||
assert!(h.state().autosaves(), "the switch turned AutoSave on");
|
||||
assert!(h.state().dialog_host.is_empty() && h.state().file_dialog.is_none(), "without Save As");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A document opened from bytes only names its file, so the switch can't hand that file to
|
||||
/// AutoSave: it shows the block and clicking it asks for Save As, after which AutoSave is on.
|
||||
#[test]
|
||||
fn clicking_autosave_on_a_document_opened_from_bytes_asks_for_save_as() {
|
||||
let files = std::sync::Arc::new(craft::host::ScriptedFiles::new());
|
||||
let (mut h, dir) = autosave_harness(Reopen::FromBytes, &files);
|
||||
assert_eq!(h.state().autosave_switch_block(), Some(crate::AutoSaveBlock::NotSavedHere));
|
||||
let copy = dir.join("copy.docx");
|
||||
files.queue(craft::host::Picked::Paths(vec![copy.clone()]));
|
||||
h.get_by_label("AutoSave").click();
|
||||
crate::test_harness::frames(&mut h, 2);
|
||||
assert!(copy.is_file(), "Save As saved a copy");
|
||||
assert!(h.state().autosaves(), "AutoSave covers the copy");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// #701: the arrow beside Undo lists the session's undo steps, newest first; clicking the third
|
||||
/// row undoes three steps at once.
|
||||
#[test]
|
||||
@@ -744,8 +801,11 @@ fn the_autosave_knob_sits_right_when_on_and_mirrors_right_to_left() {
|
||||
a.ui.language = "en".into();
|
||||
// Mark the document as saved here without touching disk (`session.dirty` stays false).
|
||||
let path = std::path::PathBuf::from("draft.docx");
|
||||
// A save to the document's own file records both (`note_file_on_disk`): the file is read
|
||||
// from disk, so the switch can be turned on again after it has been turned off.
|
||||
a.session.path = Some(path.clone());
|
||||
a.autosave_path = Some(path);
|
||||
a.autosave_path = Some(path.clone());
|
||||
a.read_from = Some(path);
|
||||
|
||||
let mut h = harness(a);
|
||||
// Arabic UI labels draw even when built without `CRAFT_FONTS_DIR` (embedded Arabic faces).
|
||||
|
||||
@@ -104,7 +104,8 @@ fn leading(app: &mut WordApp, ui: &mut Ui) -> Option<egui::Rect> {
|
||||
/// The AutoSave switch: off and with the reason as its tooltip when AutoSave can't cover the document (#196,
|
||||
/// #176); a click then offers Save As where that helps. Returns the rect it took.
|
||||
fn autosave(app: &mut WordApp, ui: &mut Ui) -> egui::Rect {
|
||||
let block = app.autosave_block();
|
||||
// A file read from disk here is off, not blocked: the switch turns it on (#3307).
|
||||
let block = app.autosave_switch_block();
|
||||
let on = app.autosaves() && block.is_none();
|
||||
let tip = block.as_ref().map_or_else(|| tl!("AutoSave saves every change to the file (needs a saved document)").to_string(), |b| b.reason());
|
||||
// The small switch, as the old title bar drew it.
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//! - `engine.execute {command, params, doc?}`: run any command (engine or `ui.*`)
|
||||
//! - `engine.commands {search?}`: engine and app print commands with enablement and parameters
|
||||
//! - `document.inspect`: document structure; `ui.inspect`: UI state, canvas geometry, perf
|
||||
//! - `ui.click`, `ui.move`, `ui.wheel`, `ui.key`, `ui.release`, `ui.type`, `ui.ime`, `ui.capsLock`:
|
||||
//! - `ui.click`, `ui.move`, `ui.drag`, `ui.wheel`, `ui.key`, `ui.release`, `ui.type`, `ui.ime`, `ui.capsLock`:
|
||||
//! real input in screen points (or document points with `coordinates`), delivered by the
|
||||
//! control library
|
||||
//! - `ui.clickText {page, x, y}`: click at a page position (points from the page's top-left)
|
||||
|
||||
@@ -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
|
||||
@@ -180,6 +191,10 @@ fn handle_in(app: &mut WordApp, doc: u64, method: &str, p: &Value) -> Reply {
|
||||
// Close, with the same guard as the window's: unsaved changes need `force`.
|
||||
if id == "file.close" {
|
||||
if let Some(e) = close_refused_for(app, doc, ¶ms) {
|
||||
// lean: `save` writes the shown document only; a background one needs file.save after making it active.
|
||||
if params.get("save").and_then(Value::as_bool) == Some(true) {
|
||||
return err(format!("{e} (`save` applies to the shown document only: make this one active first, or save it, then close)"));
|
||||
}
|
||||
return err(e);
|
||||
}
|
||||
return match app.session.close_document(doc) {
|
||||
@@ -406,7 +421,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 ui.inspect windows (`current`, `others[].id`)"),
|
||||
},
|
||||
};
|
||||
// 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`") };
|
||||
|
||||
@@ -367,8 +367,8 @@ fn a_script_opens_the_dialog_a_launcher_command_asks_for() {
|
||||
}
|
||||
|
||||
/// 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`.
|
||||
/// through to the commands as an unknown id. When input methods moved to the framework's names in #7101, the old table
|
||||
/// kept names that no longer existed; `ui.drag` is now a real one-request `{from, to}` method the channel answers.
|
||||
#[test]
|
||||
fn every_method_the_protocol_doc_lists_is_answered() {
|
||||
let doc = include_str!("../../../../docs/control-protocol.md");
|
||||
@@ -383,10 +383,13 @@ fn every_method_the_protocol_doc_lists_is_answered() {
|
||||
.map(|name| name.trim_matches('`'))
|
||||
.collect();
|
||||
assert!(methods.contains(&"engine.execute"), "the Methods table: {methods:?}");
|
||||
assert!(methods.contains(&"ui.drag"), "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");
|
||||
}
|
||||
let (req, _rx) = ControlRequest::new("ui.drag", json!({"from": {"x": 10.0, "y": 10.0}, "to": {"x": 20.0, "y": 20.0}}));
|
||||
assert!(matches!(control::handle(&mut app(), &ctx, &req), Reply::AfterInput));
|
||||
}
|
||||
|
||||
@@ -339,6 +339,26 @@ mod tests {
|
||||
assert!(under(smart.id, "Contextual Tabs") && !under(smart.id, "Other"), "{} is under the contextual tabs", smart.id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unimplemented_commands_keep_their_catalog_categories_and_disabled_state() {
|
||||
let mut a = app();
|
||||
let _ = a.command_input();
|
||||
let catalog = a.catalog().expect("catalog");
|
||||
let areas = super::areas();
|
||||
|
||||
for (id, tab, group) in [("insert.video", "Insert", "Media"), ("draw.inkToMath", "Draw", "Convert")] {
|
||||
let command = CommandRef::new(id);
|
||||
assert!(a.session.registry.get(id).is_none(), "{id} is still unimplemented");
|
||||
let def = catalog.defs().iter().find(|def| def.command == command).unwrap_or_else(|| panic!("{id} in catalog"));
|
||||
assert_eq!(def.paths, [vec![tab.to_owned(), group.to_owned()]], "{id} keeps its full ribbon path");
|
||||
let categories: Vec<_> = areas.iter().filter(|area| (area.rows)(def)).map(|area| area.id).collect();
|
||||
assert_eq!(categories, [tab, "All Commands"], "{id} is filed under its ribbon tab");
|
||||
assert!(def.defaults.is_empty(), "{id} has no default chord");
|
||||
let state = a.command_states.get(&command);
|
||||
assert!(state.is_some_and(|state| !state.is_enabled()), "{id} publishes an explicit disabled state");
|
||||
}
|
||||
}
|
||||
|
||||
/// #7971: the board's catalog files each engine command under its ribbon tab.
|
||||
#[test]
|
||||
fn catalog_paths_follow_the_ribbon_location() {
|
||||
|
||||
@@ -55,7 +55,16 @@ pub(super) fn body_field(app: &WordApp, name: &str) -> Option<FieldCode> {
|
||||
impl IndexForm {
|
||||
/// The index in the document, or Word's defaults for a new one (two columns).
|
||||
pub fn read(app: &WordApp) -> IndexForm {
|
||||
match body_field(app, "INDEX") {
|
||||
// Insert Index updates an inline index first. Otherwise it rebuilds the range field
|
||||
// before writing the settings, so the dialog needs to read those switches too.
|
||||
let index = body_field(app, "INDEX").or_else(|| {
|
||||
app.session.doc.body.iter().filter_map(|b| b.as_para()).flat_map(|p| p.objects.iter()).find_map(|o| {
|
||||
let wordcraft_doc::InlineObject::FieldStart { instr, .. } = o else { return None };
|
||||
let field = FieldCode::parse(instr);
|
||||
(field.name == "INDEX").then_some(field)
|
||||
})
|
||||
});
|
||||
match index {
|
||||
Some(f) => IndexForm {
|
||||
kind: if f.has('r') { "runIn" } else { "indented" }.into(),
|
||||
columns: f.arg('c').and_then(|c| c.trim().parse().ok()).unwrap_or(1).clamp(1, 4),
|
||||
|
||||
@@ -238,6 +238,50 @@ fn index_and_mark_entry_dialogs_write_switches() {
|
||||
assert_eq!(IndexForm::read(&a), f, "the dialog shows the index's settings");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn index_dialog_keeps_range_field_settings_when_confirmed_without_edits() {
|
||||
use egui::accesskit::{Role, Toggled};
|
||||
use egui_kittest::kittest::{NodeT, Queryable};
|
||||
use wordcraft_doc::{Block, Paragraph, Path};
|
||||
|
||||
let mut a = app("Kilns are hot.");
|
||||
a.run("select.text", json!({"text": "Kilns"})).unwrap();
|
||||
a.session.run("references.markEntry", &json!({})).unwrap();
|
||||
|
||||
// Original synthetic range field with non-default type, columns, alignment and headings.
|
||||
let instr = "INDEX \\c \"3\" \\e \"\t\" \\r";
|
||||
let mut para = Paragraph::new();
|
||||
para.insert_object(0, InlineObject::FieldEnd, &Default::default()).unwrap();
|
||||
para.insert_object(0, InlineObject::FieldStart { instr: instr.into(), locked: false, dirty: false }, &Default::default()).unwrap();
|
||||
let last = a.session.doc.body.len();
|
||||
a.session.doc.insert_block(StoryRef::Body, &Path::top(last), Block::Para(para)).unwrap();
|
||||
a.session.touch();
|
||||
|
||||
assert_eq!(a.run("references.index", json!({})).unwrap(), json!({"pending": "index"}));
|
||||
let mut h = crate::test_harness::builder().with_size(vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
a,
|
||||
);
|
||||
h.run_steps(4);
|
||||
h.get_by_role_and_label(Role::Dialog, "Index");
|
||||
let opened = form::<IndexForm>(h.state());
|
||||
assert_eq!((opened.kind.as_str(), opened.columns, opened.right_align, opened.headings), ("runIn", 3, true, false));
|
||||
assert_eq!(h.state().session.doc.field_ranges(StoryRef::Body)[0].instr, instr, "opening leaves the range field intact");
|
||||
let right_aligned = h.get_by_role_and_label(Role::CheckBox, "Page numbers at the right margin").accesskit_node().toggled();
|
||||
assert_eq!(right_aligned, Some(Toggled::True));
|
||||
assert_eq!(h.get_by_role_and_label(Role::CheckBox, "Letter headings").accesskit_node().toggled(), Some(Toggled::False));
|
||||
h.get_by_role_and_label(Role::Button, "OK").click();
|
||||
h.run_steps(3);
|
||||
assert!(!is_open::<IndexForm>(h.state()), "OK closes the dialog");
|
||||
let indexes: Vec<_> = instrs(h.state()).into_iter().filter(|i| i.starts_with("INDEX")).collect();
|
||||
assert_eq!(indexes, [instr.to_string()], "the rebuilt index keeps the same switches");
|
||||
assert!(h.state().session.doc.field_ranges(StoryRef::Body).is_empty(), "the range was replaced in place");
|
||||
}
|
||||
|
||||
/// #402: Custom Table of Contents and its Options make the TOC switches, and the dialog
|
||||
/// opens again with them.
|
||||
#[test]
|
||||
|
||||
@@ -18,8 +18,11 @@ use crate::{WordApp, panes};
|
||||
/// What the window keeps for an open document while another one is shown.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Parked {
|
||||
/// [`WordApp`]'s `autosave_path`: the file AutoSave writes this document to.
|
||||
/// [`WordApp`]'s `autosave_path`: the file this document was explicitly saved to.
|
||||
autosave_path: Option<std::path::PathBuf>,
|
||||
autosave_choice: Option<bool>,
|
||||
/// [`WordApp`]'s `read_from`: the file on disk this document was read from or saved to.
|
||||
read_from: Option<std::path::PathBuf>,
|
||||
/// The comment panel's selection and the comment and reply text typed in this document and not
|
||||
/// yet written to it.
|
||||
comments: craft::review::ui::CommentsPanelState,
|
||||
@@ -102,7 +105,12 @@ impl WordApp {
|
||||
if from == to {
|
||||
return false;
|
||||
}
|
||||
let leaving = Parked { autosave_path: self.autosave_path.take(), comments: std::mem::take(&mut self.canvas.comments) };
|
||||
let leaving = Parked {
|
||||
autosave_path: self.autosave_path.take(),
|
||||
autosave_choice: self.autosave_choice.take(),
|
||||
read_from: self.read_from.take(),
|
||||
comments: std::mem::take(&mut self.canvas.comments),
|
||||
};
|
||||
if self.session.is_open(from) {
|
||||
self.parked.insert(from, leaving);
|
||||
}
|
||||
@@ -110,6 +118,8 @@ impl WordApp {
|
||||
let seen = back.is_some();
|
||||
let back = back.unwrap_or_default();
|
||||
self.autosave_path = back.autosave_path;
|
||||
self.autosave_choice = back.autosave_choice;
|
||||
self.read_from = back.read_from;
|
||||
self.canvas.comments = back.comments;
|
||||
let session = &self.session;
|
||||
self.parked.retain(|d, _| session.is_open(*d));
|
||||
|
||||
@@ -379,7 +379,9 @@ impl WordApp {
|
||||
}
|
||||
AfterSave::AutoSave => {
|
||||
if saved {
|
||||
self.autosave_choice = None;
|
||||
self.autosave = true;
|
||||
self.session.autosave = true;
|
||||
} else if let Some(Err(error)) = &result {
|
||||
self.fail_save_as(error);
|
||||
}
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
// PLAN: the Insert key has no editor input, so the overtype switch is the shortcut layer's (shell-w6).
|
||||
use craft::behavior::editor::{EditorInput, SurroundingUnit};
|
||||
use craft::behavior::intent::{EditCommand, Granularity, MoveMods, NavMove};
|
||||
use craft::platform::clipboard::{HTML, RGBA8, RTF, URI_LIST};
|
||||
use craft::ui::canvas::ToolPass;
|
||||
use craft::ui::runtime::commands::{ClipItem, ClipboardHandle};
|
||||
|
||||
@@ -633,7 +632,9 @@ fn edit_command(app: &mut WordApp, ctx: &egui::Context, cmd: EditCommand) {
|
||||
let _ = app.run("edit.copy", json!({}));
|
||||
}
|
||||
}
|
||||
EditCommand::Paste => paste(app, ctx),
|
||||
EditCommand::Paste => {
|
||||
let _ = app.run("edit.paste", json!({}));
|
||||
}
|
||||
EditCommand::SelectAll => {
|
||||
let _ = app.run("select.all", json!({}));
|
||||
}
|
||||
@@ -650,23 +651,6 @@ fn edit_command(app: &mut WordApp, ctx: &egui::Context, cmd: EditCommand) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Paste from the clipboard: copied picture files insert as pictures (#45), text, rich text
|
||||
/// (HTML/RTF) and a clipboard picture go through `edit.paste`.
|
||||
fn paste(app: &mut WordApp, ctx: &egui::Context) {
|
||||
let clip = ClipboardHandle::of(ctx);
|
||||
let text = clip.read_text().ok().flatten();
|
||||
if text.is_none() && !clip.has(&[RGBA8, URI_LIST, HTML, RTF]) {
|
||||
return;
|
||||
}
|
||||
if let Some(t) = &text
|
||||
&& crate::paste_picture::paste_named_files(app, t)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let params = text.map_or_else(|| json!({}), |t| json!({"text": t}));
|
||||
let _ = app.run("edit.paste", params);
|
||||
}
|
||||
|
||||
/// Escape: the nearest thing that takes it first (a painter, a pen, a table pen, an object, a text
|
||||
/// box, a header), then Focus or Full Screen.
|
||||
fn cancel(app: &mut WordApp, ctx: &egui::Context) {
|
||||
|
||||
@@ -452,19 +452,33 @@ fn mod_v_released_mod_first_pastes_the_clipboard_picture() {
|
||||
assert_eq!(body(h.state()), "external");
|
||||
assert!(is_bold(&mut h), "Mod+V keeps the HTML's formatting");
|
||||
|
||||
let mut h = picture_app();
|
||||
let mut h = alt_frame_app();
|
||||
let before = h.state().session.doc.clone();
|
||||
let url = "https://example.test/picture.png";
|
||||
offer(
|
||||
&h,
|
||||
vec![
|
||||
ClipItem::Image(std::sync::Arc::new(egui::ColorImage::from_rgba_unmultiplied([4, 4], &[200u8; 4 * 4 * 4]))),
|
||||
ClipItem::Html(format!(r#"<img src="{url}">"#).into()),
|
||||
ClipItem::Text(url.into()),
|
||||
],
|
||||
);
|
||||
mods_frame(&mut h, ctrl, vec![key_event(Key::ControlLeft, true, ctrl), key_event(Key::V, true, ctrl)]);
|
||||
mods_frame(&mut h, Modifiers::NONE, vec![key_event(Key::ControlLeft, false, Modifiers::NONE)]);
|
||||
mods_frame(&mut h, Modifiers::NONE, vec![key_event(Key::V, false, Modifiers::NONE)]);
|
||||
assert_eq!(pictures(h.state_mut()), 1);
|
||||
run(&mut h, "edit.undo", json!({}));
|
||||
assert!(before.same_content(&h.state().session.doc), "one Undo restores the document before paste");
|
||||
assert_eq!(pictures(h.state_mut()), 0);
|
||||
// A plain V afterwards is not a paste.
|
||||
mods_frame(&mut h, Modifiers::NONE, vec![key_event(Key::V, true, Modifiers::NONE)]);
|
||||
mods_frame(&mut h, Modifiers::NONE, vec![key_event(Key::V, false, Modifiers::NONE)]);
|
||||
assert_eq!(pictures(h.state_mut()), 1);
|
||||
assert_eq!(pictures(h.state_mut()), 0);
|
||||
}
|
||||
|
||||
/// #5859: Mod+V admits a rich-only clipboard (HTML or RTF with no plain-text or picture flavor)
|
||||
/// and still routes an image+HTML clipboard with no plain-text flavor to picture paste.
|
||||
/// #5859: Mod+V admits a rich-only clipboard (HTML or RTF with no plain-text or picture flavor).
|
||||
/// With no plain text, a single-image HTML offer pastes its bitmap, while a formatted selection
|
||||
/// offered beside a bitmap keeps its formatting.
|
||||
#[test]
|
||||
fn mod_v_pastes_rich_only_clipboard_and_preserves_picture_routing() {
|
||||
let ctrl = mod_held();
|
||||
@@ -483,19 +497,24 @@ fn mod_v_pastes_rich_only_clipboard_and_preserves_picture_routing() {
|
||||
assert_eq!(body(h.state()), "rtf-only", "Mod+V pastes RTF-only clipboard");
|
||||
assert!(is_bold(&mut h), "RTF-only paste keeps formatting");
|
||||
|
||||
let image = || ClipItem::Image(std::sync::Arc::new(egui::ColorImage::from_rgba_unmultiplied([4, 4], &[200u8; 4 * 4 * 4])));
|
||||
let img = r#"<img src="https://example.test/picture.png">"#;
|
||||
|
||||
let mut h = alt_frame_app();
|
||||
offer(
|
||||
&h,
|
||||
vec![
|
||||
ClipItem::Image(std::sync::Arc::new(egui::ColorImage::from_rgba_unmultiplied([4, 4], &[200u8; 4 * 4 * 4]))),
|
||||
ClipItem::Html("<p><b>fallback</b></p>".into()),
|
||||
],
|
||||
);
|
||||
offer(&h, vec![image(), ClipItem::Html(img.into())]);
|
||||
mods_frame(&mut h, ctrl, vec![key_event(Key::V, true, ctrl)]);
|
||||
mods_frame(&mut h, Modifiers::NONE, vec![key_event(Key::V, false, Modifiers::NONE)]);
|
||||
assert_eq!(pictures(h.state_mut()), 1, "image+HTML with no plain text routes to picture paste");
|
||||
assert_eq!(pictures(h.state_mut()), 1, "a single-image HTML offer with no plain text pastes its bitmap");
|
||||
assert_eq!(body(h.state()), "", "picture paste does not fall back to HTML text");
|
||||
|
||||
let mut h = alt_frame_app();
|
||||
offer(&h, vec![image(), ClipItem::Html(format!("<p><b>fallback</b>{img}</p>").into())]);
|
||||
mods_frame(&mut h, ctrl, vec![key_event(Key::V, true, ctrl)]);
|
||||
mods_frame(&mut h, Modifiers::NONE, vec![key_event(Key::V, false, Modifiers::NONE)]);
|
||||
assert_eq!(pictures(h.state_mut()), 0, "a formatted selection with no plain text is not replaced by its bitmap");
|
||||
assert_eq!(body(h.state()), "fallback");
|
||||
assert!(is_bold(&mut h), "the formatted selection keeps its bold");
|
||||
|
||||
let dir = std::env::temp_dir().join(format!("wc-mod-v-uri-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let png = dir.join("clip.png");
|
||||
|
||||
@@ -599,9 +599,8 @@ fn closing_the_backstage_ends_its_keytips() {
|
||||
assert!(h.state().keytips_active, "keytips active in Backstage");
|
||||
|
||||
// What the back chevron does.
|
||||
h.state_mut().ui.backstage = false;
|
||||
let ctx = h.ctx.clone();
|
||||
h.state_mut().canvas.focus_page(&ctx);
|
||||
h.state_mut().run("ui.backstage", serde_json::json!({"value": false})).unwrap();
|
||||
h.state_mut().canvas.focus_page_after_pass();
|
||||
crate::test_harness::frames(&mut h, 2);
|
||||
assert!(!h.state().keytips_active, "the badges end with the Backstage");
|
||||
h.input_mut().events.extend([key(egui::Key::C), egui::Event::Text("c".into())]);
|
||||
|
||||
@@ -1652,6 +1652,102 @@ mod tests {
|
||||
assert!(backend.network.load(Ordering::Relaxed), "the person's click in the picker is the consent");
|
||||
}
|
||||
|
||||
/// The bounds of the first node whose label starts with `label`.
|
||||
fn bounds_of(tree: &egui::accesskit::TreeUpdate, label: &str) -> Option<egui::accesskit::Rect> {
|
||||
tree.nodes.iter().find(|(_, n)| n.label().is_some_and(|l| l.starts_with(label))).and_then(|(_, n)| n.bounds())
|
||||
}
|
||||
|
||||
/// In the Add a language picker, the reason an agent's Install was refused shows in that row with its license,
|
||||
/// whatever the license's length (Dutch's is one short line, Catalan's wraps).
|
||||
#[test]
|
||||
fn a_refused_install_says_why_in_its_own_row() {
|
||||
let _g = BACKEND_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let _reset = ResetBackend;
|
||||
let (mut a, ctx, backend) = options_app("language", false);
|
||||
// The fetch the click starts runs on a thread and reports its end here.
|
||||
let (done, ended) = std::sync::mpsc::channel();
|
||||
packs::set_background(Some(std::sync::Arc::new(move || {
|
||||
let _ = done.send(());
|
||||
})));
|
||||
let add = spot(&settled(&mut a, &ctx), "Add a language").expect("the button");
|
||||
user_click(&mut a, &ctx, add);
|
||||
assert!(a.dialog_host.is_open::<super::AddLanguage>(), "the picker opens");
|
||||
while packs::fetching() {
|
||||
ended.recv().expect("the fetch reports its end");
|
||||
}
|
||||
backend.network.store(false, Ordering::Relaxed);
|
||||
for (row, locale) in [("Dutch", "nl"), ("Catalan", "ca")] {
|
||||
let tree = settled(&mut a, &ctx);
|
||||
let shown = bounds_of(&tree, row).unwrap_or_else(|| panic!("{row} is listed: {:?}", labels(&tree)));
|
||||
let install = tree
|
||||
.nodes
|
||||
.iter()
|
||||
.filter(|(_, n)| n.label().is_some_and(|l| l.starts_with("Install")))
|
||||
.filter_map(|(_, n)| n.bounds())
|
||||
.find(|b| (b.y0 + b.y1) / 2.0 > shown.y0 && (b.y0 + b.y1) / 2.0 < shown.y1)
|
||||
.unwrap_or_else(|| panic!("{row} offers Install"));
|
||||
as_agent(&mut a, &ctx, "ui.click", json!({"x": (install.x0 + install.x1) / 2.0, "y": (install.y0 + install.y1) / 2.0}));
|
||||
assert!(a.packs_rt.errors.get(locale).is_some_and(|e| e.contains("Only you")), "{row}: {:?}", a.packs_rt.errors);
|
||||
let tree = settled(&mut a, &ctx);
|
||||
let shown = bounds_of(&tree, row).expect("the row stays listed");
|
||||
// The row's bounds stop at the list's visible edge, and the reason may run past it, so the reason starts
|
||||
// inside the row. It is at least as wide as the row's Install, so it has room to be read.
|
||||
let reason = tree.nodes.iter().find(|(_, n)| {
|
||||
n.label().is_some_and(|l| l.contains("Only you"))
|
||||
&& n.bounds()
|
||||
.is_some_and(|b| b.width() >= install.width() && b.x0 >= shown.x0 && b.x1 <= shown.x1 && b.y0 >= shown.y0 && b.y0 < shown.y1)
|
||||
});
|
||||
let why: Vec<_> = tree.nodes.iter().filter(|(_, n)| n.label().is_some_and(|l| l.contains("Only you"))).map(|(_, n)| n.bounds()).collect();
|
||||
let reason =
|
||||
reason.map(|(id, _)| *id).unwrap_or_else(|| panic!("{row}'s row ({shown:?}) says why, as wide as Install ({install:?}): {why:?}"));
|
||||
// Scrolled into view, the whole reason fits inside the list's visible area: the list's bounds cut to the
|
||||
// picker's, below the Search field and above the Close footer (the list's own bounds run on past the
|
||||
// picker when it scrolls, and the picker's bounds take in its footer).
|
||||
let visible = |tree: &egui::accesskit::TreeUpdate| {
|
||||
let find = |role: egui::accesskit::Role, label: &str| {
|
||||
tree.nodes.iter().find(|(_, n)| n.role() == role && n.label() == Some(label)).and_then(|(_, n)| n.bounds())
|
||||
};
|
||||
let list = find(egui::accesskit::Role::List, "Languages").expect("the list");
|
||||
let picker = find(egui::accesskit::Role::Dialog, "Add a language").expect("the picker");
|
||||
let in_picker = |label: &str| {
|
||||
tree.nodes
|
||||
.iter()
|
||||
.filter(|(_, n)| n.label() == Some(label))
|
||||
.filter_map(|(_, n)| n.bounds())
|
||||
.find(|b| b.x0 >= picker.x0 && b.x1 <= picker.x1 && b.y0 >= picker.y0 && b.y1 <= picker.y1)
|
||||
};
|
||||
let search = in_picker("Search").expect("the picker's Search field");
|
||||
let close = in_picker("Close").expect("the picker's Close button");
|
||||
(list.y0.max(picker.y0).max(search.y1), list.y1.min(picker.y1).min(close.y0), list)
|
||||
};
|
||||
let mut tree = tree;
|
||||
let mut seen = None;
|
||||
for _ in 0..20 {
|
||||
let (top, bottom, list) = visible(&tree);
|
||||
let b = tree.nodes.iter().find(|(id, _)| *id == reason).and_then(|(_, n)| n.bounds()).expect("the reason stays shown");
|
||||
seen = Some((b, top, bottom));
|
||||
if b.y0 >= top && b.y1 <= bottom {
|
||||
break;
|
||||
}
|
||||
let delta = if b.y1 > bottom { bottom - b.y1 } else { top - b.y0 };
|
||||
let center = egui::pos2(((list.x0 + list.x1) / 2.0) as f32, ((top + bottom) / 2.0) as f32);
|
||||
let wheel = egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Point,
|
||||
delta: egui::vec2(0.0, delta as f32),
|
||||
phase: egui::TouchPhase::Move,
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
modifiers: Default::default(),
|
||||
};
|
||||
frame(&mut a, &ctx, vec![egui::Event::PointerMoved(center), wheel]);
|
||||
tree = settled(&mut a, &ctx);
|
||||
}
|
||||
assert!(
|
||||
seen.is_some_and(|(b, top, bottom)| b.y0 >= top && b.y1 <= bottom),
|
||||
"{row}'s reason fits inside the list's visible area (reason, top, bottom): {seen:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Set as default sets only the saved default proofing language (`review.language.preferred`); the
|
||||
/// document, its undo history, the redo stack and the modified flag are untouched.
|
||||
#[test]
|
||||
|
||||
@@ -437,6 +437,10 @@ pub struct WordApp {
|
||||
/// The font database's [`generation`](wordcraft_fonts::FontDb::generation) last seen: when
|
||||
/// fonts are added or removed (by any route) the font lists and the layout are refreshed.
|
||||
font_generation: u64,
|
||||
/// Test-only catalog override so UI tests list only fixed `assets/fonts/` without scanning
|
||||
/// the host's system fonts.
|
||||
#[cfg(test)]
|
||||
pub(crate) font_catalog: Option<std::sync::Arc<craft::font_manager::Catalog>>,
|
||||
/// Focus (#1678): the ribbon is dropped down from the Focus bar, over the page. The shell
|
||||
/// owns the flag while it draws; the app reads it back after each pass.
|
||||
pub(crate) ribbon_dropped: bool,
|
||||
@@ -505,10 +509,14 @@ pub struct WordApp {
|
||||
/// Read Aloud: the start of the sentence the caret was last moved to, and the last error shown.
|
||||
pub(crate) read_aloud_at: Option<wordcraft_engine::doc::Pos>,
|
||||
pub(crate) read_aloud_error: Option<String>,
|
||||
/// The file the document was last explicitly saved to in this session; AutoSave writes only
|
||||
/// there. A file that was merely opened isn't rewritten until the user saves it: saving drops
|
||||
/// whatever WordCraft can't represent (content controls, charts, macros…).
|
||||
/// The file the document was last explicitly saved to in this session.
|
||||
autosave_path: Option<std::path::PathBuf>,
|
||||
/// The document's explicit AutoSave switch choice. None follows the shared preference
|
||||
/// once the document has been saved here.
|
||||
autosave_choice: Option<bool>,
|
||||
/// The file on disk the document was read from or saved to. A document opened from bytes
|
||||
/// (`file.open` with `data`) only names a file, so the AutoSave switch can't cover it.
|
||||
read_from: Option<std::path::PathBuf>,
|
||||
/// Web: saves the browser's picker hasn't finished yet (#1315).
|
||||
saves_in_flight: Vec<SaveInFlight>,
|
||||
/// The Save Changes prompt this window is running and the command it holds back.
|
||||
|
||||
@@ -29,6 +29,19 @@ pub(crate) fn comment_time(c: &wordcraft_doc::Comment) -> String {
|
||||
stamp(&c.date, c.date_utc.as_deref(), offset_minutes)
|
||||
}
|
||||
|
||||
/// A tracked change's time for its hover tip, read as [`comment_time`] reads a comment: the UTC
|
||||
/// time (`date_utc`, Word's `w16du:dateUtc`, which WordCraft keeps for the changes it makes) wins
|
||||
/// and shows in local time. Without it (`w:date` only), Word writes local time there with a `Z`
|
||||
/// it doesn't mean and shows it as written, so it shows as written here too; a time with an
|
||||
/// offset (`±HH:MM`) is converted. Empty when it isn't a date.
|
||||
pub(crate) fn revision_time(r: &wordcraft_doc::Revision) -> String {
|
||||
revision_stamp(r, offset_minutes)
|
||||
}
|
||||
|
||||
fn revision_stamp(r: &wordcraft_doc::Revision, offset: impl Fn(i64) -> i32) -> String {
|
||||
stamp(&r.date, r.date_utc.as_deref(), offset)
|
||||
}
|
||||
|
||||
fn stamp(date: &str, date_utc: Option<&str>, offset: impl Fn(i64) -> i32) -> String {
|
||||
let utc = date_utc.and_then(parse).filter(|t| t.timed).map(|t| Time { zone: Some(t.zone.unwrap_or(0)), ..t });
|
||||
let local_date = || parse(date).map(|t| if date.trim_end().ends_with(['Z', 'z']) { Time { zone: None, ..t } } else { t });
|
||||
@@ -185,6 +198,28 @@ mod tests {
|
||||
assert_eq!(stamp("2026-10-12Z", Some("2026-10-12"), |_| -4 * 60), "2026-10-12");
|
||||
}
|
||||
|
||||
/// A change WordCraft makes keeps its UTC time, so its tip shows the user's local time, here
|
||||
/// two hours east of UTC; a change from a file with only a `Z` date still shows as written
|
||||
/// (#7887).
|
||||
#[test]
|
||||
fn changes_made_here_show_in_local_time() {
|
||||
let utc_plus_2 = |_: i64| 2 * 60;
|
||||
let made = wordcraft_engine::cmd::made_revision(wordcraft_doc::RevisionKind::Insert, "Ada".into(), "2026-11-20T12:05:00Z".into());
|
||||
assert_eq!(revision_stamp(&made, utc_plus_2), "2026-11-20 14:05");
|
||||
let imported = wordcraft_doc::Revision::new(wordcraft_doc::RevisionKind::Insert, "Ada", "2026-11-20T12:05:00Z");
|
||||
assert_eq!(revision_stamp(&imported, utc_plus_2), "2026-11-20 12:05");
|
||||
}
|
||||
|
||||
/// A tracked change from a file with only its `w:date` (#7887): shown as written, `Z` or not,
|
||||
/// as Word shows it.
|
||||
#[test]
|
||||
fn revision_times_show_as_written() {
|
||||
let at = |date: &str| revision_time(&wordcraft_doc::Revision::new(wordcraft_doc::RevisionKind::Insert, "Ada", date));
|
||||
assert_eq!(at("2026-11-20T14:05:00Z"), "2026-11-20 14:05");
|
||||
assert_eq!(at("2026-11-20"), "2026-11-20");
|
||||
assert_eq!(at("not a date"), "");
|
||||
}
|
||||
|
||||
/// Whatever a file holds, a stamp is a date or nothing, never a panic.
|
||||
#[test]
|
||||
fn hostile_times_show_nothing() {
|
||||
|
||||
@@ -666,6 +666,10 @@ impl PreferencesModel for OptionsModel<'_> {
|
||||
if self.app.autosave_block() != Some(crate::AutoSaveBlock::Browser) {
|
||||
self.app.autosave = v;
|
||||
self.app.session.autosave = v;
|
||||
// The Options row explicitly enables AutoSave for the active saved document.
|
||||
if v && self.app.saved_here() {
|
||||
self.app.autosave_choice = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
("save.removePersonalInfo", Bool(v)) => self.run("file.privacyOptions", json!({"removePersonalInfo": v})),
|
||||
|
||||
@@ -179,6 +179,33 @@ fn options_panes_open_and_change_settings() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autosave_option_enables_saved_files_without_authorizing_open_only_files() {
|
||||
let dir = std::env::temp_dir().join(format!("wc-ui-autosave-option-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("saved.docx");
|
||||
let path = path.to_string_lossy();
|
||||
let mut a = app();
|
||||
a.run("text.insert", json!({"text": "Saved for the AutoSave test."})).unwrap();
|
||||
a.run("file.save", json!({"path": path})).unwrap();
|
||||
a.run("file.autosave", json!({"value": false})).unwrap();
|
||||
assert!(!a.autosaves());
|
||||
let enable = |m: &mut OptionsModel<'_>| m.set("save.autosave", PrefValue::Bool(true));
|
||||
with_model(&mut a, true, enable);
|
||||
assert!(a.autosaves(), "Options re-enables an explicitly saved file");
|
||||
|
||||
let mut opened = app();
|
||||
opened.run("file.open", json!({"path": path})).unwrap();
|
||||
with_model(&mut opened, true, enable);
|
||||
assert!(!opened.autosaves(), "Options must not grant permission to write an opened file");
|
||||
opened.run("file.autosave", json!({"value": true})).unwrap();
|
||||
assert!(opened.autosaves(), "the document's switch may explicitly grant permission");
|
||||
opened.run("file.autosave", json!({"value": false})).unwrap();
|
||||
with_model(&mut opened, true, enable);
|
||||
assert!(!opened.autosaves(), "Options must not restore a withdrawn grant for an opened file");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// One table over the Choice rows and the document's privacy options.
|
||||
#[test]
|
||||
fn save_privacy_checkboxes_set_the_privacy_options() {
|
||||
|
||||
@@ -10,6 +10,7 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
// PLAN(app-hub): the `craft` facade dependency of ui-egui (`craft::platform` = craft-platform), as in system_clipboard.rs
|
||||
use craft::platform::clipboard::ClipboardError;
|
||||
use craft::ui::runtime::commands::ClipboardHandle;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::{WordApp, system_clipboard};
|
||||
@@ -77,27 +78,16 @@ fn paste_files(app: &mut WordApp, files: Vec<PathBuf>) -> Option<Result<Value, S
|
||||
Some(r)
|
||||
}
|
||||
|
||||
/// Paste the picture on the system clipboard: copied picture files, else its bitmap. `None` when
|
||||
/// there is none (or no clipboard): the caller pastes as usual.
|
||||
pub(crate) fn paste(app: &mut WordApp) -> Option<Result<Value, String>> {
|
||||
/// Paste copied picture files, or the bitmap if allowed and there are no copied files.
|
||||
pub(crate) fn paste(app: &mut WordApp, allow_bitmap: bool) -> Option<Result<Value, String>> {
|
||||
let clip = system_clipboard::handle(app)?;
|
||||
let r = match clip.read_files().ok().flatten().filter(|f| !f.is_empty()) {
|
||||
Some(files) => paste_files(app, files)?,
|
||||
None => match clip.read_image() {
|
||||
None if !allow_bitmap => return None,
|
||||
None => match bitmap_png(&clip) {
|
||||
Ok(Some(png)) => return Some(insert_bitmap(app, &png)),
|
||||
Ok(None) => return None,
|
||||
Ok(Some(image)) => match png_from_rgba(image.width as usize, image.height as usize, image.rgba) {
|
||||
Ok(png) => app.execute("insert.picture", json!({"data": wordcraft_engine::cmd::insert::base64_encode(&png)})),
|
||||
Err(e) => {
|
||||
log::warn!("clipboard picture: {e}");
|
||||
app.status(e.clone());
|
||||
Err(e)
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
let e = match e {
|
||||
ClipboardError::TooLarge { .. } => "the clipboard picture is too large to paste".to_string(),
|
||||
e => crate::i18n::fmt(tl!("The picture on the clipboard couldn't be read: {error}"), &[("error", &e.to_string())]),
|
||||
};
|
||||
log::warn!("clipboard picture: {e}");
|
||||
app.status(e.clone());
|
||||
Err(e)
|
||||
@@ -109,6 +99,21 @@ pub(crate) fn paste(app: &mut WordApp) -> Option<Result<Value, String>> {
|
||||
Some(r)
|
||||
}
|
||||
|
||||
/// Encode the bounded native bitmap through the same path for ordinary and mixed clipboard pastes.
|
||||
pub(crate) fn bitmap_png(clip: &ClipboardHandle) -> Result<Option<Vec<u8>>, String> {
|
||||
let image = clip.read_image().map_err(|e| match e {
|
||||
ClipboardError::TooLarge { .. } => "the clipboard picture is too large to paste".to_string(),
|
||||
e => crate::i18n::fmt(tl!("The picture on the clipboard couldn't be read: {error}"), &[("error", &e.to_string())]),
|
||||
})?;
|
||||
image.map(|image| png_from_rgba(image.width as usize, image.height as usize, image.rgba)).transpose()
|
||||
}
|
||||
|
||||
pub(crate) fn insert_bitmap(app: &mut WordApp, png: &[u8]) -> Result<Value, String> {
|
||||
let r = app.execute("insert.picture", json!({"data": wordcraft_engine::cmd::insert::base64_encode(png)}));
|
||||
app.select_inserted_picture(&r);
|
||||
r
|
||||
}
|
||||
|
||||
/// The picture on the system clipboard as PNG (or the first copied picture file's bytes), for
|
||||
/// Paste Special to offer. `None` when there is none, or it is too large or unreadable.
|
||||
pub(crate) fn clipboard_png(app: &WordApp) -> Option<Vec<u8>> {
|
||||
@@ -127,16 +132,10 @@ fn read_picture_file(path: &Path, limit: u64) -> Option<Vec<u8>> {
|
||||
wordcraft_engine::io::read_regular_file_within(path, limit)
|
||||
}
|
||||
|
||||
/// Paste text naming copied picture files: insert the pictures when the clipboard holds those
|
||||
/// files. False leaves the text to the usual paste.
|
||||
pub(crate) fn paste_named_files(app: &mut WordApp, text: &str) -> bool {
|
||||
names_picture_files(text) && paste(app).is_some()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::system_clipboard::testing::{app_holding, rgba8};
|
||||
use crate::system_clipboard::testing::{app_holding, app_holding_with_image_error, rgba8};
|
||||
use craft::platform::clipboard::{Flavor, RGBA8, URI_LIST};
|
||||
|
||||
fn pictures(a: &mut WordApp) -> usize {
|
||||
@@ -189,6 +188,16 @@ mod tests {
|
||||
assert!(!names_picture_files("see /tmp/b.png") && !names_picture_files("notes.txt") && !names_picture_files(""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bitmap_only_paste_inserts_a_picture_during_equation_editing() {
|
||||
let mut app = app_holding(&[rgba8(4, 4, 200)]);
|
||||
app.run("insert.equation", json!({"linear": "abc"})).unwrap();
|
||||
assert!(app.session.math.is_some());
|
||||
app.run("edit.paste", json!({})).unwrap();
|
||||
let objects = app.session.run("arrange.selectionPane", &json!({})).unwrap();
|
||||
assert!(objects.as_array().is_some_and(|objects| objects.iter().any(|object| object["kind"] == "picture")));
|
||||
}
|
||||
|
||||
/// Text on the clipboard wins over a picture beside it (#584).
|
||||
#[test]
|
||||
fn paste_without_text_reads_the_system_clipboard() {
|
||||
@@ -203,6 +212,137 @@ mod tests {
|
||||
assert!(r["formats"].as_array().is_some_and(|f| f.iter().any(|x| x["id"] == "text")), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordinary_paste_prefers_pixels_for_a_single_image_offer() {
|
||||
use craft::platform::clipboard::HTML;
|
||||
|
||||
let url = "https://example.test/picture.png";
|
||||
let html = format!(r#"<meta http-equiv="content-type" content="text/html; charset=utf-8"><img src="{url}" alt="A & B">"#);
|
||||
let url_and_alt = format!("{url}\r\nA & B");
|
||||
for text in [url, "A & B", &url_and_alt] {
|
||||
let mut app = app_holding(&[Flavor::text(text), Flavor::new(HTML, html.as_bytes().to_vec()), rgba8(4, 4, 200)]);
|
||||
app.run("edit.paste", json!({})).unwrap();
|
||||
assert_eq!(pictures(&mut app), 1);
|
||||
assert!(!app.session.doc.plain_text(wordcraft_doc::StoryRef::Body).contains(text));
|
||||
app.run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(pictures(&mut app), 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_image_offer_with_rtf_prefers_readable_pixels() {
|
||||
use craft::platform::clipboard::{HTML, RGBA8, RTF};
|
||||
|
||||
let url = "https://example.test/picture.png";
|
||||
let html = Flavor::new(HTML, format!(r#"<img src="{url}">"#).into_bytes());
|
||||
let rtf = Flavor::new(RTF, br"{\rtf1\ansi Image fallback}".to_vec());
|
||||
let malformed = Flavor::new(RGBA8, vec![1, 0, 0, 0, 1, 0, 0, 0]);
|
||||
let paste = |bitmap| {
|
||||
let mut app = app_holding(&[Flavor::text(url), html.clone(), rtf.clone(), bitmap]);
|
||||
app.run("edit.paste", json!({})).unwrap();
|
||||
app
|
||||
};
|
||||
|
||||
assert_eq!(pictures(&mut paste(rgba8(4, 4, 200))), 1);
|
||||
|
||||
let mut app = paste(malformed);
|
||||
assert_eq!(pictures(&mut app), 0);
|
||||
assert_eq!(app.session.doc.plain_text(wordcraft_doc::StoryRef::Body), "Image fallback");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordinary_paste_falls_back_to_pixels_when_rich_formats_have_no_content() {
|
||||
use craft::platform::clipboard::{HTML, RTF};
|
||||
|
||||
let linked_image = br#"<a href="https://example.test/"><img src="https://example.test/picture.png"></a>"#;
|
||||
for markup in [Flavor::new(HTML, linked_image.to_vec()), Flavor::new(RTF, br"{\rtf1\ansi}".to_vec())] {
|
||||
let mut app = app_holding(&[rgba8(4, 4, 200), markup]);
|
||||
let before = app.session.undo_depth();
|
||||
app.run("edit.paste", json!({})).unwrap();
|
||||
assert_eq!(pictures(&mut app), 1);
|
||||
assert_eq!(wordcraft_render::image_size(app.session.doc.media.values().next().unwrap()), Some((4, 4)));
|
||||
assert_eq!(app.session.undo_depth(), before + 1);
|
||||
app.run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(pictures(&mut app), 0);
|
||||
assert_eq!(app.session.undo_depth(), before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_rich_paste_distinguishes_unreadable_and_absent_bitmaps() {
|
||||
use craft::platform::clipboard::RTF;
|
||||
use wordcraft_doc::StoryRef;
|
||||
|
||||
let empty_rtf = Flavor::new(RTF, br"{\rtf1\ansi}".to_vec());
|
||||
let malformed = Flavor::new(RGBA8, vec![1, 0, 0, 0, 1, 0, 0, 0]);
|
||||
let mut absent = app_holding(std::slice::from_ref(&empty_rtf));
|
||||
let before = absent.session.undo_depth();
|
||||
let nothing = system_clipboard::nothing_to_paste(&absent);
|
||||
assert_eq!(absent.run("edit.paste", json!({})).unwrap_err(), nothing);
|
||||
assert_eq!(absent.session.undo_depth(), before);
|
||||
|
||||
let mut unreadable = app_holding_with_image_error(&[empty_rtf.clone(), malformed.clone()], Some("malformed bitmap"));
|
||||
let before = unreadable.session.undo_depth();
|
||||
let error = unreadable.run("edit.paste", json!({})).unwrap_err();
|
||||
assert!(error.contains("malformed bitmap"), "{error}");
|
||||
assert_eq!(unreadable.status_message().unwrap().text.as_str(), error);
|
||||
assert_eq!(unreadable.session.undo_depth(), before);
|
||||
assert_eq!(pictures(&mut unreadable), 0);
|
||||
|
||||
let mut with_text = app_holding_with_image_error(&[empty_rtf, malformed, Flavor::text("usable text")], Some("malformed bitmap"));
|
||||
with_text.run("edit.paste", json!({})).unwrap();
|
||||
assert_eq!(with_text.session.doc.plain_text(StoryRef::Body), "usable text");
|
||||
assert_eq!(pictures(&mut with_text), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fallback_pixels_do_not_override_rich_content_or_a_refused_paste() {
|
||||
use craft::platform::clipboard::{HTML, RTF};
|
||||
use wordcraft_doc::StoryRef;
|
||||
|
||||
let empty_rtf = Flavor::new(RTF, br"{\rtf1\ansi}".to_vec());
|
||||
let rich_html = Flavor::new(HTML, b"<p><strong>Rich content</strong></p>".to_vec());
|
||||
let mut app = app_holding(&[rgba8(4, 4, 200), rich_html]);
|
||||
app.run("edit.paste", json!({})).unwrap();
|
||||
assert_eq!(app.session.doc.plain_text(StoryRef::Body), "Rich content");
|
||||
assert_eq!(pictures(&mut app), 0);
|
||||
|
||||
let mut app = app_holding(&[rgba8(4, 4, 200), empty_rtf.clone()]);
|
||||
app.session.doc.settings.protection = Some("readOnly".into());
|
||||
let err = app.run("edit.paste", json!({})).unwrap_err();
|
||||
assert!(err.contains("edit.paste:") && err.contains("read only"), "{err}");
|
||||
assert_eq!(pictures(&mut app), 0);
|
||||
|
||||
let mut app = app_holding(&[rgba8(4, 4, 200), empty_rtf]);
|
||||
app.run("insert.equation", json!({"linear": "abc"})).unwrap();
|
||||
assert!(app.session.math.is_some());
|
||||
assert!(app.run("edit.paste", json!({})).is_err());
|
||||
assert_eq!(pictures(&mut app), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordinary_paste_preserves_urls_rich_selections_and_unreadable_images() {
|
||||
use craft::platform::clipboard::{HTML, RGBA8};
|
||||
|
||||
let url = "https://example.test/picture.png";
|
||||
let img = format!(r#"<img src="{url}">"#);
|
||||
let rich = format!("<p><strong>Caption</strong>{img}</p>");
|
||||
let good = rgba8(4, 4, 200);
|
||||
let bad = Flavor::new(RGBA8, vec![1, 0, 0, 0, 1, 0, 0, 0]);
|
||||
for (markup, bitmap, text, expected) in
|
||||
[(None, good.clone(), url, url), (Some(rich.as_str()), good, "Caption", "Caption"), (Some(img.as_str()), bad, url, url)]
|
||||
{
|
||||
let mut flavors = vec![Flavor::text(text), bitmap];
|
||||
if let Some(markup) = markup {
|
||||
flavors.push(Flavor::new(HTML, markup.as_bytes().to_vec()));
|
||||
}
|
||||
let mut app = app_holding(&flavors);
|
||||
app.run("edit.paste", json!({})).unwrap();
|
||||
assert_eq!(pictures(&mut app), 0);
|
||||
assert_eq!(app.session.doc.plain_text(wordcraft_doc::StoryRef::Body), expected);
|
||||
}
|
||||
}
|
||||
|
||||
/// Copied picture files insert as pictures, not as their paths; a folder entry and a
|
||||
/// non-picture file are skipped, and files that aren't pictures leave Paste to the usual path.
|
||||
#[test]
|
||||
|
||||
@@ -1150,44 +1150,6 @@ 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:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user