Compare commits

..
Author SHA1 Message Date
autocraft-bot[bot] 12ff59a960 Merge main (2d9790c3) into the pull request
Resolved the conflicts in flow.rs (fit_height now uses the default branc

Resolved the conflicts in flow.rs (fit_height now uses the default branch's pb.at_margin()) and in layout-parity.md (both sides' entries kept). I carried the PR's abs() handling of the bottom margin into the new leading_floor in page.rs. cargo check passes, the PR's negative-margin test passes, and cargo fmt --check is clean. I did not run the full suite.
2026-12-04 08:54:57 +00:00
Mauro Mazzieri 48fca374b3 #7108: describe the rule, not measurements 2026-12-03 10:19:54 +01:00
Mauro Mazzieri 5833546550 #7108: Page Setup keeps an exact margin it didn't change
An exact (negative) top or bottom margin the dialog still shows as the
section has it, on a page not turned, is left out of layout.margins, which
keeps a side left out; the fit checks count an exact margin at its size.
Regression test dialogs::tests::page_setup_keeps_an_exact_margin_it_didnt_change;
the parity history row names the existing command test correctly.
2026-12-03 10:00:35 +01:00
Mauro MazzieriandClaude Opus 5.5 5d43bb5414 Merge main into fix/exact-page-margins (#7107)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-21 18:52:08 +01:00
Mauro MazzieriandClaude Opus 5.5 63f5623990 Merge main into fix/exact-page-margins (#7107)
The UI port (#7101) deleted crates/ui-egui/src/canvas/margins.rs: the
ruler's margin handles now come from craft-libs (craft::pages::ui), whose
margin_range clamps a drag against the opposite margin as given. The
ruler fix of this branch (an exact, negative top or bottom margin counts
at its size) moves to rulers.rs: page_edges hands the ruler the top and
bottom margins' sizes, so a drag of the opposite edge keeps an inch of
text and layout.margins accepts it, and the ruler shows the edge where
the layout puts the body. margin_params sends only the moved edge, so an
exact margin stays exact unless it is the one dragged.

The test moves to canvas/tests/markup.rs (the ruler tests on main):
ruler_margin_drags_clamp_against_an_exact_opposite_margin. The old
margin tests in canvas/tests.rs, deleted on main, stay deleted.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-21 09:27:40 +01:00
Mauro MazzieriandClaude Opus 5.5 a830b61074 UI: ruler margin drags count an exact opposite margin at its size (#7107)
Dragging the bottom (top) edge on the vertical ruler clamped the margin
against the top (bottom) margin as stored, so an exact, negative one
widened the room: with a 792 pt page and a top margin of -72, dragging
the bottom edge to 72 pt gave a bottom margin of 720, which
layout.margins rejects because the margins' sizes leave no text. The
clamp now takes the opposite top or bottom margin's absolute value, as
layout.margins does, and keeps the inch of text (648 pt here). Positive
margins clamp as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-20 13:42:52 +01:00
mmazzieriandClaude Opus 5.5 b6a4fd1266 layout, engine: a negative top or bottom margin is exact, and the header or footer overlaps the body (#7107)
Word's exact margin (`w:pgMar` `w:top` / `w:bottom` below zero, ECMA-376 §17.6.11; DOC
sprmSDyaTop / sprmSDyaBottom) starts (ends) the body at the margin's size from the page edge
even when the header (footer) is taller: the two overlap instead of the band pushing the text.
WordCraft took the larger of the margin and the header. On the synthetic reproducer (-60 pt
margins, six-line header and footer, 100 body lines) Word lays out 2 pages and WordCraft 3.

Layout:
- `body_top_for` and `PageBuilder::body_bottom` place a negative margin's body at its size and
  leave the header and footer out of it;
- the other places that read the margins as a size (`SectionProps::text_height`,
  margin-relative floats and frames, the continuous views, line fitting at the bottom margin,
  turned sections) take their absolute value.

Page Setup, as measured in Word:
- `layout.margins` keeps the value of a side it is not given, so an exact top or bottom stays
  exact when another margin changes (a negative value given still counts as 0);
- `set_landscape` turns an exact top or bottom into a side at its size;
- `layout.size` checks the room with the margins' sizes.
`layout.pageSetup` still clamps a negative margin to 0 (its documented contract, pinned by
`page_setup_section_is_validated`).

The readers keep the sign with storytold/craft-libs#2516; until the craft-libs pin moves, a DOC
or DOCX reaches the layout with a positive or zero margin. With both changes, on 159 local
DOC/DOCX files 158 PDFs are byte-identical; the one with a negative top margin goes from 7
pages to Word's 6.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-20 08:18:45 +01:00
131 changed files with 990 additions and 3772 deletions
Generated
+116 -130
View File
@@ -1173,7 +1173,7 @@ dependencies = [
[[package]]
name = "craft"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"craft-automation",
"craft-behavior",
@@ -1214,7 +1214,7 @@ dependencies = [
[[package]]
name = "craft-appkit"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"block2 0.6.2",
"objc2 0.6.5",
@@ -1226,7 +1226,7 @@ dependencies = [
[[package]]
name = "craft-atomic"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"rustix 1.1.6",
]
@@ -1234,7 +1234,7 @@ dependencies = [
[[package]]
name = "craft-automation"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"base64 0.23.1",
"craft-behavior",
@@ -1259,7 +1259,7 @@ dependencies = [
[[package]]
name = "craft-behavior"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"accesskit",
"bitflags 2.13.2",
@@ -1277,7 +1277,7 @@ dependencies = [
[[package]]
name = "craft-browse"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"craft-behavior",
"craft-docpath",
@@ -1295,12 +1295,12 @@ dependencies = [
[[package]]
name = "craft-cfb"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
[[package]]
name = "craft-cloud-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"egui",
]
@@ -1308,7 +1308,7 @@ dependencies = [
[[package]]
name = "craft-cms"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"md-5",
"rayon",
@@ -1317,12 +1317,12 @@ dependencies = [
[[package]]
name = "craft-codepage"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
[[package]]
name = "craft-color"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"serde",
]
@@ -1330,7 +1330,7 @@ dependencies = [
[[package]]
name = "craft-color-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"craft-behavior",
"craft-cms",
@@ -1350,7 +1350,7 @@ dependencies = [
[[package]]
name = "craft-control"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"craft-control-protocol",
"craft-platform",
@@ -1361,7 +1361,7 @@ dependencies = [
[[package]]
name = "craft-control-protocol"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"getrandom 0.3.4",
"serde_json",
@@ -1371,7 +1371,7 @@ dependencies = [
[[package]]
name = "craft-dds"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"rayon",
]
@@ -1379,7 +1379,7 @@ dependencies = [
[[package]]
name = "craft-dialogs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"block2 0.6.2",
"craft-appkit",
@@ -1405,7 +1405,7 @@ dependencies = [
[[package]]
name = "craft-doc-binary"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"chrono",
"craft-cfb",
@@ -1422,7 +1422,7 @@ dependencies = [
[[package]]
name = "craft-docpath"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"serde",
]
@@ -1430,7 +1430,7 @@ dependencies = [
[[package]]
name = "craft-docx"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"base64 0.23.1",
"chrono",
@@ -1450,7 +1450,7 @@ dependencies = [
[[package]]
name = "craft-draw"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"craft-behavior",
"craft-color-ui",
@@ -1469,7 +1469,7 @@ dependencies = [
[[package]]
name = "craft-drawingml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"chrono",
"craft-xml",
@@ -1481,7 +1481,7 @@ dependencies = [
[[package]]
name = "craft-flow"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"craft-wordmodel",
"image",
@@ -1491,7 +1491,7 @@ dependencies = [
[[package]]
name = "craft-font-catalog"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"fontique",
"harfrust 0.13.3",
@@ -1506,7 +1506,7 @@ dependencies = [
[[package]]
name = "craft-font-manager"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"craft-behavior",
"craft-font-catalog",
@@ -1525,7 +1525,7 @@ dependencies = [
[[package]]
name = "craft-font-os-windows"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"windows-registry",
"windows-sys 0.61.2",
@@ -1534,7 +1534,7 @@ dependencies = [
[[package]]
name = "craft-font-store"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"cap-primitives",
"craft-atomic",
@@ -1557,7 +1557,7 @@ dependencies = [
[[package]]
name = "craft-font-subset"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"brotli 9.1.3",
"harfbuzz-subset-sys",
@@ -1570,7 +1570,7 @@ dependencies = [
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"craft-font-subset",
]
@@ -1578,7 +1578,7 @@ dependencies = [
[[package]]
name = "craft-gpu"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"egui-wgpu",
"log",
@@ -1590,7 +1590,7 @@ dependencies = [
[[package]]
name = "craft-host"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"bitflags 2.13.2",
"craft-i18n",
@@ -1603,7 +1603,7 @@ dependencies = [
[[package]]
name = "craft-html"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"craft-codepage",
"craft-flow",
@@ -1616,7 +1616,7 @@ dependencies = [
[[package]]
name = "craft-i18n"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"brotli 9.1.3",
"brotli-decompressor 6.3.1",
@@ -1646,7 +1646,7 @@ dependencies = [
[[package]]
name = "craft-image-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"craft-dds",
"craft-jpeg",
@@ -1673,7 +1673,7 @@ dependencies = [
[[package]]
name = "craft-imaging"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"craft-behavior",
"craft-color-ui",
@@ -1691,7 +1691,7 @@ dependencies = [
[[package]]
name = "craft-jpeg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"thiserror 2.0.21",
]
@@ -1699,7 +1699,7 @@ dependencies = [
[[package]]
name = "craft-keymap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"craft-host",
"craft-i18n",
@@ -1714,7 +1714,7 @@ dependencies = [
[[package]]
name = "craft-latex"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"craft-flow",
"craft-math",
@@ -1725,7 +1725,7 @@ dependencies = [
[[package]]
name = "craft-markdown"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"craft-flow",
"craft-html",
@@ -1735,7 +1735,7 @@ dependencies = [
[[package]]
name = "craft-math"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"craft-xml",
"roxmltree",
@@ -1745,7 +1745,7 @@ dependencies = [
[[package]]
name = "craft-mcp-server"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"serde_json",
]
@@ -1753,7 +1753,7 @@ dependencies = [
[[package]]
name = "craft-menu"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"craft-behavior",
"craft-host",
@@ -1771,7 +1771,7 @@ dependencies = [
[[package]]
name = "craft-metadata"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"brotli-decompressor 6.3.1",
"chrono",
@@ -1783,7 +1783,7 @@ dependencies = [
[[package]]
name = "craft-metafile"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"encoding_rs",
"image",
@@ -1794,7 +1794,7 @@ dependencies = [
[[package]]
name = "craft-mime"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"chardetng",
"chrono",
@@ -1805,7 +1805,7 @@ dependencies = [
[[package]]
name = "craft-nightly"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"uds_windows",
"winsafe",
@@ -1814,7 +1814,7 @@ dependencies = [
[[package]]
name = "craft-odf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"aes",
"base64 0.23.1",
@@ -1840,7 +1840,7 @@ dependencies = [
[[package]]
name = "craft-ods"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"craft-odf",
"craft-sheet",
@@ -1851,7 +1851,7 @@ dependencies = [
[[package]]
name = "craft-offcrypto"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"aes",
"base64 0.23.1",
@@ -1868,7 +1868,7 @@ dependencies = [
[[package]]
name = "craft-opc"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"craft-xml",
"craft-zip",
@@ -1879,7 +1879,7 @@ dependencies = [
[[package]]
name = "craft-pages"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"craft-behavior",
"craft-keymap",
@@ -1895,7 +1895,7 @@ dependencies = [
[[package]]
name = "craft-pdf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"krilla",
"serde",
@@ -1905,7 +1905,7 @@ dependencies = [
[[package]]
name = "craft-platform"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"arboard",
"async-channel",
@@ -1943,7 +1943,7 @@ dependencies = [
[[package]]
name = "craft-print"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"craft-behavior",
"craft-host",
@@ -1967,7 +1967,7 @@ dependencies = [
[[package]]
name = "craft-proof"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"log",
"miniz_oxide 0.9.1",
@@ -1978,7 +1978,7 @@ dependencies = [
[[package]]
name = "craft-quit"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"dispatch2",
"egui",
@@ -1991,7 +1991,7 @@ dependencies = [
[[package]]
name = "craft-review"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"base64 0.23.1",
"craft-behavior",
@@ -2010,7 +2010,7 @@ dependencies = [
[[package]]
name = "craft-rtf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"craft-codepage",
"craft-flow",
@@ -2023,7 +2023,7 @@ dependencies = [
[[package]]
name = "craft-settings"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"craft-atomic",
"craft-host",
@@ -2040,17 +2040,17 @@ dependencies = [
[[package]]
name = "craft-sheet"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
[[package]]
name = "craft-ssip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
[[package]]
name = "craft-svg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"craft-xml",
"flate2",
@@ -2067,7 +2067,7 @@ dependencies = [
[[package]]
name = "craft-table"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"craft-behavior",
"craft-keymap",
@@ -2079,7 +2079,7 @@ dependencies = [
[[package]]
name = "craft-text"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2103,7 +2103,7 @@ dependencies = [
[[package]]
name = "craft-theme"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"bitflags 2.13.2",
"craft-tracked",
@@ -2118,7 +2118,7 @@ dependencies = [
[[package]]
name = "craft-theme-store"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"craft-atomic",
"craft-behavior",
@@ -2133,7 +2133,7 @@ dependencies = [
[[package]]
name = "craft-tiff"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -2143,7 +2143,7 @@ dependencies = [
[[package]]
name = "craft-time"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -2152,7 +2152,7 @@ dependencies = [
[[package]]
name = "craft-timeline"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"craft-behavior",
"craft-keymap",
@@ -2167,12 +2167,12 @@ dependencies = [
[[package]]
name = "craft-tracked"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"craft-cloud-ui",
"craft-ui-canvas",
@@ -2186,7 +2186,7 @@ dependencies = [
[[package]]
name = "craft-ui-canvas"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"craft-behavior",
"craft-font-catalog",
@@ -2203,7 +2203,7 @@ dependencies = [
[[package]]
name = "craft-ui-contract"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"accesskit",
"craft-behavior",
@@ -2241,7 +2241,7 @@ dependencies = [
[[package]]
name = "craft-ui-macros"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"proc-macro-crate",
"proc-macro2",
@@ -2252,7 +2252,7 @@ dependencies = [
[[package]]
name = "craft-ui-panels"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2270,7 +2270,7 @@ dependencies = [
[[package]]
name = "craft-ui-patterns"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2291,7 +2291,7 @@ dependencies = [
[[package]]
name = "craft-ui-shell"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2312,7 +2312,7 @@ dependencies = [
[[package]]
name = "craft-ui-test-kit"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2323,7 +2323,7 @@ dependencies = [
[[package]]
name = "craft-ui-widgets"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2342,7 +2342,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"base64 0.22.1",
"chrono",
@@ -2374,7 +2374,7 @@ dependencies = [
[[package]]
name = "craft-web-api"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"js-sys",
"serde_json",
@@ -2385,7 +2385,7 @@ dependencies = [
[[package]]
name = "craft-web-host"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"craft-host",
"craft-platform",
@@ -2397,7 +2397,7 @@ dependencies = [
[[package]]
name = "craft-win32"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"winsafe",
]
@@ -2405,7 +2405,7 @@ dependencies = [
[[package]]
name = "craft-window"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"craft-appkit",
"craft-atomic",
@@ -2437,7 +2437,7 @@ dependencies = [
[[package]]
name = "craft-wordmodel"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"base64 0.23.1",
"craft-math",
@@ -2451,7 +2451,7 @@ dependencies = [
[[package]]
name = "craft-xls"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"craft-cfb",
"craft-sheet",
@@ -2464,7 +2464,7 @@ dependencies = [
[[package]]
name = "craft-xlsx"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"craft-drawingml",
"craft-opc",
@@ -2476,7 +2476,7 @@ dependencies = [
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"quick-xml 0.41.0",
"serde",
@@ -2486,7 +2486,7 @@ dependencies = [
[[package]]
name = "craft-zip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"flate2",
"thiserror 2.0.21",
@@ -3828,19 +3828,6 @@ dependencies = [
"smallvec",
]
[[package]]
name = "harfrust"
version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "865dcc4105d51c323d8fedbb2d75b5e9c8ecddf5613f74c82f851d0afbc97114"
dependencies = [
"bitflags 2.13.2",
"bytemuck",
"read-fonts 0.46.0",
"smallvec",
"yoke",
]
[[package]]
name = "hashbrown"
version = "0.15.5"
@@ -3879,7 +3866,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
[[package]]
name = "hayro-cmap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"brotli 8.0.4",
"hayro-postscript",
@@ -3888,7 +3875,7 @@ dependencies = [
[[package]]
name = "hayro-interpret"
version = "0.7.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"bitflags 2.13.2",
"hayro-cmap",
@@ -3906,7 +3893,7 @@ dependencies = [
[[package]]
name = "hayro-jbig2"
version = "0.3.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"fearless_simd",
"hayro-ccitt",
@@ -3924,12 +3911,12 @@ dependencies = [
[[package]]
name = "hayro-postscript"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
[[package]]
name = "hayro-syntax"
version = "0.7.2"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"flate2",
"hayro-ccitt",
@@ -4658,7 +4645,7 @@ dependencies = [
[[package]]
name = "krilla"
version = "0.8.2"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"base64 0.22.1",
"bumpalo",
@@ -4797,7 +4784,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
[[package]]
name = "linesweeper"
version = "0.5.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
dependencies = [
"arrayvec",
"kurbo",
@@ -9131,7 +9118,7 @@ dependencies = [
[[package]]
name = "wordcraft"
version = "0.20.1"
version = "0.20.0"
dependencies = [
"craft",
"craft-nightly",
@@ -9158,7 +9145,7 @@ dependencies = [
[[package]]
name = "wordcraft-cli"
version = "0.20.1"
version = "0.20.0"
dependencies = [
"craft-zip",
"image",
@@ -9176,11 +9163,11 @@ dependencies = [
[[package]]
name = "wordcraft-control-key"
version = "0.20.1"
version = "0.20.0"
[[package]]
name = "wordcraft-doc"
version = "0.20.1"
version = "0.20.0"
dependencies = [
"base64 0.23.1",
"craft-codepage",
@@ -9196,7 +9183,7 @@ dependencies = [
[[package]]
name = "wordcraft-docbin"
version = "0.20.1"
version = "0.20.0"
dependencies = [
"cfb",
"craft-doc-binary",
@@ -9208,7 +9195,7 @@ dependencies = [
[[package]]
name = "wordcraft-docx"
version = "0.20.1"
version = "0.20.0"
dependencies = [
"base64 0.23.1",
"cfb",
@@ -9227,7 +9214,7 @@ dependencies = [
[[package]]
name = "wordcraft-engine"
version = "0.20.1"
version = "0.20.0"
dependencies = [
"cfb",
"chrono",
@@ -9265,10 +9252,10 @@ dependencies = [
[[package]]
name = "wordcraft-fonts"
version = "0.20.1"
version = "0.20.0"
dependencies = [
"brotli-decompressor 5.0.3",
"harfrust 0.15.0",
"harfrust 0.13.3",
"kurbo",
"log",
"serde_json",
@@ -9280,7 +9267,7 @@ dependencies = [
[[package]]
name = "wordcraft-formats"
version = "0.20.1"
version = "0.20.0"
dependencies = [
"chardetng",
"chrono",
@@ -9310,7 +9297,7 @@ dependencies = [
[[package]]
name = "wordcraft-geom"
version = "0.20.1"
version = "0.20.0"
dependencies = [
"craft-image-codecs",
"craft-tiff",
@@ -9320,11 +9307,10 @@ dependencies = [
[[package]]
name = "wordcraft-layout"
version = "0.20.1"
version = "0.20.0"
dependencies = [
"craft-metafile",
"craft-proof",
"craft-xml",
"image",
"js-sys",
"kurbo",
@@ -9341,7 +9327,7 @@ dependencies = [
[[package]]
name = "wordcraft-mcp"
version = "0.20.1"
version = "0.20.0"
dependencies = [
"craft",
"craft-mcp-server",
@@ -9355,7 +9341,7 @@ dependencies = [
[[package]]
name = "wordcraft-pdf"
version = "0.20.1"
version = "0.20.0"
dependencies = [
"chrono",
"craft-metafile",
@@ -9376,7 +9362,7 @@ dependencies = [
[[package]]
name = "wordcraft-render"
version = "0.20.1"
version = "0.20.0"
dependencies = [
"craft-metafile",
"image",
@@ -9390,7 +9376,7 @@ dependencies = [
[[package]]
name = "wordcraft-ui-egui"
version = "0.20.1"
version = "0.20.0"
dependencies = [
"cfb",
"chrono",
@@ -9424,7 +9410,7 @@ dependencies = [
[[package]]
name = "wordcraft-validate"
version = "0.20.1"
version = "0.20.0"
dependencies = [
"craft-image-codecs",
"craft-tiff",
@@ -9439,7 +9425,7 @@ dependencies = [
[[package]]
name = "wordcraft-web"
version = "0.20.1"
version = "0.20.0"
dependencies = [
"craft",
"eframe",
@@ -9459,7 +9445,7 @@ dependencies = [
[[package]]
name = "wordcraft-zotero"
version = "0.20.1"
version = "0.20.0"
dependencies = [
"log",
"proptest",
@@ -9677,7 +9663,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
[[package]]
name = "xtask"
version = "0.20.1"
version = "0.20.0"
dependencies = [
"serde",
"serde_json",
@@ -10067,4 +10053,4 @@ source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f
[[patch.unused]]
name = "hayro"
version = "0.7.1"
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
source = "git+https://github.com/storytold/craft-libs?rev=5299d8d97dc04648dff735d1bd6f60bd18f10b35#5299d8d97dc04648dff735d1bd6f60bd18f10b35"
+41 -41
View File
@@ -13,7 +13,7 @@ run_slots = 3
test_threads = 4
[workspace.package]
version = "0.20.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 = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
wordcraft-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 = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", default-features = false }
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
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"] }
@@ -75,7 +75,7 @@ regex-automata = { version = "0.4", default-features = false, features = ["std",
# text / rendering / formats
skrifa = "0.47"
harfrust = "0.15"
harfrust = "0.13"
# WOFF / WOFF2 web fonts added by the user (#582): pure Rust (MIT); its brotli and zlib decoders
# (brotli-decompressor, flate2) are already in the tree.
wuff = "0.2.9"
@@ -85,28 +85,28 @@ wuff = "0.2.9"
brotli-decompressor = "5"
vello_cpu = "0.2"
image = { version = "0.25", default-features = false }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", default-features = false, features = ["write"] }
craft-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 = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", features = ["doc"] }
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", features = ["text"] }
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", features = ["flow"] }
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", features = ["detect"] }
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
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,14 +174,14 @@ debug = 0
# The framework's patches, which Cargo does not carry over to dependents: its vendored crates from craft-libs,
# and the egui and winit forks it builds with.
[patch.crates-io]
krilla = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
hayro = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
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" }
-3
View File
@@ -386,12 +386,9 @@ emerge --ask app-office/wordcraft-bin
### FreeBSD
Prebuilt FreeBSD release archives target FreeBSD 15.1 or newer; FreeBSD 14.x is not supported by these builds.
| Build | File |
|---|---|
| x86_64 | `wordcraft-<ver>-freebsd-x86_64.tar.gz` |
| aarch64 | `wordcraft-<ver>-freebsd-aarch64.tar.gz` |
### Web (WebAssembly)
+1 -4
View File
File diff suppressed because one or more lines are too long
+6 -18
View File
@@ -563,17 +563,6 @@ fn run_source_paths(rest: &[String], script: Option<&script::Script>) -> (Option
(from_file, from_template)
}
/// Show a successful command's result, or its warning when results aren't printed.
fn report_run_result(id: &str, result: &Value, print: bool) -> Result<(), Failure> {
if print {
return write_stdout(|o| writeln!(o, "{id}: {result}"));
}
if let Some(warning) = result.get("warning").and_then(Value::as_str) {
let _ = writeln!(std::io::stderr().lock(), "wordcraft-cli: warning: {}", escape_text(warning, false));
}
Ok(())
}
/// Run the subcommand named by `args` (the command line after the program name). Files named
/// there are opened by their real names, which may not be valid Unicode.
fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
@@ -677,7 +666,9 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
let print = rest.iter().any(|a| a == "--print");
for (n, (id, params)) in script.iter().flat_map(|c| c.commands.iter()).enumerate() {
let r = s.run(id, params).map_err(|e| engine_error(format!("command {} ({id}): {e}", n + 1)))?;
report_run_result(id, &r, print)?;
if print {
write_stdout(|o| writeln!(o, "{id}: {r}"))?;
}
}
let mut i = 0;
while i < rest.len() {
@@ -690,7 +681,9 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
None => (spec.clone(), json!({})),
};
let r = s.run(&id, &params).map_err(|e| engine_error(format!("{id}: {e}")))?;
report_run_result(&id, &r, print)?;
if print {
write_stdout(|o| writeln!(o, "{id}: {r}"))?;
}
i += 2;
} else {
i += 1;
@@ -1070,11 +1063,6 @@ fn main() -> ExitCode {
eprintln!("wordcraft-cli: --launch-profile and --profile-root are the desktop app's Nightly bootstrap, not a CLI option");
return ExitCode::from(2);
}
// The engine logs this, but the command line installs no logger, and it is where a
// reproducible build runs.
if let Some(problem) = wordcraft_engine::cmd::source_date_epoch_problem() {
eprintln!("wordcraft-cli: warning: {problem}");
}
// Language packs installed in the suite's font store are used; `proof.installPack` installs
// only while the person has turned downloading on in the app.
wordcraft_engine::packs::use_font_store(false);
-64
View File
@@ -710,70 +710,6 @@ fn script_reads_from_a_stream_and_caps_its_size() {
assert!(script::load_from(&b"{"[..], "-", None).is_err());
}
#[test]
fn run_result_warnings_use_stderr_without_print() {
use std::process::Command;
const CHILD_ARGS: &str = "WORDCRAFT_CLI_WARNING_TEST_ARGS";
const STORE: &str = "WORDCRAFT_CLI_WARNING_TEST_STORE";
const WARNING: &str = "added for this session only: couldn't store it";
if let Ok(argv) = std::env::var(CHILD_ARGS) {
let store = PathBuf::from(std::env::var_os(STORE).unwrap());
wordcraft_fonts::FontDb::global().load_user_fonts(&store);
run(&serde_json::from_str::<Vec<String>>(&argv).unwrap()).unwrap();
// Bypass the test harness summary so the parent sees only the same header and the CLI's
// output. Each child has its own font database and never configures a real user store.
std::process::exit(0);
}
let dir = script_dir("run-warnings");
let store = dir.join("not-a-directory");
std::fs::write(&store, b"blocked font store").unwrap();
// Like the engine's font.add fixture, rename the bundled JetBrains Mono family in memory
// so it is treated as a new face. No additional font asset is used.
let mut font = include_bytes!("../../../assets/fonts/JetBrainsMono-Regular.ttf").to_vec();
let utf16 = |name: &str| name.encode_utf16().flat_map(u16::to_be_bytes).collect::<Vec<u8>>();
for (old, new) in [(b"JetBrains Mono".to_vec(), b"Cli Fixture 42".to_vec()), (utf16("JetBrains Mono"), utf16("Cli Fixture 42"))] {
let mut start = 0;
while let Some(at) = font[start..].windows(old.len()).position(|bytes| bytes == old) {
let range = start + at..start + at + old.len();
start = range.end;
font[range].copy_from_slice(&new);
}
}
let path = dir.join("fixture.ttf");
std::fs::write(&path, font).unwrap();
let params = json!({"path": path.to_string_lossy()});
let spec = format!("font.add={params}");
let script = write_script(&dir, &json!({"commands": [{"command": "font.add", "params": params}]}).to_string());
let child = |argv: &[&str]| {
let out = Command::new(std::env::current_exe().unwrap())
.args(["--exact", "tests::run_result_warnings_use_stderr_without_print", "--nocapture"])
.env(CHILD_ARGS, json!(argv).to_string())
.env(STORE, &store)
.output()
.unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
(String::from_utf8(out.stdout).unwrap(), String::from_utf8(out.stderr).unwrap())
};
let (header, quiet_stderr) = child(&["run", "--cmd", "caret.docEnd"]);
assert!(quiet_stderr.is_empty(), "{quiet_stderr}");
for argv in [["run", "--cmd", &spec], ["run", "--script", &script]] {
let (stdout, stderr) = child(&argv);
assert_eq!(stdout, header);
assert!(stderr.starts_with(&format!("wordcraft-cli: warning: {WARNING}")), "{stderr}");
assert_eq!(stderr.lines().count(), 1, "{stderr}");
let (stdout, stderr) = child(&[argv[0], argv[1], argv[2], "--print"]);
assert!(stderr.is_empty(), "{stderr}");
let result = stdout.strip_prefix(&header).unwrap().strip_prefix("font.add: ").unwrap();
let result: Value = serde_json::from_str(result).unwrap();
let warning = result["warning"].as_str().unwrap();
assert!(warning.starts_with(WARNING), "{result}");
}
}
#[test]
fn script_commands_run_before_cmd_flags() {
let dir = script_dir("order");
-17
View File
@@ -37,20 +37,3 @@ fn run_saves_the_document_opened_last() {
let stdout = String::from_utf8_lossy(&listed.stdout);
assert_eq!(stdout.matches("\"id\"").count(), 1, "{stdout}");
}
#[test]
fn failed_run_commands_still_exit_with_an_error() {
let script = std::env::temp_dir().join(format!("wordcraft-cli-run-error-{}.json", std::process::id()));
std::fs::write(&script, r#"{"commands":["no.such.command"]}"#).unwrap();
let script_path = script.to_string_lossy();
let cases = [(["run", "--cmd", "no.such.command"], "no.such.command:"), (["run", "--script", &script_path], "command 1 (no.such.command):")];
for (args, expected) in cases {
let out = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).args(args).output().unwrap();
assert_eq!(out.status.code(), Some(1));
assert!(out.stdout.is_empty(), "{out:?}");
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(stderr.starts_with("wordcraft-cli: ") && stderr.contains(expected), "{stderr}");
assert!(!stderr.contains("wordcraft-cli: warning:"), "{stderr}");
}
std::fs::remove_file(script).unwrap();
}
@@ -1,127 +0,0 @@
//! Direct PDF exports use the saved timestamp without changing the source document.
use std::process::Command;
#[test]
fn direct_pdf_exports_use_the_pinned_epoch() {
check_creation_date("", "20261005140300");
}
#[test]
fn direct_pdf_exports_preserve_an_existing_creation_date() {
check_creation_date("2000-01-01T00:00:00Z", "20000101000000");
}
/// A .docx records `dcterms:created` as text and the reader takes it as it finds it, so a
/// document can arrive holding something that is not a date at all. The PDF writer cannot put
/// that in a document and fell back to the clock, so two exports of the same file differed even
/// with `SOURCE_DATE_EPOCH` set -- the one thing it is there to stop (noted in review).
#[test]
fn direct_pdf_exports_use_the_pinned_epoch_when_the_existing_date_is_unreadable() {
for created in ["not-a-date", "", " ", "2000-13-01T00:00:00Z", "2000-01-32T00:00:00Z", "99-01-01", "today"] {
check_creation_date(created, "20261005140300");
}
}
fn check_creation_date(created: &str, expected: &str) {
// A sequence number, not the clock alone: `as_nanos` carries microsecond granularity on
// macOS, so two of these tests starting in the same microsecond took the same directory,
// wrote each other's `input.json` and failed the preservation assertion below -- a flake in
// this harness, not in the export. `create_dir` rather than `create_dir_all` so that if a
// name ever does repeat it fails here instead of quietly sharing a directory again.
static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let seq = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let dir = std::env::temp_dir().join(format!("wordcraft-pdf-date-{}-{unique}-{seq}", std::process::id()));
std::fs::create_dir(&dir).unwrap_or_else(|e| panic!("{}: {e}", dir.display()));
let mut doc = wordcraft_doc::Document::from_text("Original reproducible PDF check.");
doc.core.created = created.into();
let input = dir.join("input.json");
let source = serde_json::to_vec(&doc).unwrap();
std::fs::write(&input, &source).unwrap();
for command in ["file.exportPdf", "file.printPdf"] {
let output = dir.join(format!("{command}.pdf"));
let params = serde_json::json!({"path": output});
let run = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"))
.arg("run")
.arg("--file")
.arg(&input)
.arg("--cmd")
.arg(format!("{command}={params}"))
.env("SOURCE_DATE_EPOCH", "1791208980")
.output()
.unwrap();
assert!(run.status.success(), "{command}: {}", String::from_utf8_lossy(&run.stderr));
let bytes = std::fs::read(output).unwrap();
let date = format!("/CreationDate(D:{expected}");
assert!(bytes.windows(date.len()).any(|part| part == date.as_bytes()), "{command} must use {expected}");
assert_eq!(std::fs::read(&input).unwrap(), source, "export must preserve its source file");
}
}
/// A fresh directory for one test's files.
fn scratch(name: &str) -> std::path::PathBuf {
let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let dir = std::env::temp_dir().join(format!("wordcraft-{name}-{}-{unique}", std::process::id()));
std::fs::create_dir(&dir).unwrap_or_else(|e| panic!("{}: {e}", dir.display()));
dir
}
fn cli(env: &str, cmds: &[String]) -> std::process::Output {
let mut run = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"));
run.arg("run").env("SOURCE_DATE_EPOCH", env);
for c in cmds {
run.arg("--cmd").arg(c);
}
run.output().unwrap()
}
/// The pinned date is the file's, not the edits': a comment and a tracked change made in the
/// same run keep the time they were made, so a pinned epoch cannot back-date them (noted in
/// review). Saved as flat XML, which holds both in plain text.
#[test]
fn a_pinned_epoch_dates_the_file_and_not_the_edits_in_it() {
let out = scratch("pinned-edits").join("edits.xml");
let before = wordcraft_engine::cmd::now_iso();
let run = cli(
"1791208980",
&[
r#"review.trackChanges={"value": true}"#.to_string(),
r#"text.insert={"text": "tracked"}"#.to_string(),
r#"review.newComment={"text": "note"}"#.to_string(),
format!("file.saveAs={}", serde_json::json!({"path": out})),
],
);
let after = wordcraft_engine::cmd::now_iso();
assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr));
let xml = std::fs::read_to_string(&out).unwrap();
assert!(xml.contains(r#"<dcterms:modified xsi:type="dcterms:W3CDTF">2026-10-05T14:03:00Z</dcterms:modified>"#), "the file's date is pinned");
let dates: Vec<&str> = xml.split(r#"w:date=""#).skip(1).filter_map(|rest| rest.split('"').next()).collect();
assert!(xml.contains("<w:ins ") && xml.contains("<w:comment "), "a tracked insertion and a comment were saved");
assert!(dates.len() >= 2, "both carry a date: {dates:?}");
for date in dates {
assert!((before.as_str()..=after.as_str()).contains(&date), "{date} is the clock's, between {before} and {after}");
}
}
/// A value that is set and cannot be used is said out loud, and the run still succeeds: the
/// files take the clock's date, as they would with the variable unset (noted in review).
#[test]
fn an_unusable_epoch_is_reported_on_stderr() {
let dir = scratch("epoch-warning");
let save = |name: &str| format!("file.exportPdf={}", serde_json::json!({"path": dir.join(name)}));
let run = cli("later", &[save("later.pdf")]);
assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr));
let stderr = String::from_utf8_lossy(&run.stderr);
assert!(stderr.contains(r#"warning: SOURCE_DATE_EPOCH="later" is not a whole number of seconds"#), "{stderr}");
let pdf = std::fs::read(dir.join("later.pdf")).unwrap();
let pinned = b"/CreationDate(D:20261005140300";
assert!(pdf.windows(b"/CreationDate(D:".len()).any(|w| w == b"/CreationDate(D:"), "the export has a creation date");
assert!(!pdf.windows(pinned.len()).any(|w| w == pinned), "and it is the clock's, not a pinned one");
for quiet in ["1791208980", ""] {
let run = cli(quiet, &[save("quiet.pdf")]);
assert!(run.status.success());
assert!(!String::from_utf8_lossy(&run.stderr).contains("SOURCE_DATE_EPOCH"), "{quiet:?} says nothing");
}
}
-48
View File
@@ -1271,54 +1271,6 @@ mod smoke {
assert!(run.app.app.dialog_host_mut().is_empty(), "Escape dismisses About");
assert_eq!(run.app.app.session.doc.plain_text(wordcraft_doc::StoryRef::Body), before);
}
/// With a modal dialog open, Quit stays enabled and ⌘Q / menu Quit still run `ui.quit`:
/// a clean document quits and a modified one opens Save Changes (#8792).
#[cfg(target_os = "macos")]
#[test]
fn native_quit_works_while_a_modal_dialog_is_open() {
use craft::menu::{ItemRole, NativeMenu};
let mut clean = Run::new();
let fake = native_menu::FakeBackend::default();
let synced = fake.synced.clone();
let events = fake.events.clone();
let dispatch_cell = fake.dispatch.clone();
clean.app.native_menu = Some(NativeMenu::new(Box::new(fake)));
clean.app.app.run("ui.dialog", json!({"name": "about"})).unwrap();
clean.settle();
assert!(clean.app.app.dialog_host_mut().shows_modal());
let quit = {
let bars = synced.borrow();
let bar = bars.last().unwrap();
let about = bar.items().into_iter().find(|item| item.role == Some(ItemRole::About)).unwrap();
let quit = bar.items().into_iter().find(|item| item.role == Some(ItemRole::Quit)).unwrap();
assert!(!about.enabled, "About is greyed while About is open");
assert!(quit.enabled, "Quit stays enabled while About is open");
quit.clone()
};
let dispatch = dispatch_cell.borrow().as_ref().unwrap().clone();
let cmd_q = quit.shortcut.unwrap();
events.borrow_mut().push(dispatch.chosen(&quit.command, Some(&cmd_q), quit.layout_shortcut, true, cmd_q.mods, None));
clean.settle();
assert!(clean.app.app.quit_requested, "Cmd+Q quits a clean document while About is open");
let mut dirty = Run::new();
let fake = native_menu::FakeBackend::default();
let events = fake.events.clone();
let dispatch_cell = fake.dispatch.clone();
dirty.app.native_menu = Some(NativeMenu::new(Box::new(fake)));
dirty.app.app.run("text.insert", json!({"text": "unsaved"})).unwrap();
dirty.app.app.run("ui.dialog", json!({"name": "paragraph"})).unwrap();
dirty.settle();
assert!(dirty.app.app.dialog_host_mut().shows_modal());
let dispatch = dispatch_cell.borrow().as_ref().unwrap().clone();
events.borrow_mut().push(dispatch.chosen(&quit.command, Some(&cmd_q), quit.layout_shortcut, false, Default::default(), None));
dirty.settle();
assert!(!dirty.app.app.quit_requested, "Quit asks Save Changes first for a modified document");
dirty.app.app.run("ui.saveChanges", json!({"answer": "dontSave"})).unwrap();
assert!(dirty.app.app.quit_requested, "Don't Save completes the quit");
}
}
#[cfg(test)]
+3 -68
View File
@@ -1,6 +1,6 @@
//! The macOS application menu uses the same About dialog as File › About.
use craft::menu::{CommandRef, Gate, Item, ItemRole, Layout, LayoutOptions, Menu, MenuBar, MenuRole, ModalRules, NativeMenu, mac_layout};
use craft::menu::{CommandRef, Gate, Item, ItemRole, Layout, LayoutOptions, Menu, MenuBar, MenuRole, NativeMenu, mac_layout};
use serde_json::json;
use wordcraft_ui_egui::{WordApp, i18n};
@@ -36,24 +36,15 @@ fn layout_in(lang: i18n::Lang) -> Layout {
layout(&|s| i18n::tr(lang, s).to_owned())
}
/// Commands that still run from the application menu while a modal dialog is open: `ui.quit` asks
/// about unsaved documents through `WordApp::quit`, matching the built-in Quit item and the Dock.
fn modal_rules() -> ModalRules {
ModalRules::default().in_dialogs(["ui.quit"])
}
pub(super) fn install(ctx: &egui::Context, app: &WordApp) -> Option<NativeMenu> {
let mut menu = craft::menu::mac::install(ctx, &layout_in(lang(app)).bar);
if let Some(menu) = &mut menu {
menu.set_modal_rules(modal_rules());
} else {
let menu = craft::menu::mac::install(ctx, &layout_in(lang(app)).bar);
if menu.is_none() {
log::warn!("the WordCraft application menu could not be installed");
}
menu
}
pub(super) fn update(menu: &mut NativeMenu, app: &mut WordApp, ctx: &egui::Context) {
menu.set_modal_rules(modal_rules());
menu.set_gate(Gate::default().modal(app.dialog_host_mut().shows_modal()));
for command in menu.take_clicks(ctx) {
if let Err(error) = app.run(&command.id, command.params) {
@@ -67,29 +58,6 @@ pub(super) fn update(menu: &mut NativeMenu, app: &mut WordApp, ctx: &egui::Conte
}
}
#[cfg(test)]
#[derive(Default)]
pub(super) struct FakeBackend {
pub(super) synced: std::rc::Rc<std::cell::RefCell<Vec<MenuBar>>>,
pub(super) events: std::rc::Rc<std::cell::RefCell<Vec<craft::menu::Event>>>,
pub(super) dispatch: std::rc::Rc<std::cell::RefCell<Option<craft::menu::Dispatch>>>,
}
#[cfg(test)]
impl craft::menu::Backend for FakeBackend {
fn sync(&mut self, bar: &MenuBar) {
self.synced.borrow_mut().push(bar.clone());
}
fn attach(&mut self, dispatch: craft::menu::Dispatch) {
*self.dispatch.borrow_mut() = Some(dispatch);
}
fn drain(&mut self) -> Vec<craft::menu::Event> {
std::mem::take(&mut *self.events.borrow_mut())
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -110,37 +78,4 @@ mod tests {
let quit = layout.bar.items().into_iter().find(|item| item.role == Some(ItemRole::Quit)).unwrap();
assert_eq!(quit.command.id, "ui.quit");
}
/// Quit stays enabled while a modal dialog is open, and both a menu click and ⌘Q pass the gate (#8792).
#[test]
fn quit_stays_enabled_and_runs_under_modal_rules() {
let fake = FakeBackend::default();
let synced = fake.synced.clone();
let events = fake.events.clone();
let dispatch_cell = fake.dispatch.clone();
let mut menu = NativeMenu::new(Box::new(fake));
menu.set_modal_rules(modal_rules());
menu.set_gate(Gate::default().modal(true));
let ctx = egui::Context::default();
menu.sync_with("en", || layout(&|s| s.to_owned()));
let bar = synced.borrow();
let last = bar.last().unwrap();
let about = last.items().into_iter().find(|item| item.role == Some(ItemRole::About)).unwrap().clone();
let quit = last.items().into_iter().find(|item| item.role == Some(ItemRole::Quit)).unwrap().clone();
drop(bar);
assert!(!about.enabled, "About is greyed while a modal dialog is open");
assert!(quit.enabled, "Quit stays enabled while a modal dialog is open");
let dispatch = dispatch_cell.borrow().as_ref().unwrap().clone();
let cmd_q = quit.shortcut.unwrap();
events.borrow_mut().extend([
dispatch.chosen(&about.command, about.shortcut.as_ref(), about.layout_shortcut, false, Default::default(), None),
dispatch.chosen(&quit.command, Some(&cmd_q), quit.layout_shortcut, false, Default::default(), None),
dispatch.chosen(&quit.command, Some(&cmd_q), quit.layout_shortcut, true, cmd_q.mods, None),
]);
menu.poll(&ctx);
assert_eq!(menu.take_clicks(&ctx), vec![quit.command.clone(), quit.command]);
}
}
+10 -2
View File
@@ -773,6 +773,10 @@ pub struct SectionProps {
pub page_w: f32,
pub page_h: f32,
pub landscape: bool,
/// Top and bottom margins, points. Negative is Word's exact margin (`w:pgMar` `w:top` /
/// `w:bottom` below zero, ECMA-376 §17.6.11; DOC `dyaTop` / `dyaBottom`): the text starts
/// (ends) at the absolute value from the page edge even when the header (footer) is taller,
/// and overlaps it.
pub margin_top: f32,
pub margin_bottom: f32,
pub margin_left: f32,
@@ -912,17 +916,21 @@ impl SectionProps {
pub fn text_width(&self) -> f32 {
(self.page_w - self.margin_left - self.margin_right - self.gutter).max(18.0)
}
/// Height of the text area between the margins, points (a negative, exact margin counts at
/// its size).
pub fn text_height(&self) -> f32 {
(self.page_h - self.margin_top - self.margin_bottom).max(18.0)
(self.page_h - self.margin_top.abs() - self.margin_bottom.abs()).max(18.0)
}
/// Swap to landscape/portrait (keeps margins relative to the paper as Word does: rotates them).
/// An exact (negative) top or bottom turns into a side at its size, as in Word: only the top
/// and bottom can be exact.
pub fn set_landscape(&mut self, on: bool) {
if on == self.landscape {
return;
}
self.landscape = on;
std::mem::swap(&mut self.page_w, &mut self.page_h);
let (t, b, l, r) = (self.margin_top, self.margin_bottom, self.margin_left, self.margin_right);
let (t, b, l, r) = (self.margin_top.abs(), self.margin_bottom.abs(), self.margin_left, self.margin_right);
if on {
self.margin_top = l;
self.margin_bottom = r;
-77
View File
@@ -93,83 +93,6 @@ fn run_and_style_snap_to_grid_and_web_hidden_survive_two_saves() {
}
}
/// Keeps run and style emphasis values intact across repeated DOCX saves.
#[test]
fn run_and_style_emphasis_marks_survive_two_saves() {
use wordcraft_doc::props::EmphasisMark;
let styles = r#"
<w:style w:type="character" w:styleId="Dot"><w:rPr><w:em w:val="dot"/></w:rPr></w:style>
<w:style w:type="character" w:styleId="Comma"><w:rPr><w:em w:val="comma"/></w:rPr></w:style>
<w:style w:type="character" w:styleId="Circle"><w:rPr><w:em w:val="circle"/></w:rPr></w:style>
<w:style w:type="character" w:styleId="UnderDot"><w:rPr><w:em w:val="underDot"/></w:rPr></w:style>
<w:style w:type="character" w:styleId="NoMark"><w:rPr><w:em w:val="none"/></w:rPr></w:style>
"#;
let body = r#"
<w:p>
<w:r><w:rPr><w:rStyle w:val="Dot"/></w:rPr><w:t>default dot</w:t></w:r>
<w:r><w:rPr><w:rStyle w:val="Comma"/></w:rPr><w:t>comma</w:t></w:r>
<w:r><w:rPr><w:rStyle w:val="Circle"/></w:rPr><w:t>circle</w:t></w:r>
<w:r><w:rPr><w:rStyle w:val="UnderDot"/></w:rPr><w:t>under dot</w:t></w:r>
<w:r><w:rPr><w:rStyle w:val="Dot"/><w:em w:val="none"/></w:rPr><w:t>explicit none</w:t></w:r>
<w:r><w:rPr><w:rStyle w:val="NoMark"/></w:rPr><w:t>style none</w:t></w:r>
<w:r><w:rPr><w:em w:val="dot"/></w:rPr><w:t>run dot</w:t></w:r>
<w:r><w:rPr><w:em w:val="comma"/></w:rPr><w:t>run comma</w:t></w:r>
<w:r><w:rPr><w:em w:val="circle"/></w:rPr><w:t>run circle</w:t></w:r>
<w:r><w:rPr><w:em w:val="underDot"/></w:rPr><w:t>run under dot</w:t></w:r>
<w:r><w:rPr><w:em w:val="none"/></w:rPr><w:t>run none</w:t></w:r>
<w:r><w:t>inherit absent</w:t></w:r>
</w:p>
"#;
let mut doc = wordcraft_docx::read(&docx(body, styles)).unwrap();
let p = doc.body.iter().find_map(|b| b.as_para()).unwrap();
let expected_styles = [
("Dot", Some(EmphasisMark::Dot)),
("Comma", Some(EmphasisMark::Comma)),
("Circle", Some(EmphasisMark::Circle)),
("UnderDot", Some(EmphasisMark::UnderDot)),
("NoMark", Some(EmphasisMark::None)),
];
for (id, mark) in expected_styles {
assert_eq!(doc.styles.get(id).and_then(|style| style.chr.emphasis), mark);
}
assert_eq!(p.runs[4].props.emphasis, Some(EmphasisMark::None));
let expected_runs = [
Some(EmphasisMark::Dot),
Some(EmphasisMark::Comma),
Some(EmphasisMark::Circle),
Some(EmphasisMark::UnderDot),
Some(EmphasisMark::None),
None,
];
for (run, mark) in p.runs.iter().skip(6).zip(expected_runs) {
assert_eq!(run.props.emphasis, mark);
}
for pass in 0..2 {
let out = wordcraft_docx::write(&doc).unwrap();
let style_xml = part(&out, "word/styles.xml");
for value in ["dot", "comma", "circle", "underDot", "none"] {
assert!(style_xml.contains(&format!(r#"<w:em w:val="{value}"/>"#)), "pass {pass}: {style_xml}");
}
let document_xml = part(&out, "word/document.xml");
assert!(document_xml.contains(r#"<w:em w:val="none"/>"#), "pass {pass}: {document_xml}");
assert!(document_xml.contains("default dot"));
doc = wordcraft_docx::read(&out).unwrap();
for (id, mark) in expected_styles {
assert_eq!(doc.styles.get(id).and_then(|style| style.chr.emphasis), mark, "pass {pass}");
}
let p = doc.body.iter().find_map(|b| b.as_para()).unwrap();
for index in [0, 1, 2, 3, 5] {
assert_eq!(p.runs[index].props.emphasis, None, "pass {pass}: run {index}");
}
assert_eq!(p.runs[4].props.emphasis, Some(EmphasisMark::None), "pass {pass}: run 4",);
for (run, mark) in p.runs.iter().skip(6).zip(expected_runs) {
assert_eq!(run.props.emphasis, mark, "pass {pass}");
}
}
}
#[test]
fn style_paragraph_and_run_changes_keep_independent_authors() {
let styles = r#"
+1 -108
View File
@@ -580,65 +580,11 @@ pub fn now_unix() -> u64 {
}
}
/// ISO-8601 timestamp (UTC, seconds): the clock, for an event that happened now -- a comment, a
/// tracked change, a version. Not for what a saved or exported file records: see [`saved_iso`].
/// ISO-8601 timestamp (UTC, seconds).
pub fn now_iso() -> String {
iso_from_unix_secs(now_unix())
}
/// The timestamp a saved or exported file records (its created and modified properties):
/// `SOURCE_DATE_EPOCH` when it holds a non-negative whole number of seconds, else the clock. With
/// it set, separate conversions of unchanged input can produce the same bytes. Repeated saves
/// of one session still advance the document revision
/// (<https://reproducible-builds.org/specs/source-date-epoch/>).
///
/// The clock stays in [`now_iso`]: an editing event's time is not the file's, and pinning it would
/// misdate comments and tracked changes.
///
/// A value that is set but not one of those is ignored with a warning, so a build that meant to
/// pin its dates hears that it did not.
pub fn saved_iso() -> String {
let raw = std::env::var("SOURCE_DATE_EPOCH").ok();
if let Some(problem) = epoch_problem(raw.as_deref()) {
log::warn!("{problem}");
}
iso_from_unix_secs(pinned_or(|_| raw.clone(), now_unix))
}
/// Why `SOURCE_DATE_EPOCH` is set and still not used, for a caller with no logger to say so (the
/// command line). `None` when it is unset, empty, or a value [`saved_iso`] takes.
pub fn source_date_epoch_problem() -> Option<String> {
epoch_problem(std::env::var("SOURCE_DATE_EPOCH").ok().as_deref())
}
/// An empty value counts as unset, as a CI file's `SOURCE_DATE_EPOCH=` with nothing after it
/// means; anything else that does not pin a date is worth a warning.
fn epoch_problem(value: Option<&str>) -> Option<String> {
let v = value?;
if v.trim().is_empty() || pinned(v).is_some() {
return None;
}
Some(format!(
"SOURCE_DATE_EPOCH={v:?} is not a whole number of seconds from 1970 to 9999-12-31, so saved and exported files take the clock's date"
))
}
/// The seconds a `SOURCE_DATE_EPOCH` value pins, if it pins any.
fn pinned(v: &str) -> Option<u64> {
v.trim().parse::<u64>().ok().filter(|secs| *secs <= LAST_DATE)
}
/// [`saved_iso`]'s choice, with the environment and the clock given so a test can show which wins.
pub(crate) fn pinned_or(get: impl Fn(&str) -> Option<String>, clock: impl Fn() -> u64) -> u64 {
get("SOURCE_DATE_EPOCH").as_deref().and_then(pinned).unwrap_or_else(clock)
}
/// The last date a document can record, as Unix seconds: 9999-12-31T23:59:59Z. A year runs to
/// four digits in `xsd:dateTime`, which is what a .docx core property holds, so a value past this
/// would be written as something no reader accepts -- `292277026596-12-04T15:30:07Z` for
/// `i64::MAX`. Such a value is left to the clock, as a malformed one is.
const LAST_DATE: u64 = 253_402_300_799;
/// The local time zone's offset from UTC in seconds (east positive) at `unix`, daylight saving
/// included: the system's zone, or the browser's on the web. 0 (UTC) when it can't be found.
pub fn local_offset_secs(unix: u64) -> i64 {
@@ -789,56 +735,3 @@ mod iso_tests {
let _ = (civil_from_days(i64::MAX), civil_from_days(i64::MIN));
}
}
#[cfg(test)]
mod saved_time_tests {
use super::{epoch_problem, iso_from_unix_secs, pinned_or};
/// What a saved or exported file records: `SOURCE_DATE_EPOCH` when it holds a non-negative
/// whole number of seconds, the clock whenever it does not. The environment and the clock are
/// given here rather than set, so no test changes this process's environment -- that is
/// `unsafe` under edition 2024 and would reach every test beside it.
#[test]
fn a_pinned_epoch_is_preferred_and_the_clock_answers_otherwise() {
let env = |v: Option<&'static str>| move |_: &str| v.map(str::to_owned);
let clock = || 1_000_000;
assert_eq!(pinned_or(env(Some("1791208980")), clock), 1_791_208_980, "the variable wins");
assert_eq!(pinned_or(env(Some("0")), clock), 0, "the epoch itself counts");
assert_eq!(pinned_or(env(Some(" 1791208980 ")), clock), 1_791_208_980, "spaces around it are allowed");
// The last date a document can write is honoured; past it the year would not fit
// `xsd:dateTime` and the clock answers instead.
assert_eq!(pinned_or(env(Some("253402300799")), clock), 253_402_300_799);
assert_eq!(iso_from_unix_secs(253_402_300_799), "9999-12-31T23:59:59Z");
for ignored in [
None,
Some(""),
Some(" "),
Some("-1"),
Some("later"),
Some("1791208980.5"),
Some("99999999999999999999"),
Some("253402300800"),
Some("9223372036854775807"),
] {
assert_eq!(pinned_or(env(ignored), clock), 1_000_000, "{ignored:?} leaves it to the clock");
}
// Only that variable is read.
assert_eq!(pinned_or(|name: &str| (name == "TZ").then(|| "1791208980".to_owned()), clock), 1_000_000);
// And it reaches the stamp as that instant, not as something near it.
assert_eq!(iso_from_unix_secs(pinned_or(env(Some("1791208980")), clock)), "2026-10-05T14:03:00Z");
}
/// A value that is set and still ignored is reported, so a build that meant to pin its dates
/// hears that it did not (noted in review). Unset and empty say nothing: an empty value is
/// how a CI file leaves the variable off.
#[test]
fn a_set_but_unusable_epoch_is_reported_and_nothing_else_is() {
for quiet in [None, Some(""), Some(" "), Some("0"), Some("1791208980"), Some(" 1791208980 "), Some("253402300799")] {
assert_eq!(epoch_problem(quiet), None, "{quiet:?}");
}
for loud in ["later", "-1", "1791208980.5", "1e9", "253402300800", "99999999999999999999"] {
let problem = epoch_problem(Some(loud)).unwrap_or_else(|| panic!("{loud:?} should be reported"));
assert!(problem.contains(&format!("{loud:?}")) && problem.contains("clock"), "{problem}");
}
}
}
+21 -42
View File
@@ -3,7 +3,7 @@
use serde_json::Value;
use wordcraft_doc::math_edit::MathPos;
use wordcraft_doc::para::OBJ;
use wordcraft_doc::{InlineObject, Paragraph, Path, Pos, StoryRef};
use wordcraft_doc::{InlineObject, Paragraph, Pos, StoryRef};
use wordcraft_layout::ViewMode;
use super::{parse_pos, sel_result};
@@ -53,10 +53,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("caret.set", "Set Caret", "Navigation", set)
.params(r#"{"pos": Pos, "extend"?: bool} | {"page": n, "x": pt, "y": pt}"#)
.pure(),
CommandSpec::new("select.all", "Select All", "Home › Editing › Select", select_all)
.key("Mod+A")
.params(r#"{"whole"?: bool (default true: select the whole story; false: grow through the cell, row and table first)}"#)
.pure(),
CommandSpec::new("select.all", "Select All", "Home › Editing › Select", select_all).key("Mod+A").pure(),
CommandSpec::new("select.range", "Select Range", "Navigation", select_range).params(r#"{"anchor": Pos, "focus": Pos}"#).pure(),
CommandSpec::new("select.word", "Select Word", "Navigation", select_word).pure(),
CommandSpec::new("select.sentence", "Select Sentence", "Navigation", select_sentence).pure(),
@@ -127,11 +124,10 @@ fn lr(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
}
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);
let edge = logical_edge(s, &from, is_left);
if !ext
&& !s.math_left
&& let Some(r) = into_equation(s, &from, edge, is_left, hidden)
&& let Some(r) = into_equation(s, &from, edge, is_left)
{
return r;
}
@@ -145,10 +141,10 @@ fn lr(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
/// 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, from: &Pos, edge: usize, is_left: bool, hidden: wordcraft_layout::HideDeleted) -> Option<CmdResult> {
fn into_equation(s: &mut Session, from: &Pos, edge: usize, is_left: bool) -> 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)) {
if !matches!(para.object_at(off), Some(InlineObject::Equation { .. })) || (!s.view.show_markup && para.props_of_char(off).del.is_some()) {
return None;
}
s.sel = Selection::caret(Pos { off, ..from.clone() });
@@ -186,7 +182,7 @@ fn visual_lr(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
/// 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 {
fn hidden_deletion_edge(para: &Paragraph, off: usize, is_left: 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.
@@ -201,28 +197,27 @@ fn hidden_deletion_edge(para: &Paragraph, off: usize, is_left: bool, hides: impl
})
};
let Some((i, range)) = found else { return off };
if !hides(para.runs[i].props.del) {
if para.runs[i].props.del.is_none() {
return off;
}
if is_left {
range.start - para.runs[..i].iter().rev().take_while(|run| hides(run.props.del)).map(|run| run.len).sum::<usize>()
range.start - para.runs[..i].iter().rev().take_while(|run| run.props.del.is_some()).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>()
range.end + para.runs[i + 1..].iter().take_while(|run| run.props.del.is_some()).map(|run| run.len).sum::<usize>()
}
}
fn logical_edge(s: &Session, from: &Pos, is_left: bool, hidden: wordcraft_layout::HideDeleted) -> usize {
if hidden.any()
fn logical_edge(s: &Session, from: &Pos, is_left: bool) -> usize {
if !s.view.show_markup
&& let Some(para) = s.doc.para_at(from)
{
return hidden_deletion_edge(para, from.off, is_left, |del| hidden.hides(&s.doc, del));
return hidden_deletion_edge(para, from.off, is_left);
}
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)
step_from_edge(s, from, logical_edge(s, from, is_left), is_left)
}
fn step_from_edge(s: &Session, from: &Pos, edge: usize, is_left: bool) -> Pos {
@@ -234,39 +229,23 @@ fn step_from_edge(s: &Session, from: &Pos, edge: usize, is_left: bool) -> Pos {
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 }
let neighbor = if is_left { s.doc.prev_para(from.story, &from.path) } else { s.doc.next_para(from.story, &from.path) };
let Some(path) = neighbor else { return from.clone() };
let off = if is_left { s.doc.para(from.story, &path).map_or(0, Paragraph::len) } else { 0 };
Pos { story: from.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() },
_ => step_to_neighbor(s, p, true, false),
_ => logical_step(s, p, true),
}
}
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() },
_ => step_to_neighbor(s, p, false, false),
_ => logical_step(s, p, false),
}
}
@@ -397,7 +376,7 @@ fn select_all(s: &mut Session, v: &Value) -> CmdResult {
s.column_mode = false;
return sel_result(s);
}
if !p::bool(v, "whole").unwrap_or(true)
if !p::bool(v, "whole").unwrap_or(false)
&& let Some(r) = super::table::grow_select_all(s)
{
return r;
-7
View File
@@ -521,13 +521,6 @@ 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)
}
+2 -16
View File
@@ -1,13 +1,12 @@
//! Character formatting (Home › Font).
use std::collections::HashMap;
use std::sync::{Arc, PoisonError};
use serde_json::{Value, json};
use wordcraft_doc::eq::{EncloseShape, EncloseStyle, Enclosure};
use wordcraft_doc::props::{Border, CharProps, Highlight, Rgb, TextColor, Underline, VertAlign};
use wordcraft_doc::resolve::ResolvedChar;
use wordcraft_doc::{Document, InlineObject, PartKind, Pos, RevisionKind, StoryRef};
use wordcraft_doc::{InlineObject, PartKind, Pos, RevisionKind, StoryRef};
use super::sel_result;
use super::tools::{is_turkic, lower_char, upper_char};
@@ -956,19 +955,6 @@ pub fn state(s: &Session) -> Value {
(*cached_state(s)).clone()
}
/// The common East Asian family shown by the font controls. If a slot has no face, keep
/// showing the named font. Resolve each theme slot once even for a selection with many runs.
fn selection_east_asian_font<'a>(doc: &'a Document, runs: &'a [ResolvedChar]) -> Option<&'a str> {
let mut themes = HashMap::new();
let mut fonts = runs.iter().map(|run| {
run.font_ea_theme
.and_then(|slot| *themes.entry(slot).or_insert_with(|| wordcraft_layout::para::east_asian_font(doc, run)))
.or(run.font_ea.as_deref())
});
let first = fonts.next().flatten()?;
fonts.all(|font| font == Some(first)).then_some(first)
}
fn compute_state(s: &Session) -> Value {
let all = resolved(s);
let first = all.first().cloned();
@@ -989,7 +975,7 @@ fn compute_state(s: &Session) -> Value {
json!({
"font": font,
"fontShownAs": shown_as,
"fontEastAsia": selection_east_asian_font(&s.doc, &all),
"fontEastAsia": same(&|r| json!(r.font_ea)),
"size": same(&|r| json!(r.size)),
"bold": all.iter().all(shown_bold),
"italic": all.iter().all(shown_italic),
+2 -2
View File
@@ -16,8 +16,8 @@ mod objects;
pub(crate) use header_footer::saved_copy;
use header_footer::{create_hf, edit_hf, header_footer, new_empty_headers, strip_headers};
pub use items::{
DropCapState, default_date_picture, default_time_picture, drop_cap_state, format_date, format_date_at, format_date_at_in, format_date_in,
format_date_parts, format_date_parts_in,
DropCapState, default_date_picture, drop_cap_state, format_date, format_date_at, format_date_at_in, format_date_in, format_date_parts,
format_date_parts_in,
};
use items::{cover_page, date_time, drop_cap, drop_cap_off, field, page_number, symbol};
use links::{bookmark, delete_bookmark, link, link_targets};
-34
View File
@@ -218,8 +218,6 @@ struct DateNames {
days_short: [&'static str; 7],
/// The picture of a `DATE` field without `\@`.
default: &'static str,
/// The picture of a `TIME` field without `\@`.
default_time: &'static str,
}
const ENGLISH: DateNames = DateNames {
@@ -228,7 +226,6 @@ const ENGLISH: DateNames = DateNames {
days: ["Thursday", "Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday"],
days_short: ["Thu", "Fri", "Sat", "Sun", "Mon", "Tue", "Wed"],
default: "M/d/yyyy",
default_time: "h:mm am/pm",
};
/// Portuguese (observed in Word for Mac with a pt-BR document): lower-case names, `MMM` = `out`,
@@ -239,7 +236,6 @@ const PORTUGUESE: DateNames = DateNames {
days: ["quinta-feira", "sexta-feira", "sábado", "domingo", "segunda-feira", "terça-feira", "quarta-feira"],
days_short: ["qui", "sex", "sáb", "dom", "seg", "ter", "qua"],
default: "dd/MM/yyyy",
default_time: "h:mm am/pm",
};
/// German (Word's Windows NLS forms): `MMMM` = `März`, `MMM` = `Mrz`, `ddd` = `Fr` (two
@@ -250,7 +246,6 @@ const GERMAN: DateNames = DateNames {
days: ["Donnerstag", "Freitag", "Samstag", "Sonntag", "Montag", "Dienstag", "Mittwoch"],
days_short: ["Do", "Fr", "Sa", "So", "Mo", "Di", "Mi"],
default: "dd.MM.yyyy",
default_time: "HH:mm",
};
/// Austrian Standard German: January is `Jänner`, abbreviated `Jän` (Österreichisches
@@ -261,7 +256,6 @@ const GERMAN_AUSTRIA: DateNames = DateNames {
days: ["Donnerstag", "Freitag", "Samstag", "Sonntag", "Montag", "Dienstag", "Mittwoch"],
days_short: ["Do", "Fr", "Sa", "So", "Mo", "Di", "Mi"],
default: "dd.MM.yyyy",
default_time: "HH:mm",
};
/// Choose month and weekday names from the language tag: the primary subtag picks the language,
@@ -285,12 +279,6 @@ pub fn default_date_picture(lang: Option<&str>) -> &'static str {
date_names(lang).default
}
/// The picture Word gives a `TIME` field that has no `\@` switch, in the field's language: German
/// shows the 24-hour clock (#8562).
pub fn default_time_picture(lang: Option<&str>) -> &'static str {
date_names(lang).default_time
}
/// Format a date and time with a Word picture; `days_since` (days since 1970-01-01) gives the weekday.
pub fn format_date_parts(fmt: &str, y: i64, m: usize, d: u32, hms: (u32, u32, u32), days_since: i64) -> String {
format_date_parts_in(fmt, None, y, m, d, hms, days_since)
@@ -634,28 +622,6 @@ mod date_time_locale_tests {
assert_eq!(default_date_picture(Some("de-CH")), "dd.MM.yyyy");
}
/// A `TIME` field without `\@` shows the 24-hour clock in a German document and the 12-hour
/// clock in an English one (#8562).
#[test]
fn bare_time_field_follows_the_document_language() {
let refreshed = |lang: &str| {
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("review.language", &json!({"lang": lang, "default": true})).unwrap();
s.run("insert.field", &json!({"instr": "TIME", "result": "stale"})).unwrap();
crate::cmd::references::refresh_date_fields(&mut s.doc);
let path = s.doc.para_paths(StoryRef::Body).remove(0);
let p = s.doc.para(StoryRef::Body, &path).unwrap();
let result = p.objects.iter().find_map(|o| if let InlineObject::Field { result, .. } = o { Some(result.clone()) } else { None });
result.expect("a TIME field")
};
for lang in ["de-DE", "de-AT", "de-CH"] {
let time = refreshed(lang);
assert!(time != "stale" && !time.contains("AM") && !time.contains("PM"), "{lang}: {time}");
}
let time = refreshed("en-US");
assert!(time.contains("AM") || time.contains("PM"), "en-US: {time}");
}
/// Windows NLS short forms: two-letter weekdays (`Mo`, `Di`…) and `Mrz` for March, with no
/// trailing full stop (#7146).
#[test]
+1 -1
View File
@@ -21,7 +21,7 @@ mod shape;
mod specs;
pub use arrange::moves_with_text;
pub(crate) use arrange::{anchor_paragraph, nearest_line, shifted_float_offset};
pub(crate) use arrange::{anchor_paragraph, nearest_line};
#[cfg(test)]
use group::ungroup;
pub use picture::{OriginalSize, PictureLook, cropped_original_size, fit_size, original_size};
+1 -30
View File
@@ -212,29 +212,9 @@ 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> {
@@ -265,12 +245,6 @@ 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(())
}
@@ -294,14 +268,11 @@ 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 mut o = edit_float(s, &pos, |f| {
let 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)}))
}
+10 -8
View File
@@ -520,20 +520,22 @@ fn margins(s: &mut Session, v: &Value) -> CmdResult {
None => return Err(CmdError::Params(format!("unknown preset `{x}`"))),
},
None => {
// A negative margin given counts as zero; one left out keeps its value, so an exact
// (negative) top or bottom from the file stays exact when another side changes, as
// in Word.
let c = sect(s);
let given = |k: &str| p::f32(v, k).map(|m| m.max(0.0));
(
p::f32(v, "top").unwrap_or(c.margin_top),
p::f32(v, "bottom").unwrap_or(c.margin_bottom),
p::f32(v, "left").unwrap_or(c.margin_left),
p::f32(v, "right").unwrap_or(c.margin_right),
given("top").unwrap_or(c.margin_top),
given("bottom").unwrap_or(c.margin_bottom),
given("left").unwrap_or(c.margin_left.max(0.0)),
given("right").unwrap_or(c.margin_right.max(0.0)),
)
}
};
// Negative margins count as zero before the fit check, so one can't offset another.
let (t, b, l, r) = (t.max(0.0), b.max(0.0), l.max(0.0), r.max(0.0));
let gutter = p::f32(v, "gutter").map(|g| g.max(0.0));
let cur = sect(s);
if !margins_fit((cur.page_w, cur.page_h), (t, b, l, r), gutter.unwrap_or(cur.gutter)) {
if !margins_fit((cur.page_w, cur.page_h), (t.abs(), b.abs(), l, r), gutter.unwrap_or(cur.gutter)) {
return Err(CmdError::Params("margins leave no room for text".into()));
}
// A preset picks mirrored or not, as does `mirror` (Page Setup's Multiple pages); plain numbers
@@ -588,7 +590,7 @@ fn size(s: &mut Session, v: &Value) -> CmdResult {
sections
.iter()
.find(|(e, _)| *e == block)
.is_none_or(|(_, x)| margins_fit(oriented(x), (x.margin_top, x.margin_bottom, x.margin_left, x.margin_right), x.gutter))
.is_none_or(|(_, x)| margins_fit(oriented(x), (x.margin_top.abs(), x.margin_bottom.abs(), x.margin_left, x.margin_right), x.gutter))
};
if !selected_section_ends(s).into_iter().all(fits) {
return Err(CmdError::Params(MARGINS_DONT_FIT.into()));
+23
View File
@@ -433,3 +433,26 @@ fn page_number_format_keeps_or_clears_the_start() {
assert_eq!(back["pageNumFormat"], "decimal");
assert_eq!(back["pageNumStart"], 1);
}
/// An exact (negative) top or bottom margin survives Margins and Orientation: changing another
/// margin keeps it exact, and turning the page moves its size, as a plain margin, to the side it
/// goes to.
#[test]
fn exact_margins_survive_margins_and_orientation() {
let mut s = doc();
s.doc.last_section.margin_top = -60.0;
s.doc.last_section.margin_bottom = -40.0;
s.run("layout.margins", &json!({"left": 80.0})).unwrap();
let x = &s.doc.last_section;
assert_eq!((x.margin_top, x.margin_bottom, x.margin_left), (-60.0, -40.0, 80.0));
// A negative margin given still counts as zero.
s.run("layout.margins", &json!({"top": -30.0})).unwrap();
assert_eq!((s.doc.last_section.margin_top, s.doc.last_section.margin_bottom), (0.0, -40.0));
s.doc.last_section.margin_top = -60.0;
s.run("layout.orientation", &json!({"value": "landscape"})).unwrap();
let x = &s.doc.last_section;
assert!(x.margin_left >= 0.0 && x.margin_right >= 0.0, "{x:?}");
let mut sides = [x.margin_left, x.margin_right];
sides.sort_by(f32::total_cmp);
assert_eq!(sides, [40.0, 60.0], "the exact margins' sizes go to the sides");
}
-5
View File
@@ -18,7 +18,6 @@ mod styles;
mod tabs_borders;
mod tools;
pub(super) use format::drop_direct_indents;
use format::{align, asian_typography, cur, direction, line_spacing, ls, set_align, set_props, tog};
pub use format::{cur as selection_para, fmt, indent, outdent};
pub use lists::{ListButtons, list_buttons, manage_list, touch_all};
@@ -173,11 +172,7 @@ pub fn specs() -> Vec<CommandSpec> {
let lvl = p::u64(v, "level").unwrap_or(0).min(8) as u8;
fmt(s, &|p| {
if let Some(n) = p.numbering.as_mut() {
let moved = n.level != lvl;
n.level = lvl;
if moved {
format::drop_direct_indents(p);
}
}
})
})
+2 -24
View File
@@ -163,16 +163,6 @@ pub(super) fn set_props(s: &mut Session, v: &Value) -> CmdResult {
sel_result(s)
}
/// A list item that moves to another level takes that level's indents: a direct indent (a ruler
/// drag, a pasted block, a Word file's `w:ind`) would otherwise win over them and leave the item
/// out of line with its level (#4287).
pub(in crate::cmd) fn drop_direct_indents(p: &mut ParaProps) {
p.indent_left = None;
p.indent_first = None;
p.indent_left_chars = None;
p.indent_first_chars = None;
}
pub fn indent(s: &mut Session, _: &Value) -> CmdResult {
let a = s.sel.ordered().0;
let paths = crate::cmd::selected_paths(s);
@@ -184,13 +174,7 @@ pub fn indent(s: &mut Session, _: &Value) -> CmdResult {
};
let para = s.doc.para_mut(a.story, &path)?;
match num {
Some(n) => {
let level = n.level.saturating_add(1).min(8);
para.props.numbering = Some(NumRef { num: n.num, level });
if level != n.level {
drop_direct_indents(&mut para.props);
}
}
Some(n) => para.props.numbering = Some(NumRef { num: n.num, level: n.level.saturating_add(1).min(8) }),
None => {
para.props.indent_left = Some(((left / tab).floor() + 1.0) * tab);
para.props.cancel_char_indents(true, false, false);
@@ -212,13 +196,7 @@ pub fn outdent(s: &mut Session, _: &Value) -> CmdResult {
};
let para = s.doc.para_mut(a.story, &path)?;
match num {
Some(n) => {
let level = n.level.saturating_sub(1);
para.props.numbering = Some(NumRef { num: n.num, level });
if level != n.level {
drop_direct_indents(&mut para.props);
}
}
Some(n) => para.props.numbering = Some(NumRef { num: n.num, level: n.level.saturating_sub(1) }),
None => {
para.props.indent_left = Some((((left / tab).ceil() - 1.0) * tab).max(0.0));
para.props.cancel_char_indents(true, false, false);
+1 -1
View File
@@ -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::ClipboardEmpty),
_ => Err(CmdError::Failed("the clipboard is empty".into())),
}
}
+1 -1
View File
@@ -607,7 +607,7 @@ fn created_at(stamp: &str) -> Option<(u64, i64)> {
/// Word's default date or time picture when a field instruction carries no `\@` picture switch.
fn default_picture(name: &str, lang: Option<&str>) -> String {
if name == "TIME" { crate::cmd::insert::default_time_picture(lang).into() } else { crate::cmd::insert::default_date_picture(lang).into() }
if name == "TIME" { "h:mm am/pm".into() } else { crate::cmd::insert::default_date_picture(lang).into() }
}
/// Most names SET fields give values.
const MAX_SET: usize = 10_000;
+1 -1
View File
@@ -707,7 +707,7 @@ fn a_toc_inserted_in_the_middle_of_a_document_leaves_the_caret_after_it() {
s.sel = Selection::caret(Pos { story: StoryRef::Body, path: Path::top(1), off: 0 });
s.run("references.toc", &json!({"levels": 2})).unwrap();
let (start, end) = toc_range(&s).unwrap();
assert_eq!(start, 1, "the TOC must immediately follow Intro without an extra blank paragraph");
assert!(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,
-2
View File
@@ -439,8 +439,6 @@ pub(super) fn insert_toc(s: &mut Session, v: &Value) -> CmdResult {
s.doc.remove_block(StoryRef::Body, &at.path)?;
}
at.path.last()
} else if at.off == 0 {
at.path.last()
} else {
s.doc.split_paragraph(&at)?.path.last()
};
+11 -3
View File
@@ -19,8 +19,10 @@ pub use changes::{
DELETION_TEXT_CHARS, DeletionBalloon, deletion_balloons, format_changes, has_deletions, has_format_changes, move_changes, tracking_json,
};
use changes::{list_changes, nav_change, resolve_all_then, resolve_sel_then, tracking_options};
use comments::{
comment_at_caret, comments_change, delete_comment, edit_comment, list_comments, nav_comment, new_comment, reply, validate_comment_id,
};
pub use comments::{comment_list, comment_range_at_caret};
use comments::{comments_change, delete_comment, edit_comment, list_comments, nav_comment, new_comment, reply, resolve_comment};
use proofing::{all_issues, issue_at, next_issue, suggestions, thesaurus, word_count};
pub fn specs() -> Vec<CommandSpec> {
@@ -35,8 +37,14 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("review.deleteComment", "Delete", "Review › Comments", delete_comment).params(
r#"{"id"?: non-negative 32-bit JSON integer (omit to use the caret), "all"?: bool (every comment), "resolved"?: bool (every resolved comment, with its replies; wins over all)}"#,
),
CommandSpec::new("review.resolveComment", "Resolve", "Review › Comments", resolve_comment)
.params(r#"{"id"?: non-negative 32-bit JSON integer (a comment or reply; omit to use the caret), "value"?: bool (omit to toggle the whole thread)}"#),
CommandSpec::new("review.resolveComment", "Resolve", "Review › Comments", |s, v| {
validate_comment_id(v)?;
let id = p::u64(v, "id").map(|x| x as u32).or_else(|| comment_at_caret(s)).ok_or_else(|| CmdError::Params("`id` required".into()))?;
let c = s.doc.comments.get_mut(&id).ok_or_else(|| CmdError::Params("no such comment".into()))?;
c.resolved = p::bool(v, "value").unwrap_or(!c.resolved);
sel_result(s)
})
.params(r#"{"id"?: non-negative 32-bit JSON integer (omit to use the caret), "value"?: bool (omit to toggle)}"#),
CommandSpec::new("review.nextComment", "Next", "Review › Comments", |s, _| nav_comment(s, 1)).pure(),
CommandSpec::new("review.previousComment", "Previous", "Review › Comments", |s, _| nav_comment(s, -1)).pure(),
CommandSpec::new("review.comments", "Show Comments", "Review › Comments", list_comments).pure(),
+9 -59
View File
@@ -26,8 +26,7 @@ fn resolve_runs(para: &mut wordcraft_doc::Paragraph, from: usize, to: usize, pro
}
/// Accept or reject a revision range in one paragraph; `mark` includes its paragraph mark (and
/// the section break on it), `props` the paragraph's own formatting change. If the next
/// paragraph moves into this path, return how many bytes of this paragraph precede it.
/// the section break on it), `props` the paragraph's own formatting change.
fn resolve_para(
s: &mut Session,
story: StoryRef,
@@ -35,11 +34,11 @@ fn resolve_para(
(from, to): (usize, usize),
(mark, props): (bool, bool),
accept: bool,
) -> Result<Option<usize>, CmdError> {
) -> Result<(), CmdError> {
let para = s.doc.para_mut(story, path)?;
resolve_runs(para, from, to, props, accept)?;
if !mark {
return Ok(None);
return Ok(());
}
if para.mark.fmt_change.is_some() || para.section.as_ref().is_some_and(|x| x.fmt_change.is_some()) {
fmt_revisions::resolve_char(&mut para.mark, accept);
@@ -50,9 +49,8 @@ fn resolve_para(
}
let (ins, del) = (para.mark.ins, para.mark.del);
if ins.is_none() && del.is_none() {
return Ok(None);
return Ok(());
}
let prefix_len = para.len();
// An inserted paragraph mark that is rejected, or a deleted one that is accepted, goes away:
// the next paragraph joins this one (the split is undone). A paragraph left empty goes away
// whole, so the next one keeps its own style and numbering, as in Word. The end mark of a
@@ -68,18 +66,15 @@ fn resolve_para(
if sectioned {
s.doc.remove_section_break(path.last());
}
if crate::cmd::remove_empty_para(s, story, path)? {
return Ok(Some(0));
}
if crate::cmd::join_next_para(s, story, path)? {
return Ok(Some(prefix_len));
if crate::cmd::remove_empty_para(s, story, path)? || crate::cmd::join_next_para(s, story, path)? {
return Ok(());
}
}
let para = s.doc.para_mut(story, path)?;
para.mark.ins = None;
para.mark.del = None;
para.touch();
Ok(None)
Ok(())
}
/// Remove the whole paragraph at `path` when a whole-paragraph revision on its mark resolved to
@@ -264,49 +259,7 @@ fn resolve_loose_blocks(blocks: &mut wordcraft_doc::Blocks, accept: bool) -> Res
Ok(())
}
/// Byte offset after resolving the runs in the endpoint's original paragraph. Only apply it
/// when paragraph removal or joining also moves the endpoint.
fn resolved_offset(s: &Session, end: &Pos, accept: bool) -> usize {
let Some(para) = s.doc.para_at(end) else { return end.off };
let removed: usize = para
.run_ranges()
.filter(|(_, c)| if accept { c.del.is_some() } else { c.ins.is_some() })
.map(|(range, _)| end.off.min(range.end).saturating_sub(range.start))
.sum();
end.off - removed
}
/// The next paragraph has moved into `path` (empty removal) or been appended to its surviving
/// prefix (join). Later siblings, including a table containing an endpoint, shift one block back.
fn remap_after_middle_paragraph(s: &mut Session, story: StoryRef, path: &wordcraft_doc::Path, prefix_len: usize, offsets: &mut [usize; 2]) {
let depth = path.parent().len();
for (end, offset) in [&mut s.sel.anchor, &mut s.sel.focus].into_iter().zip(offsets) {
if end.story != story || !end.path.0.starts_with(path.parent()) {
continue;
}
let Some(&block) = end.path.0.get(depth) else { continue };
if block as usize > path.last() {
let mut dest = end.path.clone();
dest.0[depth] -= 1;
// An endpoint in a terminal paragraph removed earlier still uses terminal clamping.
if s.doc.para(story, &dest).is_none() {
continue;
}
if &dest == path {
*offset = offset.saturating_add(prefix_len);
}
end.path = dest;
} else if &end.path == path {
*offset = (*offset).min(prefix_len);
} else {
continue;
}
end.off = *offset;
}
}
fn resolve_all(s: &mut Session, accept: bool) -> CmdResult {
let mut offsets = [&s.sel.anchor, &s.sel.focus].map(|end| resolved_offset(s, end, accept));
let stories: Vec<StoryRef> = std::iter::once(StoryRef::Body).chain(s.doc.parts.keys().map(|k| StoryRef::Part(*k))).collect();
for st in stories {
for path in s.doc.para_paths(st).into_iter().rev() {
@@ -316,7 +269,7 @@ fn resolve_all(s: &mut Session, accept: bool) -> CmdResult {
let is_last = s.doc.block(st, &path.with_last(path.last().saturating_add(1))).is_none();
let trailing = is_last && s.doc.para(st, &path).is_some_and(|p| (p.mark.del.is_some() && accept) || (p.mark.ins.is_some() && !accept));
let len = s.doc.para(st, &path).map(|p| p.len()).unwrap_or(0);
let prefix_len = resolve_para(s, st, &path, (0, len), (true, true), accept)?;
resolve_para(s, st, &path, (0, len), (true, true), accept)?;
if trailing && remove_trailing_para(s, st, &path)? {
// Selection ends in the removed paragraph go to the end of the one before it;
// clamping later would keep their offsets in that paragraph's text (#8500).
@@ -326,9 +279,6 @@ fn resolve_all(s: &mut Session, accept: bool) -> CmdResult {
}
}
}
if let Some(prefix_len) = prefix_len {
remap_after_middle_paragraph(s, st, &path, prefix_len, &mut offsets);
}
}
}
// Tables, rows, cells, sections and style definitions.
@@ -1013,7 +963,7 @@ fn resolve_sel(s: &mut Session, accept: bool, next: bool) -> CmdResult {
// A paragraph's mark is in the selection when the selection goes on past it.
let mark = path != b.path || caret_mark.as_ref() == Some(&path);
let props = (ranged && (path != b.path || to > from)) || caret_props.as_ref() == Some(&path);
let _ = resolve_para(s, a.story, &path, (from, to), (mark, props), accept)?;
resolve_para(s, a.story, &path, (from, to), (mark, props), accept)?;
if ranged {
resolve_cell(s, a.story, &path, accept)?;
}
-23
View File
@@ -186,29 +186,6 @@ fn threads_of(s: &Session, roots: impl IntoIterator<Item = u32>) -> Vec<u32> {
ids
}
/// Resolve or reopen the whole discussion, even when the target is a reply. A toggle uses
/// the target's state, matching its Resolve/Reopen button even in a mixed-state file.
pub(super) fn resolve_comment(s: &mut Session, v: &Value) -> CmdResult {
validate_comment_id(v)?;
let id = p::u64(v, "id").map(|x| x as u32).or_else(|| comment_at_caret(s)).ok_or_else(|| CmdError::Params("`id` required".into()))?;
let c = s.doc.comments.get(&id).ok_or_else(|| CmdError::Params("no such comment".into()))?;
let resolved = p::bool(v, "value").unwrap_or(!c.resolved);
let mut root = id;
let mut seen = BTreeSet::new();
while seen.insert(root) {
match s.doc.comments.get(&root).and_then(|c| c.parent).filter(|p| s.doc.comments.contains_key(p)) {
Some(parent) => root = parent,
None => break,
}
}
for id in threads_of(s, [root]) {
if let Some(c) = s.doc.comments.get_mut(&id) {
c.resolved = resolved;
}
}
sel_result(s)
}
pub(super) fn delete_comment(s: &mut Session, v: &Value) -> CmdResult {
validate_comment_id(v)?;
let ids: Vec<u32> = if p::bool(v, "resolved").unwrap_or(false) {
+1 -141
View File
@@ -311,7 +311,7 @@ fn comment_range_at_caret_needs_the_caret_inside_the_range() {
assert_eq!(super::comment_range_at_caret(&s), Some(id), "inside the commented text");
s.run("select.text", &json!({"text": "three"})).unwrap();
assert_eq!(super::comment_range_at_caret(&s), None, "elsewhere in the paragraph");
assert_eq!(super::comments::comment_at_caret(&s), Some(id), "the older lookup still falls back to the paragraph's comment");
assert_eq!(super::comment_at_caret(&s), Some(id), "the older lookup still falls back to the paragraph's comment");
}
fn glyph_text(d: &[Draw]) -> String {
@@ -491,81 +491,6 @@ 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()
}
@@ -1000,71 +925,6 @@ fn deleting_a_comment_deletes_replies_to_replies() {
assert_eq!(anchors(&s).len(), 2);
}
/// Resolving from the root, the caret or a nested reply changes the whole discussion in one
/// undo step. Reopening is also thread-wide, and unrelated discussions stay untouched.
#[test]
fn resolving_a_comment_changes_its_whole_thread() {
let mut s = Session::new(Document::from_text("first second"));
s.run("select.text", &json!({"text": "first"})).unwrap();
let root = s.run("review.newComment", &json!({"text": "root"})).unwrap()["id"].as_u64().unwrap();
let reply = s.run("review.reply", &json!({"id": root, "text": "reply"})).unwrap()["id"].as_u64().unwrap();
let nested = s.run("review.reply", &json!({"id": reply, "text": "nested"})).unwrap()["id"].as_u64().unwrap();
s.run("review.reply", &json!({"id": root, "text": "sibling"})).unwrap();
s.run("select.text", &json!({"text": "second"})).unwrap();
let other = s.run("review.newComment", &json!({"text": "other"})).unwrap()["id"].as_u64().unwrap() as u32;
s.run("select.text", &json!({"text": "first"})).unwrap();
let before = s.doc.comments.clone();
let body = s.doc.body.clone();
let parts = s.doc.parts.clone();
let depth = s.undo_depth();
let mut resolved = before.clone();
for (id, c) in &mut resolved {
c.resolved = *id != other;
}
for params in [json!({"id": root, "value": true}), json!({}), json!({"id": nested})] {
s.run("review.resolveComment", &params).unwrap();
assert_eq!(s.doc.comments, resolved, "{params}: all replies resolve, not the other discussion");
assert_eq!(s.undo_depth(), depth + 1, "one undo step for the whole thread");
s.run("review.resolveComment", &json!({"id": reply, "value": true})).unwrap();
assert_eq!(s.undo_depth(), depth + 1, "resolving an already resolved thread adds no step");
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc.comments, before, "one undo restores every comment");
s.run("edit.redo", &json!({})).unwrap();
assert_eq!(s.doc.comments, resolved);
s.run("review.resolveComment", &json!({"id": nested})).unwrap();
assert_eq!(s.doc.comments, before, "toggling a reply reopens the whole thread");
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc.comments, resolved);
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc.comments, before);
}
assert_eq!(s.doc.body, body, "resolution leaves the body and anchors alone");
assert_eq!(s.doc.parts, parts, "resolution leaves the comments' text alone");
}
/// Imported comments can have mixed resolved flags, missing parents or a parent cycle. A
/// thread operation reconciles the connected comments without following a missing parent.
#[test]
fn resolving_a_comment_handles_mixed_state_and_broken_parent_links() {
use wordcraft_doc::Comment;
for parent in [None, Some(99), Some(2)] {
let mut doc = Document::new();
doc.comments.insert(0, Comment { resolved: true, parent, ..Default::default() });
doc.comments.insert(1, Comment { parent: Some(0), ..Default::default() });
doc.comments.insert(2, Comment { parent: Some(1), ..Default::default() });
doc.comments.insert(3, Comment { parent: Some(99), ..Default::default() });
let mut s = Session::new(doc);
s.run("review.resolveComment", &json!({"id": 2})).unwrap();
assert!(
s.doc.comments.iter().all(|(id, c)| c.resolved == (*id != 3)),
"a reply's Resolve action must not reopen its resolved parent: {parent:?}"
);
s.run("review.resolveComment", &json!({"id": 1, "value": false})).unwrap();
assert!(s.doc.comments.values().all(|c| !c.resolved), "{parent:?}");
}
}
/// A parent cycle (possible in a hostile file) doesn't hang Delete; both comments go.
#[test]
fn deleting_a_comment_in_a_parent_cycle_ends() {
+1 -1
View File
@@ -1,7 +1,7 @@
use super::cells::{cell, cell_at, grid_cols, row_ends, selected_cells};
use super::{CmdError, CmdResult, Paragraph, Path, Pos, Selection, Session, StoryRef, Value, sel_result};
/// Explicit staged select-all in a table: the cell, then its row, then the table. A nested table that
/// Ctrl+A in a table, as in Word: the cell, then its row, then the table. A nested table that
/// is already fully selected grows to the cell around it. Returns `None` when the next step is
/// the whole story (not in a table, or the top-level table is already selected).
pub(crate) fn grow_select_all(s: &mut Session) -> Option<CmdResult> {
+4 -4
View File
@@ -630,10 +630,10 @@ fn room_right(l: &DocLayout, doc: &Document, page: usize, target: &ResizeTarget)
let Some(b) = boxes.iter().find(|b| b.story == target.story && b.table == outer && b.row == row && b.cell == cell) else {
return margin;
};
// A cell's right margin is on its right in a right-to-left table too, as the layout draws
// it (#6941): Word doesn't mirror cell margins.
let right_margin = wordcraft_layout::cell_margins(doc, t, row, cell)[3];
(b.rect.right() - right_margin).min(margin)
// A right-to-left table has its cells' start (left) margin on their right.
let m = wordcraft_layout::cell_margins(doc, t, row, cell);
let inset = if t.props.bidi_visual { m[1] } else { m[3] };
(b.rect.right() - inset).min(margin)
}
#[cfg(test)]
@@ -534,46 +534,6 @@ fn a_nested_tables_column_fits_within_its_cell() {
assert_eq!((host1.x, host1.w), (host.x, host.w), "the table around it keeps its columns");
}
/// #8441: a right-to-left table keeps its cells' right margins on their right (#6941), so a
/// nested table in such a cell fits up to that cell's right margin, not its left one, when the
/// two differ.
#[test]
fn a_nested_tables_column_fits_within_a_right_to_left_cell() {
let mut s = rtl_table_session(1, 2);
s.sel = Selection::caret(cell_pos(&s, 0, 0));
s.run("insert.table", &json!({"rows": 1, "cols": 2})).unwrap();
let (inner, _, _) = s.sel.focus.path.cell().unwrap();
let outer = table_path(&s);
// A left margin of 20 pt and a right one of 2 pt; the nested table itself left to right.
s.doc.table_mut(StoryRef::Body, &outer).unwrap().rows[0].cells[0].props.margins = Some([0.0, 20.0, 0.0, 2.0]);
s.doc.table_mut(StoryRef::Body, &inner).unwrap().props.bidi_visual = false;
s.touch();
let rect = |s: &mut Session, table: &Path, cell: usize| {
s.layout().pages[0]
.items
.iter()
.find_map(|it| match it {
Placed::Cell { rect, table: t, row: 0, cell: c, .. } if t == table && *c == cell => Some(*rect),
_ => None,
})
.unwrap()
};
for col in [1, 0] {
let r = rect(&mut s, &inner, col);
s.run("table.fitColumn", &json!({"page": 0, "x": r.right(), "y": mid_y(r)})).unwrap();
}
s.run("text.insert", &json!({"text": "word ".repeat(40)})).unwrap();
let host = rect(&mut s, &outer, 0);
let (a, b) = (rect(&mut s, &inner, 0), rect(&mut s, &inner, 1));
assert!(b.right() < host.right() - 40.0, "{b:?} in {host:?}");
s.run("table.fitColumn", &json!({"page": 0, "x": a.right(), "y": mid_y(a)})).unwrap();
let b1 = rect(&mut s, &inner, 1);
let text_right = host.right() - 2.0;
assert!((b1.right() - text_right).abs() < 0.5, "the table fills its cell's text up to its right margin: {b1:?}, {text_right}");
let host1 = rect(&mut s, &outer, 0);
assert_eq!((host1.x, host1.w), (host.x, host.w), "the table around it keeps its columns");
}
/// Pasting formatting onto a selected column leaves its text (it used to clear it).
#[test]
fn the_format_painter_keeps_a_selected_columns_text() {
+3 -15
View File
@@ -206,11 +206,7 @@ pub(super) fn tab(s: &mut Session, _: &Value) -> CmdResult {
&& n.num != 0
{
let para = s.doc.para_mut(f.story, &f.path)?;
let level = n.level.saturating_add(1).min(8);
para.props.numbering = Some(NumRef { num: n.num, level });
if level != n.level {
crate::cmd::para::drop_direct_indents(&mut para.props);
}
para.props.numbering = Some(NumRef { num: n.num, level: n.level.saturating_add(1).min(8) });
para.touch();
return sel_result(s);
}
@@ -259,11 +255,7 @@ fn indent_by_tab(s: &mut Session, f: &Pos) -> CmdResult {
&& let Some(n) = r.numbering.filter(|n| n.num != 0)
{
let p = s.doc.para_mut(f.story, &f.path)?;
let level = n.level.saturating_add(1).min(8);
p.props.numbering = Some(NumRef { num: n.num, level });
if level != n.level {
crate::cmd::para::drop_direct_indents(&mut p.props);
}
p.props.numbering = Some(NumRef { num: n.num, level: n.level.saturating_add(1).min(8) });
p.touch();
return sel_result(s);
}
@@ -296,11 +288,7 @@ pub(super) fn back_tab(s: &mut Session, _: &Value) -> CmdResult {
let f = s.sel.focus.clone();
if let Some(n) = s.doc.para_at(&f).and_then(|x| x.props.numbering).filter(|n| n.num != 0) {
let para = s.doc.para_mut(f.story, &f.path)?;
let level = n.level.saturating_sub(1);
para.props.numbering = Some(NumRef { num: n.num, level });
if level != n.level {
crate::cmd::para::drop_direct_indents(&mut para.props);
}
para.props.numbering = Some(NumRef { num: n.num, level: n.level.saturating_sub(1) });
para.touch();
return sel_result(s);
}
+9 -20
View File
@@ -260,12 +260,12 @@ fn diff_notes(
}
for &new_id in &notes.inserted {
if let Some(part) = doc.parts.get_mut(&new_id) {
part.blocks = part.blocks.iter().map(|b| Arc::new(mark_block(b, &|c| c.ins = Some(ctx.ins), &|_| {}))).collect();
part.blocks = part.blocks.iter().map(|b| Arc::new(mark_block(b, &|c| c.ins = Some(ctx.ins)))).collect();
}
}
for &orig_id in &notes.deleted {
if let Some(part) = doc.parts.get_mut(&orig_id) {
part.blocks = part.blocks.iter().map(|b| Arc::new(mark_block(b, &|c| c.del = Some(ctx.del), &|_| {}))).collect();
part.blocks = part.blocks.iter().map(|b| Arc::new(mark_block(b, &|c| c.del = Some(ctx.del)))).collect();
}
}
}
@@ -443,18 +443,14 @@ fn diff_blocks(doc: &mut Document, old: &[Arc<Block>], new: &[Arc<Block>], ctx:
(Some(Block::Para(pa)), Some(Block::Para(pb))) => out.push(para_block(word_diff(doc, pa, pb, ctx))),
_ => {
if let Some(x) = a {
out.push(Arc::new(mark_block(
x,
&|c| {
// An existing deletion is another author's: keep their revision
// stamp instead of re-attributing the paragraph to this compare.
c.del.get_or_insert(ctx.del);
},
&|_| {},
)));
out.push(Arc::new(mark_block(x, &|c| {
// An existing deletion is another author's: keep their revision
// stamp instead of re-attributing the paragraph to this compare.
c.del.get_or_insert(ctx.del);
})));
}
if let Some(x) = b {
out.push(Arc::new(mark_block(x, &|c| c.ins = Some(ctx.ins), &|c| c.del = None)));
out.push(Arc::new(mark_block(x, &|c| c.ins = Some(ctx.ins))));
}
}
}
@@ -1631,13 +1627,7 @@ fn block_text(b: &Block, depth: usize) -> String {
/// where the paragraph carries a section break or is the container's only paragraph. A
/// non-terminal section-carrying paragraph is removed whole too: `resolve_para` removes the
/// section break first (#5734, issue #5667), so the following paragraph keeps its own properties.
///
/// `mark` additionally updates each paragraph mark. A whole inserted block keeps only the
/// compare's insertion on its mark: a `del` the revised document's mark already carried (a pending
/// deletion by another author) must not survive next to the compare's `ins` — on accept the
/// deletion branch would resolve the inserted paragraph away (#6899). Run-level revisions of the
/// source block are left alone.
fn mark_block(b: &Block, f: &dyn Fn(&mut CharProps), mark: &dyn Fn(&mut CharProps)) -> Block {
fn mark_block(b: &Block, f: &dyn Fn(&mut CharProps)) -> Block {
let mut out = b.clone();
let mut todo = vec![&mut out];
while let Some(blk) = todo.pop() {
@@ -1646,7 +1636,6 @@ fn mark_block(b: &Block, f: &dyn Fn(&mut CharProps), mark: &dyn Fn(&mut CharProp
let len = p.len();
let _ = p.format(0, len, f);
f(&mut p.mark);
mark(&mut p.mark);
p.touch();
}
Block::Table(t) => {
+62 -199
View File
@@ -16,103 +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 resolving_a_middle_paragraph_keeps_the_caret_with_its_text() {
for (original, revised, command) in [("A\nB\nC", "A\nNEW\nB\nC", "review.rejectAll"), ("A\nOLD\nB\nC", "A\nB\nC", "review.acceptAll")] {
let mut s = Session::new(Document::from_text(original));
s.run("review.compare", &json!({"text": revised})).unwrap();
s.sel = Selection::caret(Pos::body(2, 1));
s.run(command, &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB\nC");
assert!(s.sel.is_collapsed());
assert_eq!(s.sel.focus, Pos::body(1, 1), "{command} keeps the caret after B");
s.run("text.insert", &json!({"text": "!"})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB!\nC");
}
}
#[test]
fn accepting_a_middle_paragraph_join_keeps_the_backward_selection() {
let mut s = Session::new(Document::from_text("A\néDROP\nX🙂B\nC"));
s.run("review.trackChanges", &json!({"value": true})).unwrap();
s.sel = Selection { anchor: Pos::body(1, "é".len()), focus: Pos::body(2, "X".len()) };
s.run("text.delete", &json!({})).unwrap();
s.sel = Selection { anchor: Pos::body(2, "X🙂".len()), focus: Pos::body(1, 0) };
s.run("review.acceptAll", &json!({"stopTracking": true})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\né🙂B\nC");
assert_eq!(s.sel.anchor, Pos::body(1, "é🙂".len()));
assert_eq!(s.sel.focus, Pos::body(1, 0));
s.run("text.insert", &json!({"text": "Q"})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nQB\nC");
}
#[test]
fn compare_marks_an_empty_paragraphs_mark() {
// An empty inserted paragraph is stamped on its mark, though `format` skips its empty range.
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
@@ -1776,43 +1679,6 @@ fn compare_lcs_window_move_past_cap_does_not_cascade_false_revisions() {
assert_eq!(s.doc.plain_text(StoryRef::Body), revised);
}
fn assert_whole_block_mark_compare(from: &str, to: &str, expected_mid: &str, is_del: bool, preserve_bold: bool) {
let expected_empty = |text: &str| text.split('\n').filter(|line| line.is_empty()).count();
let from_len = from.split('\n').count();
let to_len = to.split('\n').count();
let mut s = Session::new(Document::from_text(from));
if preserve_bold && let Some(Block::Para(p)) = s.doc.body.get_mut(1).map(Arc::make_mut) {
p.mark.bold = Some(true);
}
s.run("review.compare", &json!({"text": to})).unwrap();
assert_eq!(s.doc.body.len(), 3);
let mid = s.doc.body[1].as_para().expect("block 1 must be paragraph");
assert_eq!(mid.plain_text(), expected_mid);
if expected_mid.is_empty() {
assert_eq!(mid.len(), 0);
}
if is_del {
assert!(mid.mark.del.is_some(), "whole-block delete must record revision on paragraph mark");
} else {
assert!(mid.mark.ins.is_some(), "whole-block insert must record revision on paragraph mark");
}
if preserve_bold {
assert_eq!(mid.mark.bold, Some(true), "paragraph mark formatting must be preserved on deleted block");
}
let mut s_rej = Session::new(s.doc.clone());
s_rej.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s_rej.doc.plain_text(StoryRef::Body), from);
assert_eq!(s_rej.doc.body.len(), from_len);
assert_eq!(empty_paras(&s_rej), expected_empty(from), "rejecting a whole-block revision changed empty paragraph count");
s.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), to);
assert_eq!(s.doc.body.len(), to_len);
assert_eq!(empty_paras(&s), expected_empty(to), "accepting a whole-block revision changed empty paragraph count");
}
/// Verifies that `mark_block` records paragraph mark revisions on whole-block deletions,
/// whole-block insertions, empty paragraphs, and ensures clean resolution via `review.acceptAll`
/// and `review.rejectAll`.
@@ -1821,78 +1687,75 @@ fn compare_mark_block_records_paragraph_mark_revisions_on_whole_block_changes()
// Whole block delete/insert: test with differing paragraph count so whole-block paths trigger
let orig_multi = "Keep start.\nDelete me.\nKeep end.";
let rev_multi = "Keep start.\nKeep end.";
assert_whole_block_mark_compare(orig_multi, rev_multi, "Delete me.", true, true);
assert_whole_block_mark_compare(rev_multi, orig_multi, "Delete me.", false, false);
let mut s2 = Session::new(Document::from_text(orig_multi));
if let Some(Block::Para(p)) = s2.doc.body.get_mut(1).map(Arc::make_mut) {
p.mark.bold = Some(true);
}
s2.run("review.compare", &json!({"text": rev_multi})).unwrap();
// In s2.doc.body, block 1 was deleted whole.
// Verify that p.mark.del is recorded by mark_block and formatting is preserved.
let del_para = s2.doc.body[1].as_para().expect("block 1 must be paragraph");
assert!(del_para.mark.del.is_some(), "whole-block delete must record revision on paragraph mark");
assert_eq!(del_para.mark.bold, Some(true), "paragraph mark formatting must be preserved on deleted block");
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.";
let rev_empty = "Before.\nAfter.";
assert_whole_block_mark_compare(orig_empty, rev_empty, "", true, false);
assert_whole_block_mark_compare(rev_empty, orig_empty, "", false, false);
}
let mut s4 = Session::new(Document::from_text(orig_empty));
s4.run("review.compare", &json!({"text": rev_empty})).unwrap();
let empty_del = s4.doc.body[1].as_para().expect("empty paragraph block");
assert_eq!(empty_del.len(), 0);
assert!(empty_del.mark.del.is_some(), "empty paragraph deletion must set mark.del");
s4.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s4.doc.plain_text(StoryRef::Body), rev_empty);
assert_eq!(s4.doc.body.len(), 2);
assert_eq!(empty_paras(&s4), 0, "accepting an empty deleted paragraph left it behind");
/// Issue #6899: when the revised document's paragraph mark already carries another author's
/// pending deletion, a whole-paragraph insertion by compare must not leave the mark with both
/// `ins` and `del` — on accept the deletion branch would remove the inserted paragraph (or join
/// it away), losing the inserted break. The revised clone's mark keeps only the compare's `ins`.
#[test]
fn compare_inserted_paragraph_mark_drops_a_foreign_del() {
use wordcraft_doc::{Revision, RevisionKind};
let mut rev = Document::from_text("Keep start.\nNew line.\nKeep end.");
rev.revisions.push(Revision { kind: RevisionKind::Delete, author: "Other".into(), date: String::new(), date_utc: None, move_name: None });
if let Some(Block::Para(p)) = rev.body.get_mut(1).map(Arc::make_mut) {
p.mark.del = Some(0);
}
let path = std::env::temp_dir().join(format!("wc-compare-6899-{}.docx", std::process::id()));
crate::io::save_path(&path, &rev).unwrap();
let check = crate::io::open_path(&path).unwrap();
assert!(check.body[1].as_para().unwrap().mark.del.is_some(), "the foreign del must survive the docx round-trip, or this test proves nothing");
let mut 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 s = Session::new(Document::from_text("Keep start.\nKeep end."));
s.run("review.compare", &json!({"path": path.to_string_lossy()})).unwrap();
let _ = std::fs::remove_file(&path);
let ins = s.doc.body[1].as_para().expect("block 1 is the inserted paragraph");
assert!(ins.mark.ins.is_some(), "compare marks the whole inserted paragraph's mark");
assert!(ins.mark.del.is_none(), "the foreign del does not sit next to the compare's ins");
// Accepting keeps the inserted paragraph break: the text reads as the revised document's.
s.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "Keep start.\nNew line.\nKeep end.");
}
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");
/// Issue #6899, inside a table: `mark_block` recurses into cells, so a paragraph mark there gets
/// the same treatment — a foreign `del` does not sit next to the compare's `ins`.
#[test]
fn compare_inserted_table_cell_paragraph_mark_drops_a_foreign_del() {
use wordcraft_doc::{Revision, RevisionKind, Table};
let mut rev = Document::from_text("Keep start.\nKeep end.");
rev.revisions.push(Revision { kind: RevisionKind::Delete, author: "Other".into(), date: String::new(), date_utc: None, move_name: None });
let mut t = Table::new(1, 1, 200.0);
if let Some(c) = t.rows.first_mut().and_then(|r| r.cells.first_mut())
&& let Some(Block::Para(p)) = c.blocks.first_mut().map(Arc::make_mut)
{
p.mark.del = Some(0);
}
rev.body.insert(1, Arc::new(Block::Table(t)));
let path = std::env::temp_dir().join(format!("wc-compare-6899-table-{}.docx", std::process::id()));
crate::io::save_path(&path, &rev).unwrap();
let check = crate::io::open_path(&path).unwrap();
let cell_marked = check.body.iter().any(|b| match &**b {
Block::Table(t) => {
t.rows.iter().flat_map(|r| r.cells.iter()).flat_map(|c| c.blocks.iter()).any(|b| b.as_para().is_some_and(|p| p.mark.del.is_some()))
}
_ => false,
});
assert!(cell_marked, "the cell paragraph's foreign del must survive the docx round-trip, or this test proves nothing");
let mut s = Session::new(Document::from_text("Keep start.\nKeep end."));
s.run("review.compare", &json!({"path": path.to_string_lossy()})).unwrap();
let _ = std::fs::remove_file(&path);
let Some(Block::Table(t)) = s.doc.body.get(1).map(|b| &**b) else { panic!("block 1 is the inserted table") };
let cell_para = t.rows[0].cells[0].blocks[0].as_para().expect("the cell paragraph");
assert!(cell_para.mark.ins.is_some(), "compare marks the inserted cell paragraph's mark");
assert!(cell_para.mark.del.is_none(), "the foreign del does not sit next to the compare's ins");
s.run("review.acceptAll", &json!({})).unwrap();
assert!(matches!(s.doc.body.get(1).map(|b| &**b), Some(Block::Table(_))), "accepting keeps the inserted table");
s5.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s5.doc.plain_text(StoryRef::Body), orig_empty);
assert_eq!(s5.doc.body.len(), 3);
}
#[test]
+1 -1
View File
@@ -509,7 +509,7 @@ pub fn open_path_in(path: &std::path::Path, password: Option<&str>, region: &wor
/// Largest document file opened by path.
#[cfg(not(target_arch = "wasm32"))]
const MAX_DOCUMENT: u64 = 2u64 << 30;
const MAX_DOCUMENT: u64 = 2 << 30;
/// The bytes of the document at `path`, read as `file.open` reads a path: inside the automation
/// read root, and only a regular file of at most 2 GB. A named pipe would block the open and a
+1 -18
View File
@@ -92,7 +92,7 @@ pub fn save(ext: &str, doc: &Document, opts: &crate::io::ExportOptions) -> Optio
// Output shows the fields Word fills in as it prints (see `output_fields`).
let out = crate::cmd::references::output_fields(doc);
let doc = out.as_ref().unwrap_or(doc);
Some(crate::strict::export_pdf(&pdf_document(doc), opts))
Some(crate::strict::export_pdf(doc, opts))
}
other => wordcraft_formats::export_with(other, doc, &wordcraft_formats::ExportOptions { comments: opts.markup && opts.comments }),
}
@@ -142,23 +142,6 @@ pub fn render_png(doc: &Document, page: usize, scale: f32, opts: &crate::io::Exp
Ok(img.to_png())
}
/// Supply an absent or unreadable PDF creation date without changing the document or advancing
/// its revision. This covers direct exports and web downloads, which do not pass through
/// `stamp_save`.
///
/// Unreadable, not only absent: the DOCX reader takes `core.created` as it finds it, so a file can
/// arrive carrying something like `not-a-date`. The PDF writer cannot put that in a document and
/// falls back to the clock, which is the one thing a pinned date is meant to stop -- so the
/// question asked here is the writer's own (`reads_as_date`), not whether the string is empty
/// (noted in review).
pub(crate) fn pdf_document(doc: &Document) -> std::borrow::Cow<'_, Document> {
let mut output = std::borrow::Cow::Borrowed(doc);
if !wordcraft_pdf::reads_as_date(&doc.core.created) {
output.to_mut().core.created = crate::cmd::saved_iso();
}
output
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
-2
View File
@@ -84,8 +84,6 @@ pub enum CmdError {
Params(String),
#[error("not available: {0}")]
Disabled(String),
#[error("the clipboard is empty")]
ClipboardEmpty,
#[error("{0}")]
Failed(String),
}
+1 -1
View File
@@ -243,7 +243,7 @@ impl Session {
compress: p::bool(v, "compress").unwrap_or(true),
..Default::default()
};
let bytes = wordcraft_pdf::export_layout(&crate::io_ext::pdf_document(doc), &lay, &opts).map_err(|e| CmdError::Failed(e.to_string()))?;
let bytes = wordcraft_pdf::export_layout(doc, &lay, &opts).map_err(|e| CmdError::Failed(e.to_string()))?;
Ok((bytes, plan))
}
}
+1 -1
View File
@@ -106,7 +106,7 @@ impl Session {
pub fn stamp_save(&mut self) {
self.doc.settings.zoom = crate::cmd::view::saved_zoom(&self.view);
let core = &mut self.doc.core;
core.modified = crate::cmd::saved_iso();
core.modified = crate::cmd::now_iso();
if core.created.is_empty() {
core.created = core.modified.clone();
}
+5 -19
View File
@@ -1,5 +1,3 @@
use wordcraft_layout::HideDeleted;
use super::doc_state::{Selection, TypedWord, typed_range};
use super::locale::SYSTEM_LOCALE;
use super::snapshot_types::LayoutEntry;
@@ -13,20 +11,6 @@ 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 };
@@ -39,8 +23,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 revisions = self.revision_layout_options();
let deleted = (revisions.hide_deleted, revisions.hide_marked, revisions.deletions_in_balloons);
let hide_deleted = !self.view.show_markup;
let deleted = (hide_deleted, self.prefs.markup.hidden_deletions(), self.revisions_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
@@ -78,6 +62,9 @@ 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,
@@ -90,7 +77,6 @@ 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);
+81 -95
View File
@@ -3711,23 +3711,6 @@ fn tracked_table_changes_are_kept_as_formatting_changes() {
assert!(b && !ch, "Accept All keeps it");
}
#[test]
fn ctrl_a_inside_table_selects_document() {
let mut s = s();
run(&mut s, "text.insert", json!({"text": "Before"}));
run(&mut s, "text.newParagraph", json!({}));
run(&mut s, "insert.table", json!({"rows": 2, "cols": 2}));
run(&mut s, "text.insert", json!({"text": "A1"}));
assert!(s.sel.focus.path.cell().is_some());
run(&mut s, "select.all", json!({}));
assert_eq!(s.sel.ordered(), (s.doc.start_of(StoryRef::Body), s.doc.end_of(StoryRef::Body)));
assert!(s.column.is_none());
assert!(s.selected_text().contains("Before"));
assert!(s.selected_text().contains("A1"));
}
#[test]
fn select_all_grows_cell_then_row_then_table_then_document() {
let mut s = s();
@@ -3737,24 +3720,24 @@ fn select_all_grows_cell_then_row_then_table_then_document() {
run(&mut s, "text.insert", json!({"text": "A1"}));
assert_eq!(s.sel.focus.path.cell().map(|(_, r, c)| (r, c)), Some((0, 0)));
run(&mut s, "select.all", json!({"whole": false}));
assert_eq!(cells(&s), Some(((0, 0), (0, 0))), "first staged selection selects the cell");
run(&mut s, "select.all", json!({}));
assert_eq!(cells(&s), Some(((0, 0), (0, 0))), "first Ctrl+A selects the cell");
assert_eq!(s.selected_text(), "A1");
run(&mut s, "select.all", json!({"whole": false}));
assert_eq!(cells(&s), Some(((0, 0), (0, 1))), "second staged selection selects the row");
run(&mut s, "select.all", json!({}));
assert_eq!(cells(&s), Some(((0, 0), (0, 1))), "second Ctrl+A selects the row");
run(&mut s, "select.all", json!({"whole": false}));
assert_eq!(cells(&s), Some(((0, 1), (0, 1))), "third staged selection selects the table");
run(&mut s, "select.all", json!({}));
assert_eq!(cells(&s), Some(((0, 1), (0, 1))), "third Ctrl+A selects the table");
run(&mut s, "select.all", json!({"whole": false}));
run(&mut s, "select.all", json!({}));
assert!(s.column.is_none());
let (a, b) = s.sel.ordered();
assert_eq!(a, s.doc.start_of(StoryRef::Body));
assert_eq!(b, s.doc.end_of(StoryRef::Body));
assert!(s.selected_text().starts_with("Before"));
run(&mut s, "select.all", json!({"whole": false}));
run(&mut s, "select.all", json!({}));
let (a, b) = s.sel.ordered();
assert_eq!((a, b), (s.doc.start_of(StoryRef::Body), s.doc.end_of(StoryRef::Body)));
}
@@ -3765,8 +3748,8 @@ fn select_all_from_a_column_grows_to_the_table() {
run(&mut s, "insert.table", json!({"rows": 2, "cols": 2}));
run(&mut s, "table.selectColumn", json!({}));
assert_eq!(cells(&s), Some(((0, 1), (0, 0))));
run(&mut s, "select.all", json!({"whole": false}));
assert_eq!(cells(&s), Some(((0, 1), (0, 1))), "staged selection on a column selects the table");
run(&mut s, "select.all", json!({}));
assert_eq!(cells(&s), Some(((0, 1), (0, 1))), "Ctrl+A on a column selects the table");
}
#[test]
@@ -7186,56 +7169,6 @@ 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};
@@ -10178,6 +10111,77 @@ fn change_case_keeps_each_runs_formatting_when_lengths_change() {
assert_eq!(text(&s), "Q");
}
/// #3479: Change Case follows language-aware mapping for Turkish, Azerbaijani, and Crimean Tatar (i↔İ, ı↔I).
#[test]
fn change_case_follows_turkic_language_mapping() {
// 1. Turkish (tr-TR): all 5 modes
// Capitalize Each Word (title)
let mut s = s();
run(&mut s, "review.language", json!({"lang": "tr-TR", "default": true}));
run(&mut s, "text.insert", json!({"text": "istanbul ışık", "raw": true}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": "title"}));
assert_eq!(text(&s), "İstanbul Işık");
// UPPERCASE
run(&mut s, "format.changeCase", json!({"mode": "upper"}));
assert_eq!(text(&s), "İSTANBUL IŞIK");
// lowercase
run(&mut s, "format.changeCase", json!({"mode": "lower"}));
assert_eq!(text(&s), "istanbul ışık");
// sentence case
let mut s = self::s();
run(&mut s, "review.language", json!({"lang": "tr-TR", "default": true}));
run(&mut s, "text.insert", json!({"text": "istanbul. ışık.", "raw": true}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": "sentence"}));
assert_eq!(text(&s), "İstanbul. Işık.");
// toggle case
let mut s = self::s();
run(&mut s, "review.language", json!({"lang": "tr-TR", "default": true}));
run(&mut s, "text.insert", json!({"text": "İstanbul Işık", "raw": true}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": "toggle"}));
assert_eq!(text(&s), "iSTANBUL ıŞIK");
// 2. Azerbaijani (az-AZ)
let mut s = self::s();
run(&mut s, "review.language", json!({"lang": "az-AZ", "default": true}));
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": "title"}));
assert_eq!(text(&s), "İstanbul");
// 3. Crimean Tatar (crh)
let mut s = self::s();
run(&mut s, "review.language", json!({"lang": "crh", "default": true}));
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": "title"}));
assert_eq!(text(&s), "İstanbul");
// 4. English control (en-US): unchanged Unicode default
let mut s = self::s();
run(&mut s, "review.language", json!({"lang": "en-US", "default": true}));
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": "title"}));
assert_eq!(text(&s), "Istanbul");
// 5. Mixed-language selection: Turkish run followed by English run
let mut s = self::s();
run(&mut s, "review.language", json!({"lang": "tr-TR"}));
run(&mut s, "text.insert", json!({"text": "istanbul ", "raw": true}));
run(&mut s, "review.language", json!({"lang": "en-US"}));
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": "title"}));
assert_eq!(text(&s), "İstanbul Istanbul");
}
#[test]
fn change_case_sentence_ignores_decimal_points() {
// #3485: Sentence case should not capitalize after decimal points.
@@ -16350,21 +16354,3 @@ fn open_and_save_report_format_conversion_errors() {
}
});
}
#[test]
fn opening_open_document_files_reports_section_conversion_errors_without_replacing_the_document() {
let incoming = wordcraft_doc::Document::from_text("Incoming document");
let message = "OpenDocument page conversion failed";
for name in ["incoming.odt", "incoming.ott", "incoming.fodt"] {
let bytes = crate::io::save_bytes(name, &incoming).unwrap();
let params = json!({"path": name, "data": crate::cmd::insert::base64_encode(&bytes)});
let mut s = Session::new(wordcraft_doc::Document::from_text("Keep this document"));
let id = s.document_id();
let err = wordcraft_formats::with_shared_conversion_error(message, || s.run("file.open", &params)).unwrap_err();
assert!(err.to_string().contains(message), "{name}: {err}");
assert_eq!(s.document_id(), id, "{name}");
assert_eq!(text(&s), "Keep this document", "{name}");
run(&mut s, "file.open", params);
assert_eq!(text(&s), "Incoming document", "{name}");
}
}
-24
View File
@@ -6,30 +6,6 @@ use wordcraft_doc::Pos;
use crate::Session;
use crate::cmd::insert::base64_encode;
#[test]
fn format_state_reports_the_east_asian_theme_face_and_keeps_unresolved_and_mixed_controls() {
use std::sync::Arc;
use wordcraft_doc::props::ThemeFont;
use wordcraft_doc::{Document, Path, StoryRef};
let mut doc = Document::from_text("漢字");
Arc::make_mut(&mut doc.styles).default_chr.font_ea = Some("Times New Roman".into());
doc.para_mut(StoryRef::Body, &Path::top(0))
.unwrap()
.format(0, "漢".len(), &|props| props.font_ea_theme = Some(ThemeFont::MinorEastAsia))
.unwrap();
let mut fallback = Session::new(doc.clone());
fallback.run("select.all", &json!({})).unwrap();
assert_eq!(fallback.run("format.state", &json!({})).unwrap()["fontEastAsia"], "Times New Roman");
doc.passthrough.insert("wordcraft:theme.fonts".into(), Arc::new(b"minor\tface\tea\tExample CJK Face\n".to_vec()));
let mut s = Session::new(doc);
s.run("select.range", &json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, "漢".len())})).unwrap();
assert_eq!(s.run("format.state", &json!({})).unwrap()["fontEastAsia"], "Example CJK Face");
s.run("select.all", &json!({})).unwrap();
assert!(s.run("format.state", &json!({})).unwrap()["fontEastAsia"].is_null(), "the theme face and named face differ");
}
/// The bundled face `file` of family `original` renamed `family` (as long as `original`), so it
/// is a font the database doesn't have.
fn renamed(file: &str, original: &str, family: &str) -> Vec<u8> {
+36 -184
View File
@@ -2407,57 +2407,6 @@ 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()))
@@ -2549,33 +2498,28 @@ fn arrow_keys_enter_a_visible_equation_across_a_hidden_deletion() {
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"}));
}
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),
] {
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": "noMarkup"}));
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, 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}");
}
run(&mut s, "caret.set", json!({"pos": from}));
arrow(&mut s, key);
assert_eq!(editing(&s), Some((equation, math_pos)));
}
}
@@ -3573,11 +3517,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 ışı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"),
("upper", "istanbul", "İSTANBUL"),
("lower", "IŞIK", "ışık"),
("title", "istanbul güzel", "İstanbul Güzel"),
("sentence", "istanbul. izmir", "İstanbul. İzmir"),
("toggle", "iI", "İı"),
] {
let mut s = s();
run(&mut s, "review.language", json!({"lang": tag, "default": true}));
@@ -3594,20 +3538,17 @@ 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.
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}");
}
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");
}
// Spelling as you type (#1552): the word being typed gets no red squiggle until the caret leaves
@@ -4639,95 +4580,6 @@ fn issues_1281_1045_english_dialects_proof_typed_text() {
assert_eq!(words, ["21th"]);
}
/// Where the first paragraph's list label starts (points from the page's text edge), and where its text starts.
fn label_and_text_x(s: &mut Session) -> (f32, f32) {
let l = s.layout();
l.pages
.iter()
.flat_map(|p| &p.items)
.find_map(|i| {
if let wordcraft_layout::Placed::Lines { para, l0: 0, .. } = i {
// The text starts where the first cluster is placed, after the label's suffix or tab stop.
para.label.as_ref().and_then(|lb| para.lines.first().and_then(|line| line.xs.first().map(|&x| (lb.x, x))))
} else {
None
}
})
.expect("a list label")
}
/// #4287: changing a list item's level (Change List Level, Tab, Shift+Tab) puts it at the new level's
/// indent, also when it carried a direct indent (a ruler drag, a pasted block, a Word file's `w:ind`).
#[test]
fn changing_a_list_level_drops_a_direct_indent() {
// The reference: a fresh list item moved to level 2 with no direct indent in the way.
let fresh = |command: &str, params: serde_json::Value| {
let mut s = s();
typ(&mut s, "Item");
run(&mut s, "para.numbering", json!({"kind": "upperLetter"}));
run(&mut s, command, params);
label_and_text_x(&mut s)
};
let dragged = |command: &str, params: serde_json::Value| {
let mut s = s();
typ(&mut s, "Item");
run(&mut s, "para.numbering", json!({"kind": "upperLetter"}));
// The ruler's left-indent marker dragged to a custom place.
run(&mut s, "para.indents", json!({"left": 120.0, "firstLine": -6.0}));
run(&mut s, command, params);
label_and_text_x(&mut s)
};
for (command, params) in [("para.listLevel", json!({"level": 1})), ("para.indent", json!({}))] {
assert_eq!(dragged(command, params.clone()), fresh(command, params), "{command}");
}
// Tab at the start of the item takes it down a level the same way.
let tabbed = |drag: bool| {
let mut s = s();
typ(&mut s, "Item");
run(&mut s, "para.numbering", json!({"kind": "upperLetter"}));
if drag {
run(&mut s, "para.indents", json!({"left": 120.0, "firstLine": -6.0}));
}
run(&mut s, "caret.home", json!({}));
run(&mut s, "text.tab", json!({}));
label_and_text_x(&mut s)
};
assert_eq!(tabbed(true), tabbed(false), "text.tab");
// Shift+Tab takes it back up.
let backtabbed = |drag: bool| {
let mut s = s();
typ(&mut s, "Item");
run(&mut s, "para.numbering", json!({"kind": "upperLetter"}));
run(&mut s, "para.listLevel", json!({"level": 1}));
if drag {
run(&mut s, "para.indents", json!({"left": 200.0, "firstLine": -30.0}));
}
run(&mut s, "text.backTab", json!({}));
label_and_text_x(&mut s)
};
assert_eq!(backtabbed(true), backtabbed(false), "text.backTab");
// Back out (Shift+Tab) from level 2 to 1 as well.
let back = |drag: bool| {
let mut s = s();
typ(&mut s, "Item");
run(&mut s, "para.numbering", json!({"kind": "upperLetter"}));
run(&mut s, "para.listLevel", json!({"level": 1}));
if drag {
run(&mut s, "para.indents", json!({"left": 200.0, "firstLine": -30.0}));
}
run(&mut s, "para.outdent", json!({}));
label_and_text_x(&mut s)
};
assert_eq!(back(true), back(false), "para.outdent");
// A ruler drag with no level change sticks.
let mut s = s();
typ(&mut s, "Item");
run(&mut s, "para.numbering", json!({"kind": "upperLetter"}));
let before = label_and_text_x(&mut s);
run(&mut s, "para.indents", json!({"left": 120.0, "firstLine": -6.0}));
assert_ne!(label_and_text_x(&mut s), before, "the drag moves the item");
}
/// #6788: Enter in a paragraph with a drop cap makes a normal paragraph; only the first keeps
/// the cap (Word behaviour), for a dropped cap and one in the margin.
#[test]
-11
View File
@@ -224,17 +224,6 @@ impl FontDb {
log::debug!("cataloged {n} system font faces");
*self.catalog.write().unwrap_or_else(std::sync::PoisonError::into_inner) = found;
self.catalog_gen.fetch_add(1, Ordering::AcqRel);
{
let mut sys = self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
sys.tried.clear();
sys.misses.clear();
}
self.fallbacks.write().unwrap_or_else(std::sync::PoisonError::into_inner).map.clear();
{
let mut rf = self.run_fallbacks.write().unwrap_or_else(std::sync::PoisonError::into_inner);
rf.map.clear();
rf.chars = 0;
}
n
}
+7 -4
View File
@@ -82,12 +82,12 @@ pub struct FontFace {
/// than the full-width figure in the table. Word's automatic spacing between East Asian and
/// Latin text is half of it (see `wordcraft_layout::para::grid::auto_space`).
pub avg_char_width: f64,
/// The shaper's view of the face, at the named instance's location for variable fonts.
pub hb: harfrust::Font,
/// Variable fonts: the named instance's axis settings (user units; empty = default instance)
/// and the normalised location.
pub shaper: harfrust::ShaperData,
/// Variable fonts: the named instance's axis settings (user units; empty = default instance),
/// the normalised location and the shaper's view of it.
pub coords: Vec<([u8; 4], f32)>,
pub(super) location: Location,
pub instance: Option<harfrust::ShaperInstance>,
/// Basic Multilingual Plane coverage bitset, built on first use.
pub(super) bmp: std::sync::OnceLock<Box<[u64]>>,
// Some legacy CJK fonts assemble their contours with TrueType instructions.
@@ -205,6 +205,9 @@ impl FontFace {
pub fn skrifa(&self) -> Option<skrifa::FontRef<'_>> {
skrifa::FontRef::from_index(self.data(), self.index).ok()
}
pub fn hb(&self) -> Option<harfrust::FontRef<'_>> {
harfrust::FontRef::from_index(self.data(), self.index).ok()
}
/// Where in the design space glyphs, metrics and outlines come from.
pub fn location(&self) -> LocationRef<'_> {
(&self.location).into()
+1 -1
View File
@@ -98,7 +98,7 @@ impl FontDb {
#[cfg(not(target_arch = "wasm32"))]
{
let enabled = self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).enabled;
if enabled && self.family_maps(FAMILY, c) {
if enabled {
self.load_cataloged(FAMILY);
}
}
+6 -7
View File
@@ -418,12 +418,10 @@ pub(super) fn make_face(
let location = if coords.is_empty() { Location::default() } else { f.axes().location(settings.iter().copied()) };
let m = f.metrics(Size::unscaled(), &location);
let a = f.attributes();
let source: harfrust::font::Source = match &bytes {
FontBytes::Static(b) => (*b).into(),
FontBytes::Owned(v) => (v.clone() as Arc<dyn AsRef<[u8]> + Send + Sync>).into(),
};
let hb = harfrust::Font::new(source, index)?;
let hb = if coords.is_empty() { hb } else { hb.instance_builder().variations(coords.iter().map(|(t, v)| (harfrust::Tag::new(t), *v))).build() };
let hb = harfrust::FontRef::from_index(data, index).ok()?;
let shaper = harfrust::ShaperData::new(&hb);
let instance = (!coords.is_empty())
.then(|| harfrust::ShaperInstance::from_variations(&hb, settings.iter().map(|(t, v)| harfrust::Variation { tag: *t, value: *v })));
let axis = |tag: &[u8; 4]| coords.iter().find(|(t, _)| t == tag).map(|(_, v)| *v);
// Old releases of heavy faces (Arial Black in the core fonts) claim weight 400 where current
// ones say 900, which Word doesn't embolden: a family named for its weight is that heavy.
@@ -449,9 +447,10 @@ pub(super) fn make_face(
cap_height: m.cap_height.map(|v| v as f64).filter(|v| *v > 0.0).unwrap_or(m.ascent as f64 * 0.72),
x_height: m.x_height.map(|v| v as f64).filter(|v| *v > 0.0).unwrap_or(m.ascent as f64 * 0.5),
avg_char_width: avg_char_width(&f, upem),
hb,
shaper,
coords,
location,
instance,
bytes,
index,
bmp: std::sync::OnceLock::new(),
-33
View File
@@ -1018,39 +1018,6 @@ fn catalog_postscript_names() {
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn cataloged_family_without_glyph_is_not_loaded_by_fallback_and_rescan_clears_misses() {
struct Cleanup(std::path::PathBuf);
impl Drop for Cleanup {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
let dir = std::env::temp_dir().join(format!("wc-sysfonts-{}-cmap-skip-and-rescan", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let _cleanup = Cleanup(dir.clone());
// SourceSerif4-Regular lacks '●' (\u{25CF}): cataloging it under Times New Roman and Arial
// must not cause circle_fallback or system_fallback to load those families when searching for '●'.
std::fs::write(dir.join("TNR.ttf"), named_face("SourceSerif4-Regular.ttf", "Times New Roman")).unwrap();
std::fs::write(dir.join("Arial.ttf"), named_face("SourceSerif4-Regular.ttf", "Arial")).unwrap();
let db = FontDb::with_font_dirs(vec![dir.clone()]);
db.faces.write().unwrap().retain(|face| face.family == "Source Serif 4");
let primary = db.face("Source Serif 4", "Regular");
assert!(db.fallback_for('●', primary.id()).is_none(), "no loaded or cataloged face covers '●'");
assert!(!db.is_loaded("Times New Roman"), "circle_fallback must skip Times New Roman when its cmap lacks '●'");
assert!(!db.is_loaded("Arial"), "system_fallback must skip Arial when its cmap lacks '●'");
// Populate sys.tried before rescanning; replacing Arial.ttf in place with a covering face and
// rescanning clears sys.tried, cached misses, and stale file coverage ranges.
db.sys.lock().unwrap().tried.insert("Arial");
std::fs::write(dir.join("Arial.ttf"), named_face("SourceSans3-Regular.ttf", "Arial")).unwrap();
db.load_system_fonts();
assert!(db.sys.lock().unwrap().tried.is_empty(), "rescan clears sys.tried");
let resolved = db.fallback_for('●', primary.id()).expect("rescan drops cached miss and reloads replaced Arial.ttf");
assert_eq!(resolved.family, "Arial");
}
/// Diagram fallback matches the primary font's serif/sans classification while body-text
/// fallback preserves loaded order (#5672), and changing user fonts invalidates run fallbacks.
#[test]
+53 -67
View File
@@ -20,7 +20,7 @@ pub use fontdb::{
base_style, bundled, bundled_inter, decode_font_file, is_font_file_name, name_language_matches, sniff, system_font_dirs,
};
pub use harfrust::Feature;
use harfrust::{Buffer, Direction, ShapeOptions, ShapePlan, ShapePlanKey, ShaperFont, Tag};
use harfrust::{Direction, ShapeOptions, ShapePlan, ShapePlanKey, Shaper, Tag, UnicodeBuffer};
pub use kurbo::BezPath;
pub use script::{fallback_rank, is_emoji, joins_cursively, needs_layout_tables, script_fallbacks};
use skrifa::MetadataProvider;
@@ -202,53 +202,50 @@ fn shape_dir(
around: ShapeContext<'_>,
) -> Vec<ShapedGlyph> {
let mut out = Vec::with_capacity(text.len());
let sf = ShaperFont::new(&face.hb);
// One script per shaping call: the shaper picks its script engine (Myanmar, Khmer,
// Indic, USE reordering…) from the run's script, so "Hi မြန်မာ" in one face must not be
// shaped as Latin. Runs come in text order; right-to-left callers regroup by cluster.
for r in script::script_runs(text) {
let Some(sub) = text.get(r.clone()) else { continue };
let mut buf = Buffer::new();
for (i, c) in sub.char_indices() {
buf.push(map(c) as u32, (r.start + i) as u32);
let shaped = face.hb().map(|hb| {
let shaper = face.shaper.shaper(&hb).instance(face.instance.as_ref()).build();
// One script per shaping call: the shaper picks its script engine (Myanmar, Khmer,
// Indic, USE reordering…) from the run's script, so "Hi မြန်မာ" in one face must not be
// shaped as Latin. Runs come in text order; right-to-left callers regroup by cluster.
for r in script::script_runs(text) {
let Some(sub) = text.get(r.clone()) else { continue };
let mut buf = UnicodeBuffer::new();
for (i, c) in sub.char_indices() {
buf.add(map(c), (r.start + i) as u32);
}
// After the text: adding to a buffer clears what follows it.
let around = around.at_edges_of(text, &r);
buf.set_pre_context(around.before);
buf.set_post_context(around.after);
buf.guess_segment_properties();
buf.set_direction(if rtl { Direction::RightToLeft } else { Direction::LeftToRight });
let plan = shape_plan(face, &shaper, &buf, features);
let gb = shaper.shape(buf, ShapeOptions::new().plan(plan.as_deref()).features(features));
for (info, pos) in gb.glyph_infos().iter().zip(gb.glyph_positions()) {
out.push(ShapedGlyph {
gid: info.glyph_id,
cluster: info.cluster as usize,
x_advance: pos.x_advance,
x_offset: pos.x_offset,
y_offset: pos.y_offset,
});
}
}
// After the text: adding to a buffer clears what follows it.
let around = around.at_edges_of(text, &r);
buf.set_pre_context(around.before);
buf.set_post_context(around.after);
buf.guess_segment_properties();
buf.set_direction(if rtl { Direction::RightToLeft } else { Direction::LeftToRight });
let plan = shape_plan(face, &buf, features);
// A run that exhausts the shaper's budget returns Ok with an incomplete buffer.
if harfrust::shape(&sf, &mut buf, ShapeOptions::new().plan(plan.as_deref()).features(features)).is_err() || !buf.allocation_successful() {
cmap_glyphs(face, sub, r.start, map, &mut out);
continue;
}
for (info, pos) in buf.glyph_infos().iter().zip(buf.glyph_positions()) {
out.push(ShapedGlyph {
gid: info.glyph_id,
cluster: info.cluster as usize,
x_advance: pos.x_advance,
x_offset: pos.x_offset,
y_offset: pos.y_offset,
});
});
if shaped.is_none()
&& let Some(f) = face.skrifa()
{
let cmap = f.charmap();
let gm = f.glyph_metrics(Size::unscaled(), face.location());
for (i, c) in text.char_indices() {
let g = cmap.map(map(c)).unwrap_or_default();
let adv = gm.advance_width(g).unwrap_or(face.upem as f32 * 0.5);
out.push(ShapedGlyph { gid: g.to_u32(), cluster: i, x_advance: adv.round() as i32, x_offset: 0, y_offset: 0 });
}
}
out
}
/// One glyph per character straight from the cmap, for a run the shaper could not do.
fn cmap_glyphs(face: &FontFace, text: &str, base: usize, map: &impl Fn(char) -> char, out: &mut Vec<ShapedGlyph>) {
let Some(f) = face.skrifa() else { return };
let cmap = f.charmap();
let gm = f.glyph_metrics(Size::unscaled(), face.location());
for (i, c) in text.char_indices() {
let g = cmap.map(map(c)).unwrap_or_default();
let adv = gm.advance_width(g).unwrap_or(face.upem as f32 * 0.5);
out.push(ShapedGlyph { gid: g.to_u32(), cluster: base + i, x_advance: adv.round() as i32, x_offset: 0, y_offset: 0 });
}
}
/// How many shape plans each thread keeps: the oldest is dropped to make room, so a thread never
/// holds more than this many, whatever fonts, scripts and feature sets it shapes.
const MAX_SHAPE_PLANS: usize = 64;
@@ -282,22 +279,22 @@ thread_local! {
/// oldest dropped past [`MAX_SHAPE_PLANS`]). A kept plan is used only for the same face and when
/// harfrust's own [`ShapePlanKey::matches`] accepts it (script, direction, language, the face's
/// variation instance and the features). `None` leaves making it to the shaper.
fn shape_plan(face: &FontFace, buf: &Buffer, features: &[Feature]) -> Option<std::rc::Rc<ShapePlan>> {
fn shape_plan(face: &FontFace, shaper: &Shaper, buf: &UnicodeBuffer, features: &[Feature]) -> Option<std::rc::Rc<ShapePlan>> {
// The buffer's script is unset when it reads as unknown: the guess never sets that.
let script = buf.script().filter(|s| *s != harfrust::Script::UNKNOWN);
let script = Some(buf.script()).filter(|s| *s != harfrust::script::UNKNOWN);
let language = buf.language();
let direction = buf.direction();
if direction == Direction::Invalid {
return None;
}
let key = ShapePlanKey::new(&face.hb, script, direction).language(language).features(features);
let key = ShapePlanKey::new(script, direction).language(language.as_ref()).instance(face.instance.as_ref()).features(features);
let of = PlanFace::of(face);
SHAPE_PLANS.with(|cell| {
let mut plans = cell.try_borrow_mut().ok()?;
if let Some((_, plan)) = plans.iter().find(|(f, plan)| *f == of && key.matches(plan)) {
return Some(plan.clone());
}
let plan = std::rc::Rc::new(ShapePlan::new(&face.hb, direction, script, language, features));
let plan = std::rc::Rc::new(ShapePlan::new(shaper, direction, script, language.as_ref(), features));
if plans.len() >= MAX_SHAPE_PLANS {
plans.remove(0);
}
@@ -362,14 +359,14 @@ mod tests {
#[test]
fn kept_shape_plans_shape_as_fresh_ones() {
let fresh = |face: &FontFace, text: &str, features: &[Feature], rtl: bool| -> Vec<(u32, u32, i32, i32, i32)> {
let mut buf = Buffer::new();
let Some(hb) = face.hb() else { return Vec::new() };
let shaper = face.shaper.shaper(&hb).instance(face.instance.as_ref()).build();
let mut buf = UnicodeBuffer::new();
buf.push_str(text);
buf.guess_segment_properties();
buf.set_direction(if rtl { Direction::RightToLeft } else { Direction::LeftToRight });
if harfrust::shape(&ShaperFont::new(&face.hb), &mut buf, ShapeOptions::new().features(features)).is_err() {
return Vec::new();
}
buf.glyph_infos().iter().zip(buf.glyph_positions()).map(|(i, p)| (i.glyph_id, i.cluster, p.x_advance, p.x_offset, p.y_offset)).collect()
let gb = shaper.shape(buf, ShapeOptions::new().features(features));
gb.glyph_infos().iter().zip(gb.glyph_positions()).map(|(i, p)| (i.glyph_id, i.cluster, p.x_advance, p.x_offset, p.y_offset)).collect()
};
let kept = |face: &FontFace, text: &str, features: &[Feature], rtl: bool| -> Vec<(u32, u32, i32, i32, i32)> {
shape_dir(face, text, features, &|c| c, rtl, ShapeContext::default())
@@ -398,14 +395,14 @@ mod tests {
fn kept_shape_plans_are_bounded() {
let face = FontDb::global().face(DEFAULT_FAMILY, "Regular");
let fresh = |features: &[Feature], rtl: bool| -> Vec<(u32, i32)> {
let mut buf = Buffer::new();
let Some(hb) = face.hb() else { return Vec::new() };
let shaper = face.shaper.shaper(&hb).instance(face.instance.as_ref()).build();
let mut buf = UnicodeBuffer::new();
buf.push_str("office");
buf.guess_segment_properties();
buf.set_direction(if rtl { Direction::RightToLeft } else { Direction::LeftToRight });
if harfrust::shape(&ShaperFont::new(&face.hb), &mut buf, ShapeOptions::new().features(features)).is_err() {
return Vec::new();
}
buf.glyph_infos().iter().zip(buf.glyph_positions()).map(|(i, p)| (i.glyph_id, p.x_advance)).collect()
let gb = shaper.shape(buf, ShapeOptions::new().features(features));
gb.glyph_infos().iter().zip(gb.glyph_positions()).map(|(i, p)| (i.glyph_id, p.x_advance)).collect()
};
for n in 0..3 * MAX_SHAPE_PLANS as u32 {
let features = [feature_value(b"kern", n % 2), feature_value(b"liga", n)];
@@ -418,17 +415,6 @@ mod tests {
assert_eq!(kept_shape_plans(), MAX_SHAPE_PLANS);
}
/// The cmap fallback for a failed run gives one glyph per character, its clusters offset by
/// where the run starts in the text.
#[test]
fn cmap_fallback_keeps_cluster_offsets() {
let face = FontDb::global().face(DEFAULT_FAMILY, "Regular");
let mut out = Vec::new();
cmap_glyphs(&face, "ab", 5, &|c| c, &mut out);
assert_eq!(out.iter().map(|g| g.cluster).collect::<Vec<_>>(), [5, 6]);
assert!(out.iter().all(|g| g.gid != 0 && g.x_advance > 0));
}
#[test]
fn ligatures_can_be_disabled() {
let face = FontDb::global().face(DEFAULT_FAMILY, "Regular");
+3 -4
View File
@@ -122,8 +122,7 @@ const COLOR_EMOJI: &[&str] = &["Segoe UI Emoji", "Apple Color Emoji", "Noto Colo
pub fn is_emoji(c: char) -> bool {
matches!(
u32::from(c),
0x1F000..=0x1F7FF
| 0x1F900..=0x1FAFF
0x1F000..=0x1FAFF
| 0x231A..=0x231B
| 0x23E9..=0x23EC
| 0x23F0
@@ -211,8 +210,8 @@ mod tests {
assert!(fallback_rank(c, "Segoe UI Emoji") < fallback_rank(c, "Segoe UI Symbol"), "{c}");
assert!(fallback_rank(c, "Noto Color Emoji") < fallback_rank(c, "Noto Emoji"), "{c}");
}
// Text-style symbols keep the symbol fonts, including Supplemental Arrows-C.
for c in ['✔', '☺', '→', '\u{1F86A}', 'a', '1'] {
// Text-style symbols keep the symbol fonts.
for c in ['✔', '☺', '→', 'a', '1'] {
assert!(!is_emoji(c), "{c}");
}
}
+2 -4
View File
@@ -9,10 +9,8 @@ description = "WordCraft import/export: plain text, Markdown, HTML, RTF, OpenDoc
workspace = true
[features]
# 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.
# `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-support = ["craft-xls/test-support"]
[dependencies]
+8 -4
View File
@@ -4,13 +4,17 @@ use std::sync::Arc;
use wordcraft_doc::{Block, Document, SectionProps};
use crate::shared_section;
pub use craft_odf::text::{CryptError, TEMPLATE_MIME, TEXT_MIME, decrypt, encrypt, is_encrypted};
/// Text room, points, that header and footer bands leave on a page (as Page Setup's margins must).
const MIN_TEXT_ROOM: f32 = 36.0;
fn shared_section(page: &SectionProps) -> craft_wordmodel::SectionProps {
let mut d = Document::new();
d.last_section = page.clone();
wordcraft_docx::to_shared_model(&d).map(|s| s.last_section).unwrap_or_default()
}
/// A shared document opened as a WordCraft one, its pages keeping the text room the header and
/// footer bands leave ([`keep_text_room`]).
fn from_shared(shared: craft_wordmodel::Document) -> Result<Document, String> {
@@ -65,7 +69,7 @@ pub fn import(bytes: &[u8]) -> Result<Document, String> {
}
pub fn import_on(bytes: &[u8], page: &SectionProps) -> Result<Document, String> {
from_shared(craft_odf::text::import_on(bytes, &shared_section(page)?)?)
from_shared(craft_odf::text::import_on(bytes, &shared_section(page))?)
}
pub fn import_flat(bytes: &[u8]) -> Result<Document, String> {
@@ -73,7 +77,7 @@ pub fn import_flat(bytes: &[u8]) -> Result<Document, String> {
}
pub fn import_flat_on(bytes: &[u8], page: &SectionProps) -> Result<Document, String> {
from_shared(craft_odf::text::import_flat_on(bytes, &shared_section(page)?)?)
from_shared(craft_odf::text::import_flat_on(bytes, &shared_section(page))?)
}
/// The shared model an OpenDocument file is written from. ODF's `dc:date` is an instant (a `Z`
-28
View File
@@ -418,34 +418,6 @@ fn odt_round_trip() {
assert_eq!(back.core.creator, "Ada Writer");
}
#[test]
fn open_document_import_on_reports_section_conversion_errors() {
// Original synthetic ODT, OTT and FODT without a page layout, so they use the supplied paper size.
let ns = concat!(
r#"xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" "#,
r#"xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" office:version="1.3""#,
);
let body = "<office:body><office:text><text:p>Page geometry</text:p></office:text></office:body>";
let packaged = |mime: &str| {
let content = format!("<office:document-content {ns}>{body}</office:document-content>");
let mut zip = craft_zip::Writer::new();
zip.add("mimetype", mime.as_bytes(), craft_zip::Compression::Stored).unwrap();
zip.add("content.xml", content.as_bytes(), craft_zip::Compression::Stored).unwrap();
zip.finish().unwrap()
};
let flat = format!(r#"<office:document {ns} office:mimetype="{}">{body}</office:document>"#, crate::odt::TEXT_MIME);
let cases = [("odt", packaged(crate::odt::TEXT_MIME)), ("ott", packaged(crate::odt::TEMPLATE_MIME)), ("fodt", flat.into_bytes())];
let page = wordcraft_doc::SectionProps { page_w: 505.0, page_h: 731.0, ..Default::default() };
let message = "OpenDocument page conversion failed";
for (ext, bytes) in cases {
let open = || crate::import_on(ext, &bytes, &page).unwrap();
let doc = open().unwrap();
assert_eq!((doc.last_section.page_w, doc.last_section.page_h), (page.page_w, page.page_h), "{ext}");
assert_eq!(doc.plain_text(wordcraft_doc::StoryRef::Body), "Page geometry", "{ext}");
assert_eq!(crate::with_shared_conversion_error(message, open).unwrap_err(), message, "{ext}");
}
}
/// A flat ODT on A4 with a header and a footer, their bands' minimum heights (`fo:min-height`)
/// stated, and two body paragraphs.
fn flat_odt_with_bands(header: &str, footer: &str) -> Vec<u8> {
-1
View File
@@ -14,7 +14,6 @@ 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 }
+3 -3
View File
@@ -1,6 +1,6 @@
use super::ctx::{Ctx, Joining, page_anchored};
use super::floats::{
AnchoredFloat, ObjFrame, ObjectPlacement, WrapArea, align_in, float_rect, floating, left_out_objects, place_objects, rel_exclusions, wrap_area,
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;
@@ -361,7 +361,7 @@ 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, AnchoredFloat::new(r));
floats.insert(oi, r);
}
let rel = rel_exclusions(&excl, 0.0, y, applied);
if !rel.is_empty() {
@@ -563,7 +563,7 @@ fn box_float_table_rect(
Anchor::Page => Some((0.0, s.page_h)),
Anchor::Margin => {
let mut reference = s.clone();
reference.margin_top = fr.margin_top.unwrap_or(s.margin_top);
reference.margin_top = fr.margin_top.unwrap_or(s.margin_top.abs());
Some((reference.margin_top, reference.text_height()))
}
_ => None,
-1
View File
@@ -156,7 +156,6 @@ pub(crate) fn env_hash(doc: &Document, cache: &mut LayoutCache, opts: &LayoutOpt
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);
+16 -35
View File
@@ -82,7 +82,7 @@ pub(crate) fn float_rect(frame: Option<PageFrame>, col: (f32, f32), y0: f32, w:
};
let page_y = |f: &PageFrame| {
let s = f.sect;
let top = f.margin_top.unwrap_or(s.margin_top);
let top = f.margin_top.unwrap_or(s.margin_top.abs());
match float.v_rel {
Anchor::Page => Some((0.0, s.page_h)),
Anchor::Margin => {
@@ -90,8 +90,8 @@ pub(crate) fn float_rect(frame: Option<PageFrame>, col: (f32, f32), y0: f32, w:
reference.margin_top = top;
Some((top, reference.text_height()))
}
Anchor::TopMargin | Anchor::InsideMargin => Some((0.0, s.margin_top)),
Anchor::BottomMargin | Anchor::OutsideMargin => Some((s.page_h - s.margin_bottom, s.margin_bottom)),
Anchor::TopMargin | Anchor::InsideMargin => Some((0.0, s.margin_top.abs())),
Anchor::BottomMargin | Anchor::OutsideMargin => Some((s.page_h - s.margin_bottom.abs(), s.margin_bottom.abs())),
_ => None,
}
};
@@ -349,7 +349,7 @@ pub(crate) fn anchor_floats(
pb: &mut PageBuilder,
anchor: FloatAnchor,
force: &[usize],
) -> (HashMap<usize, AnchoredFloat>, Arc<ParaLayout>, Vec<para::Exclusion>, Vec<usize>) {
) -> (HashMap<usize, Rect>, 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.
@@ -471,26 +471,13 @@ 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, AnchoredFloat>, Arc<ParaLayout>, Vec<para::Exclusion>) {
) -> (HashMap<usize, Rect>, 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;
@@ -528,7 +515,7 @@ 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, AnchoredFloat::new(r));
rects.insert(oi, 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()));
@@ -566,8 +553,7 @@ fn anchor_floats_but(
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;
let Some(&r) = rects.get(&oi) else { continue };
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 };
@@ -575,11 +561,7 @@ fn anchor_floats_but(
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),
};
rects.insert(oi, moved);
if let Some((k, _)) = area
&& let Some(slot) = pb.excl.get_mut(k)
{
@@ -756,7 +738,7 @@ pub(crate) struct ObjectPlacement<'a> {
pub lines: (usize, usize),
pub origin: (f32, f32),
pub at: &'a ObjFrame<'a>,
pub floats: &'a HashMap<usize, AnchoredFloat>,
pub floats: &'a HashMap<usize, Rect>,
pub depth: usize,
}
@@ -816,23 +798,22 @@ 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, origin_y) = if let Some(r) = pinned {
(r, at.para_y)
let rect = if let Some(r) = pinned {
r
} else if let Some(l) = late_here {
(l.rect, l.top)
l.rect
} else if floating {
match floats.get(&oi) {
Some(placed) => (placed.rect, placed.pushed_origin.unwrap_or(at.para_y)),
Some(r) => *r,
None => {
let h = ctx.float_height(obj, w, h);
(float_rect(at.page, at.col, at.para_y, w, h, float), at.para_y)
float_rect(at.page, at.col, at.para_y, w, h, float)
}
}
} else {
let cx = x + line.cl_left(k).unwrap_or(0.0);
let modern = ctx.doc.settings.compat_mode >= wordcraft_doc::COMPAT_MODE_CURRENT;
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)
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 (mut behind, mut front) = (Vec::new(), Vec::new());
let layer = if float.wrap == Wrap::BehindText { &mut behind } else { &mut front };
@@ -879,7 +860,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, origin_y),
origin: Point::new(at.col.0, late_here.map_or(at.para_y, |l| l.top)),
group_boxes,
});
for (id, rect) in boxes {
+5 -6
View File
@@ -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::{
AnchoredFloat, FloatAnchor, LateFloats, ObjFrame, ObjectPlacement, anchor_floats, body_wraps, continued_exclusions, fitting, float_rect,
late_floats, place_late, place_objects, wrap_area,
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, StoryRef, TextDirection, ViewMode,
outline, para,
Arc, Block, Counters, Document, HashMap, InlineObject, Level, LineEnd, Page, ParaLayout, Paragraph, Path, Rect, 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, AnchoredFloat>,
float_rects: HashMap<usize, Rect>,
pl: Arc<ParaLayout>,
rel: Vec<para::Exclusion>,
/// The page its fields were laid out for, and the width.
@@ -1312,7 +1312,6 @@ 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() {
+11 -3
View File
@@ -386,7 +386,7 @@ impl PageBuilder<'_> {
self.number = self.restart_at.take().unwrap_or_else(|| self.number.saturating_add(1));
let (w, h) = if self.web { (s.page_w, f32::MAX / 4.0) } else { (s.page_w, s.page_h) };
let bottom = self.body_bottom(body_top);
self.leading_floor = (s.page_h - s.margin_bottom).min(self.foot_top);
self.leading_floor = (s.page_h - s.margin_bottom.abs()).min(self.foot_top);
let body = Rect::new(s.margin_left + s.gutter, body_top, s.text_width(), (bottom - body_top).max(36.0));
let mut decor = Vec::new();
if !self.web {
@@ -473,8 +473,12 @@ impl PageBuilder<'_> {
self.bottom >= self.leading_floor - 0.01
}
/// The bottom of the body on a page started with its body at `body_top`: a footer taller than
/// the bottom margin pushes it up (Word: no gap), leaving it at least a little room.
/// the bottom margin pushes it up (Word: no gap), leaving it at least a little room. A
/// negative bottom margin is exact: the body ends at its size and the footer overlaps it.
fn body_bottom(&self, body_top: f32) -> f32 {
if self.sect.margin_bottom < 0.0 {
return self.sect.page_h + self.sect.margin_bottom;
}
// ODF keeps the footer's spacing above a footer too tall for the bottom margin.
let gap = if self.sect.footer_gap.is_finite() { self.sect.footer_gap.clamp(0.0, 1584.0) } else { 0.0 };
(self.sect.page_h - self.sect.margin_bottom).min((self.foot_top - gap).max(body_top + 36.0))
@@ -569,8 +573,12 @@ pub(crate) fn item_bottom(y: f32, para: &ParaLayout, l0: usize, l1: usize) -> Op
Some(y + l.top + l.height - f.top)
}
/// Where body text starts: the top margin, or below the header if it's taller.
/// Where body text starts: the top margin, or below the header if it's taller. A negative top
/// margin is exact (ECMA-376 §17.6.11): the text starts at its size and the header overlaps it.
pub(crate) fn body_top_for(ctx: &mut Ctx, sect: &SectionProps, header: Option<u32>) -> f32 {
if sect.margin_top < 0.0 {
return -sect.margin_top;
}
let Some(id) = header else { return sect.margin_top };
let Some(part) = ctx.doc.parts.get(&id) else { return sect.margin_top };
let blocks = part.blocks.clone();
-6
View File
@@ -45,12 +45,6 @@ pub use paragraph::layout_para;
pub(crate) use paragraph::word_widths;
pub use proof::{ProofRun, is_list_item, paragraph_issues, proof_runs, proof_text};
/// The East Asian family requested by layout for this run, before installed-font substitution.
/// A theme slot takes precedence over the inherited name and can have no resolved face.
pub fn east_asian_font<'a>(doc: &'a Document, run: &'a ResolvedChar) -> Option<&'a str> {
chars::east_asian_font(doc, run)
}
/// A laid-out paragraph.
#[derive(Clone, Debug)]
pub struct ParaLayout {
+5 -12
View File
@@ -155,14 +155,11 @@ 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, 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). Any other character: Small Caps draws lowercase letters, and
// the space and ideographic space, at the small-caps size, as Word does; a no-break
// space, digits and punctuation keep the full size (#7062).
// that character's size, so the two stay in one shaping run and its cluster is matched
// whole.
let small = match cur {
Some(k) if mark => k.small,
_ => rc.small_caps && !rc.caps && (c.is_lowercase() || c == ' ' || c == '\u{3000}'),
_ => rc.small_caps && !rc.caps && c.is_lowercase(),
};
let key = SegKey { face, small, complex, rtl };
match cur {
@@ -208,9 +205,7 @@ impl<'a> Builder<'a> {
return i;
}
}
// Small capitals are set at 80% of the size rounded to the half point, as Word does
// (16 pt → 13, 14 → 11, 12 → 9.5, #7062).
let size = if small { (rc.draw_size() * 0.8 * 2.0).round() / 2.0 } else { rc.draw_size() };
let size = rc.draw_size() * if small { 0.8 } else { 1.0 };
// A symbol font that isn't installed, or is installed one em tall (Apple's Symbol), takes
// the height Word gives it.
let (a, d) = match wordcraft_fonts::word::symbol_line(&rc.font, &r) {
@@ -226,9 +221,7 @@ impl<'a> Builder<'a> {
}
None => wordcraft_fonts::word::line_metrics(&face),
};
// A small-caps piece is drawn at 80% but measured for the line at the full size: a Small
// Caps line is as tall as without Small Caps, as in Word (#7063).
let k = rc.draw_size() as f64 / face.upem.max(1.0);
let k = size as f64 / face.upem.max(1.0);
// A fallback face (letters the requested font lacks) is emboldened or slanted when it has
// no bold or italic of its own.
let (synth_bold, synth_italic) = match face_override {
+7 -34
View File
@@ -215,48 +215,21 @@ pub fn substitute_face(doc: &Document, font: &str) -> Option<FaceRef> {
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.
/// The East Asian font (`a:ea`) stored for the theme's major or minor font scheme, when the
/// document's theme names a non-empty one (`craft-docx` keeps them in `wordcraft:theme.fonts`).
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)?)
text.lines().find_map(|line| {
let mut parts = line.splitn(4, '\t');
let (k, kind, which, face) = (parts.next()?, parts.next()?, parts.next()?, parts.next()?);
(k == key && kind == "face" && which == "ea" && !face.trim().is_empty()).then_some(face)
})
}
/// 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.
/// points to an East Asian theme font with no single named `a:ea` 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 {
+7 -17
View File
@@ -61,9 +61,6 @@ 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,
@@ -235,7 +232,6 @@ impl<'e> Breaker<'e> {
i: 0,
top: 0.0,
first: true,
space_band: true,
row_rest: VecDeque::new(),
row_first: 0,
skipped: 0,
@@ -272,13 +268,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). 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 {
// laid out again under it (#7143). Exclusions are relative to the first line's
// original top (0), so keep the band anchored there (`[-before, est_h]`) even after
// `row_spans` or `skip_row` moves `self.top` down past a side-wrapping object (#8614):
// only the space the flow actually laid out above 0 holds a space-before obstruction.
if self.first && self.space_before > 0.0 {
let before = self.space_before;
let row = (self.top - before, self.est_h + before, self.table_h + before);
let row = (-before, self.est_h + before, self.table_h);
if let Some(below) = self
.exclusions
.iter()
@@ -286,12 +282,8 @@ 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 = below + before;
guard += 1;
continue;
self.top = self.top.max(below + before);
}
}
let row = (self.top, self.est_h, self.table_h);
@@ -306,7 +298,6 @@ impl<'e> Breaker<'e> {
}
Err(below) if below > self.top && guard < 50 => {
self.top = below;
self.space_band = false;
guard += 1;
}
Ok((None, _)) | Err(_) => {
@@ -388,7 +379,6 @@ 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))
+2 -2
View File
@@ -291,7 +291,7 @@ fn section_tops(ctx: &mut Ctx, hf: &HfLinks, (si, sect): (usize, &SectionProps),
let (heads, feet) = (hf.heads.set(si), hf.feet.set(si));
let hb = |i: Option<u32>| hf.defining_width(false, si, i);
let fb = |i: Option<u32>| hf.defining_width(true, si, i);
let body = if fixed { sect.margin_top } else { with_pct_base(ctx, hb(heads.default), |c| body_top_for(c, sect, heads.default)) };
let body = if fixed { sect.margin_top.abs() } else { with_pct_base(ctx, hb(heads.default), |c| body_top_for(c, sect, heads.default)) };
let first = if fixed || !sect.title_page { body } else { with_pct_base(ctx, hb(heads.first), |c| body_top_for(c, sect, heads.first)) };
let foot = if fixed { f32::MAX } else { with_pct_base(ctx, fb(feet.default), |c| foot_top_for(c, sect, feet.default)) };
let first_foot = if fixed || !sect.title_page { foot } else { with_pct_base(ctx, fb(feet.first), |c| foot_top_for(c, sect, feet.first)) };
@@ -625,7 +625,7 @@ pub(crate) fn layout_pass(
section_endnotes(&mut ctx, &mut pb, &mut endnotes, (sect, si, block));
}
if pb.pages.is_empty() {
pb.new_page(0, sect_ref.margin_top);
pb.new_page(0, sect_ref.margin_top.abs());
}
// The rest of the endnotes after the last paragraph.
let rest: Vec<u32> = endnotes.into_iter().map(|(id, _)| id).collect();
+2 -79
View File
@@ -336,12 +336,8 @@ pub fn autofit_widths(cols: &[(f32, f32)], avail: f32) -> Vec<f32> {
/// 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). A right-to-left table (`w:bidiVisual`) has its left edge at the offset in every
/// mode: Word moves it by neither a cell margin nor the indent nor a border (#8517).
/// Windows).
pub(crate) fn float_offset_shift(ctx: &Ctx, t: &Table) -> f32 {
if t.props.bidi_visual {
return 0.0;
}
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)
@@ -606,10 +602,6 @@ fn table_frame(ctx: &mut Ctx, t: &Table, avail: f32, depth: usize, style: Option
// by that half.
indent + half_edge_border(t, &tborders)
} else {
// A right-to-left table too, though its first cell's left margin is on the cell's far
// side: with a left margin of 10 pt and a right one of 2 pt its text ends 8 pt past the
// right margin, as in Word (#8517, measured in Word for Windows). A floating one isn't
// moved ([`float_offset_shift`]).
indent - first_cell_left_margin_in(t, margins_def)
};
// The reading view fits the table into what the start offset leaves of the column, mirrored or not (#7988).
@@ -866,13 +858,7 @@ fn layout_table_rows(ctx: &mut Ctx, story: StoryRef, t: &Table, path: &[u32], av
};
bottoms.push(row_below);
edges.push(row_edge);
heights.push(
if (collapsed && !cells.is_empty()) || matches!((row.props.height, row.props.height_rule), (Some(h), HeightRule::Exact) if h > 0.0) {
rh.max(0.0)
} else {
rh.max(4.0)
},
);
heights.push(if collapsed && !cells.is_empty() { rh.max(0.0) } else { rh.max(4.0) });
rows.push(cells);
}
grow_vertical_merges(&rows, &mut heights);
@@ -1752,10 +1738,6 @@ fn is_automatic(t: &Table) -> bool {
/// Consistent cell widths replace a stale grid without changing the table's total width.
/// Conflicting widths, spans and percentages need the full shared-grid algorithm.
fn apply_cell_widths(t: &Table, grid: &mut [f32]) {
if let Some(widths) = stale_grid_widths(t, grid) {
grid.copy_from_slice(&widths);
return;
}
let Some(first) = t.rows.first() else { return };
if first.cells.len() != grid.len() {
return;
@@ -1775,41 +1757,6 @@ fn apply_cell_widths(t: &Table, grid: &mut [f32]) {
grid.copy_from_slice(&widths);
}
// An autofit table whose width matches its complete point-width rows but not its grid takes the rows.
fn stale_grid_widths(t: &Table, grid: &[f32]) -> Option<Vec<f32>> {
const WIDTH_EPSILON: f32 = 0.5;
const EDGE_EPSILON: f32 = 0.01;
let width = t.props.width.filter(|w| w.is_finite() && (w - grid.iter().sum::<f32>()).abs() > WIDTH_EPSILON)?;
if t.props.fixed || t.props.width_pct.is_some() || t.rows.is_empty() {
return None;
}
let mut edges = vec![None; grid.len() + 1];
edges[0] = Some(0.0);
for row in &t.rows {
if row.first_grid() != 0 || row.grid_after() != 0 {
return None;
}
let (mut g, mut x) = (0usize, 0.0f32);
for cell in &row.cells {
x += cell.props.width.filter(|w| w.is_finite() && *w > 0.0 && cell.props.width_pct.is_none())?;
g = g.saturating_add(cell.span());
let edge = edges.get_mut(g)?;
if edge.is_some_and(|previous: f32| (previous - x).abs() > EDGE_EPSILON) {
return None;
}
edge.get_or_insert(x);
}
if g != grid.len() {
return None;
}
}
if (edges[grid.len()]? - width).abs() > WIDTH_EPSILON {
return None;
}
let widths: Option<Vec<f32>> = edges.windows(2).map(|pair| Some(pair[1]? - pair[0]?)).collect();
widths.filter(|widths| widths.iter().all(|w| *w > 0.0))
}
/// Word sizes each column by the percentage its cells ask for, whichever rows ask: cells without a
/// preferred width take no part, so a header row of percentages sizes the automatic rows below it.
/// The percentages are shares of the table's width, scaled up when they come short of 100%; past
@@ -2011,30 +1958,6 @@ mod width_tests {
assert_eq!(grid, [25.0, 40.0]);
}
#[test]
fn rows_outrank_grid_total() {
let mut table = Table::new(3, 4, 400.0);
let rows = [vec![(4, 400.0)], vec![(2, 150.0), (1, 200.0), (1, 50.0)], vec![(1, 60.0), (1, 90.0), (2, 250.0)]];
for (row, widths) in table.rows.iter_mut().zip(rows) {
row.cells.truncate(widths.len());
for (cell, (span, width)) in row.cells.iter_mut().zip(widths) {
cell.props.span = span;
cell.props.width = Some(width);
}
}
table.grid = vec![100.0, 200.0, 250.0, 100.0];
table.props.width = Some(400.0);
let mut grid = table.grid.clone();
apply_cell_widths(&table, &mut grid);
assert_eq!(grid, [60.0, 90.0, 200.0, 50.0]);
table.props.fixed = true;
grid.copy_from_slice(&table.grid);
apply_cell_widths(&table, &mut grid);
assert_eq!(grid, [100.0, 200.0, 250.0, 100.0], "a fixed table keeps its grid");
}
#[test]
fn autofit_keeps_fitting_widths() {
crate::test_fonts();
+1 -1
View File
@@ -395,7 +395,7 @@ fn place_floating_table(ctx: &mut Ctx, pb: &mut PageBuilder, tl: &table::TableLa
// The text a table anchored to it stands in: where the next paragraph starts.
let v_area = match f.v_rel {
Anchor::Page => (0.0, s.page_h),
Anchor::Margin => (s.margin_top, s.text_height()),
Anchor::Margin => (s.margin_top.abs(), s.text_height()),
_ => (pb.y, 0.0),
};
let x = float_table_x(pb, w, f, legacy, ctx.mirror);
+6 -309
View File
@@ -3894,9 +3894,9 @@ 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.
/// A single word longer than an at-least row's minimum height (0.3 cm / ~8.5 pt) runs past
/// the row along its length instead of growing the row, as long as the wrapped pieces fit across
/// the column.
#[test]
fn a_word_longer_than_min_height_does_not_grow_an_at_least_row() {
use wordcraft_doc::props::HeightRule;
@@ -3922,20 +3922,17 @@ fn a_word_longer_than_min_height_does_not_grow_an_at_least_row() {
.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]
let 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))
Some(para.lines.get(*l0..*l1).unwrap_or(&[]).iter().filter_map(|line| line.xs.last().copied()).fold(0.0f32, f32::max))
}
_ => 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}");
assert!(extent > min_h, "{turn:?}: word should run past the min height {min_h}, got {extent}");
}
}
@@ -6906,30 +6903,6 @@ fn row_height(l: &DocLayout, row: usize) -> f32 {
l.pages[0].items.iter().find_map(|i| if let Placed::Cell { rect, row: r, .. } = i { (*r == row).then_some(rect.h) } else { None }).unwrap()
}
#[test]
fn exact_rows_below_four_points_keep_their_height() {
crate::test_fonts();
use wordcraft_doc::props::HeightRule;
let mut doc = Document::new();
let mut table = Table::new(40, 1, 200.0);
table.props.cell_margins = Some([0.0; 4]);
for row in &mut table.rows {
row.props.height = Some(2.85);
row.props.height_rule = HeightRule::Exact;
}
doc.body = vec![Arc::new(Block::Table(table))];
let layout = lay(&doc);
let height: f32 = layout
.pages
.iter()
.flat_map(|page| &page.items)
.filter_map(|item| if let Placed::Cell { rect, table, .. } = item { (table == &Path::top(0)).then_some(rect.h) } else { None })
.sum();
assert!((height - 40.0 * 2.85).abs() < 0.1, "40 exact rows should total 114 pt, got {height}");
}
/// The laid-out paragraph in cell (row, col) of the table at body index 1.
fn cell_para(l: &DocLayout, row: u32, col: u32) -> Arc<ParaLayout> {
l.pages[0]
@@ -9055,121 +9028,6 @@ fn side_wrapping_push_does_not_shift_space_before_band_into_para_area() {
);
}
/// #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();
@@ -15291,30 +15149,6 @@ fn cell_widths_override_grid() {
}
}
// Word sizes an autofit table whose width matches its rows from the rows, not a stale grid.
#[test]
fn ordinary_table_takes_row_widths() {
crate::test_fonts();
let mut t = Table::new(3, 2, 132.0);
t.grid = vec![70.0, 62.0];
t.props.width = Some(120.0);
for row in &mut t.rows {
for (cell, width) in row.cells.iter_mut().zip([40.0, 80.0]) {
cell.props.width = Some(width);
cell.blocks = vec![wordcraft_doc::para_block(Paragraph::with_text("A", Default::default()))];
}
}
t.rows[0].cells.truncate(1);
t.rows[0].cells[0].props.span = 2;
t.rows[0].cells[0].props.width = Some(120.0);
let mut d = Document::from_text("After");
d.insert_block(StoryRef::Body, &Path::top(0), wordcraft_doc::Block::Table(t)).unwrap();
let l = lay(&d);
let [(x0, _, _)] = para_at(&l, &[0, 1, 0, 0])[..] else { panic!("cell missing") };
let [(x1, _, _)] = para_at(&l, &[0, 1, 1, 0])[..] else { panic!("cell missing") };
assert!((x1 - x0 - 40.0).abs() < 0.01, "{}", x1 - x0);
}
#[test]
fn percentage_cell_widths_that_disagree_or_span_columns() {
// Measured in Word (A4, 451.3 pt between the margins; 468 pt here), autofit tables 100% wide:
@@ -15807,91 +15641,6 @@ fn caps_draw_sharp_s_as_two_capitals_in_one_cluster() {
assert_eq!(cl.iter().map(|c| c.2.len()).sum::<usize>(), 6, "{cl:?}");
}
/// `text` laid out with `f` applied to all of it: its paragraph's layout.
fn para_with(text: &str, f: &dyn Fn(&mut wordcraft_doc::props::CharProps)) -> ParaLayout {
let mut d = Document::from_text(text);
d.format_range(&Pos::body(0, 0), &Pos::body(0, text.len()), f).unwrap();
let l = lay(&d);
l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some((**para).clone()) } else { None }).expect("a laid-out line")
}
/// Small Caps draws a space (U+0020) at the small-caps size, like a lowercase letter, as Word
/// does (measured: 40 spaces in Times New Roman Bold 10 pt are 80% as wide in Small Caps); a
/// no-break space keeps its full width, and with All Caps as well the space keeps its full width,
/// as All Caps wins (#7062).
#[test]
fn a_space_in_small_caps_is_as_wide_as_at_the_small_caps_size() {
crate::test_fonts();
// The gap between the first and the last letter of `text`.
let gap = |text: &str, f: &dyn Fn(&mut wordcraft_doc::props::CharProps)| {
let pl = para_with(text, f);
let line = &pl.lines[0];
let x = |start: usize| (line.c0..line.c1).find(|&k| pl.clusters[k].start == start).and_then(|k| line.cl_left(k)).unwrap();
x(text.len() - 1) - x(1)
};
// At 10 pt the small-caps size is exactly 8 pt (80%, no rounding to the half point).
let plain: &dyn Fn(&mut wordcraft_doc::props::CharProps) = &|c| c.size = Some(10.0);
let small: &dyn Fn(&mut wordcraft_doc::props::CharProps) = &|c| {
c.small_caps = Some(true);
c.size = Some(10.0);
};
let both: &dyn Fn(&mut wordcraft_doc::props::CharProps) = &|c| {
c.caps = Some(true);
c.small_caps = Some(true);
c.size = Some(10.0);
};
let spaces = format!("a{}a", " ".repeat(10));
let ratio = gap(&spaces, small) / gap(&spaces, plain);
assert!((ratio - 0.8).abs() < 0.01, "Small Caps spaces are 80% as wide: {ratio}");
assert!((gap(&spaces, both) - gap(&spaces, plain)).abs() < 0.01, "All Caps wins: full-width spaces");
let nbsp = format!("a{}a", "\u{a0}".repeat(10));
assert!((gap(&nbsp, small) - gap(&nbsp, plain)).abs() < 0.01, "a no-break space keeps its width");
}
/// Word sets small capitals at 80% of the size rounded to the half point, a size the format can
/// store, like superscript (measured in Word for Microsoft 365, Times New Roman: 10 pt → 8,
/// 11 → 9, 12 → 9.5, 14 → 11, 16 → 13); a Small Caps space takes that size too (#7062).
#[test]
fn small_caps_take_eighty_percent_of_the_size_rounded_to_the_half_point() {
crate::test_fonts();
let width = |text: &str, f: &dyn Fn(&mut wordcraft_doc::props::CharProps)| {
let pl = para_with(text, f);
let line = &pl.lines[0];
(line.c0..line.c1).map(|k| pl.clusters[k].adv).sum::<f32>()
};
for (size, small) in [(16.0_f32, 13.0_f32), (14.0, 11.0), (12.0, 9.5)] {
let small_caps = width("xxxxxxxxxx", &|c| {
c.small_caps = Some(true);
c.size = Some(size);
});
let capitals = width("XXXXXXXXXX", &|c| c.size = Some(small));
assert!((small_caps - capitals).abs() < 0.01, "{size} pt Small Caps draws capitals at {small} pt: {small_caps} vs {capitals}");
let spaces = width("x x", &|c| {
c.small_caps = Some(true);
c.size = Some(size);
}) - width("xx", &|c| {
c.small_caps = Some(true);
c.size = Some(size);
});
let plain = width("x x", &|c| c.size = Some(small)) - width("xx", &|c| c.size = Some(small));
assert!((spaces - plain).abs() < 0.01, "{size} pt Small Caps spaces are {small} pt spaces: {spaces} vs {plain}");
}
}
/// A Small Caps line of lowercase letters is as tall as the same line without Small Caps: the
/// small capitals are drawn at 80% of the size, but the line is measured at the full size, as in
/// Word (#7063).
#[test]
fn a_small_caps_line_of_lowercase_is_as_tall_as_without_small_caps() {
crate::test_fonts();
let text = "only lowercase letters here";
let line = |f: &dyn Fn(&mut wordcraft_doc::props::CharProps)| para_with(text, f).lines[0].clone();
let plain = line(&|c| c.bold = Some(false));
let small = line(&|c| c.small_caps = Some(true));
assert!((small.height - plain.height).abs() < 0.01, "line height: Small Caps {} vs plain {}", small.height, plain.height);
assert!((small.baseline - plain.baseline).abs() < 0.01, "baseline: Small Caps {} vs plain {}", small.baseline, plain.baseline);
}
/// A caps run in a symbol font draws each code as its symbol: ß never becomes two glyphs (#1581).
#[test]
fn caps_in_a_symbol_font_never_expand_characters() {
@@ -19460,10 +19209,6 @@ fn negative_offset_floats_in_a_paragraph_pushed_down_by_a_wrapping_float_stay_on
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
@@ -19861,54 +19606,6 @@ fn a_floating_table_placed_by_an_offset_takes_its_indent_before_word_2013_only()
assert!((text_x(15, Some(-5.4)) - (margin + 0.25 + 5.4)).abs() < 0.01, "mode 15, indent: {}", text_x(15, Some(-5.4)));
}
/// #8517: a floating right-to-left table placed by an offset has its left edge at the offset in
/// every mode, whatever its first cell's margins, its indent or its left border (measured in
/// Word for Windows: with `w:tblpX` 1 inch from the margin and cells of left 10 / right 2 pt,
/// the leftmost cell's text is 10 pt in from 144 in modes 14 and 15, with or without a 36 pt
/// indent or an 8 pt left border). A left-to-right one still moves out by its first cell's left
/// margin before Word 2013.
#[test]
fn a_floating_right_to_left_table_has_its_edge_at_its_offset() {
crate::test_fonts();
use wordcraft_doc::para::Anchor;
use wordcraft_doc::props::TableFloat;
let left_edge = |mode: u32, rtl: bool, indent: Option<f32>, border: bool| {
let mut t = Table::new(1, 2, 300.0);
t.props.fixed = true;
t.props.bidi_visual = rtl;
t.props.indent = indent;
t.props.cell_margins = Some([0.0, 10.0, 0.0, 2.0]);
if border {
t.props.borders = Some(Borders { left: Some(Border::single(8.0)), ..Default::default() });
}
t.props.float = Some(TableFloat { h_rel: Anchor::Margin, v_rel: Anchor::Paragraph, x: 72.0, ..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()
.filter_map(|i| match i {
Placed::Cell { rect, .. } => Some(rect.x),
_ => None,
})
.fold(f32::INFINITY, f32::min)
};
let offset = 72.0 + 72.0;
for mode in [14, 15] {
for indent in [None, Some(36.0)] {
for border in [false, true] {
let x = left_edge(mode, true, indent, border);
assert!((x - offset).abs() < 0.01, "mode {mode}, indent {indent:?}, border {border}: {x}");
}
}
}
assert!((left_edge(14, false, None, false) - (offset - 10.0)).abs() < 0.01, "left to right, mode 14");
}
/// 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.
-34
View File
@@ -199,40 +199,6 @@ fn east_asian_theme_slot_overrides_inherited_named_font() {
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();
@@ -101,34 +101,6 @@ 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(&para, 0).id(), serif.id(), "lower-case letter stays in the run's font");
assert_eq!(face_at(&para, 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();
+37
View File
@@ -1167,3 +1167,40 @@ fn a_page_reference_into_nested_text_boxes_stops_where_layout_does() {
let output = layout(&d, &mut LayoutCache::new(), &LayoutOptions { output_page_refs: true, ..Default::default() });
assert_eq!(shown_in(&output, 0, StoryRef::Body), ["2", "2", "9"]);
}
/// Word's exact margins: a negative top (bottom) margin starts (ends) the body at its size from
/// the page edge even when the header (footer) is taller, and the two overlap (ECMA-376
/// §17.6.11, `w:pgMar` below zero; DOC `dyaTop` / `dyaBottom`), so the same text fits on fewer
/// pages. Positive margins stay "at least": a taller header or footer pushes the body.
#[test]
fn negative_margins_are_exact_and_let_the_header_and_footer_overlap_the_body() {
crate::test_fonts();
let make = |top: f32, bottom: f32| {
let mut d = Document::from_text(&"Body line\n".repeat(100));
d.last_section.page_w = 595.3;
d.last_section.page_h = 841.9;
d.last_section.margin_top = top;
d.last_section.margin_bottom = bottom;
d.last_section.header = 36.0;
d.last_section.footer = 36.0;
let head = d.add_part(PartKind::Header, paras("Header line", 6));
let foot = d.add_part(PartKind::Footer, paras("Footer line", 6));
d.last_section.headers.default = Some(head);
d.last_section.footers.default = Some(foot);
let l = lay(&d);
let body = extent(&l.pages[0].items, StoryRef::Body).unwrap();
let header = extent(&l.pages[0].header, StoryRef::Part(head)).unwrap();
let footer = extent(&l.pages[0].footer, StoryRef::Part(foot)).unwrap();
(l.pages.len(), body, header, footer)
};
let (pages, body, header, footer) = make(-60.0, -60.0);
assert!(header.1 > 60.0 && footer.0 < 841.9 - 60.0, "the bands reach past the margins: {header:?} {footer:?}");
assert!((body.0 - 60.0).abs() < 0.5, "the body starts at the exact top margin, over the header: {body:?}");
assert!(
body.1 <= 841.9 - 60.0 + 0.01 && body.1 > footer.0,
"the body runs down to the exact bottom margin, over the footer: {body:?} {footer:?}"
);
let (at_least_pages, at_least_body, at_least_header, at_least_footer) = make(60.0, 60.0);
assert!(at_least_body.0 >= at_least_header.1 - 0.01 && at_least_body.1 <= at_least_footer.0 + 0.01, "{at_least_body:?}");
assert!(pages < at_least_pages, "exact margins: {pages} pages, at least: {at_least_pages}");
}
+1 -1
View File
@@ -21,7 +21,7 @@ pub(crate) fn unturned_sect(s: &SectionProps, body_top: f32) -> SectionProps {
v.page_w = s.page_h;
v.page_h = s.page_w;
v.gutter = 0.0;
let (top, right, bottom, left) = (body_top, s.margin_right, s.margin_bottom, s.margin_left + s.gutter);
let (top, right, bottom, left) = (body_top, s.margin_right, s.margin_bottom.abs(), s.margin_left + s.gutter);
// The unturned frame's (u, v) lands at (W - v, u) for `Down` and (v, H - u) for `Up`: its
// top edge is the real right edge (left for `Up`), its left edge the real top (bottom).
match s.text_direction {
+1 -4
View File
@@ -304,9 +304,6 @@ 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))
{
@@ -412,7 +409,7 @@ impl Exporter<'_> {
p.text_without(&dropped)
}
/// The structure entry for a paragraph on this page (created on first sight, in reading order).
/// The structure entry for a paragraph (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;
-1
View File
@@ -70,7 +70,6 @@ pub use export::{export, export_layout};
use exporter::Exporter;
#[cfg(test)]
use glyphs::{baseline, cluster_ends, left_to_right, split_clusters, visual_order};
pub use metadata::reads_as_date;
#[cfg(test)]
use metadata::{civil, parse_iso};
pub use options::{PdfError, PdfOptions, WATERMARK_MAX_CHARS};
-9
View File
@@ -32,15 +32,6 @@ pub(crate) fn metadata(doc: &Document, opts: &PdfOptions) -> Metadata {
m
}
/// Whether `s` is a date this writer can put in a PDF.
///
/// A caller that pins the creation date has to ask the question this writer will ask, because a
/// value it cannot read falls back to the clock below and the export stops being reproducible
/// (noted in review).
pub fn reads_as_date(s: &str) -> bool {
parse_iso(s).is_some()
}
type Civil = (i64, u8, u8, u8, u8, u8);
/// `YYYY-MM-DD[THH:MM[:SS]]…` → civil time.
-138
View File
@@ -4004,141 +4004,3 @@ fn header_and_footer_link_annotations_are_tagged_on_every_page() {
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");
}
/// Neighbouring table cells carrying the same link URL keep separate Link elements, MCIDs, and
/// OBJRs inside their own TD cells (both in RTL tables and when a right-aligned first cell puts
/// the two runs within one em of each other).
#[test]
fn table_cell_links_with_same_target_stay_in_their_own_cells() {
use hayro_syntax::object::{Array, Dict, Name, Object};
use wordcraft_doc::props::{Align, TableProps};
use wordcraft_doc::{Cell, Row, Table};
let link_props = CharProps { link: Some("https://example.com".into()), ..Default::default() };
let make_cell = |text: &str, align: Option<Align>| {
let mut p = Paragraph::with_text(text, link_props.clone());
p.props.align = align;
Cell { blocks: vec![para_block(p)], ..Cell::empty() }
};
for (name, bidi_visual, first_align) in [("rtl", true, None), ("ltr-right-aligned", false, Some(Align::Right))] {
let row = Row { cells: vec![make_cell("First", first_align), make_cell("Second", None)], ..Default::default() };
let table = Table {
props: TableProps { bidi_visual, cell_margins: Some([0.0, 5.4, 0.0, 5.4]), ..Default::default() },
grid: vec![120.0, 120.0],
rows: vec![row],
..Default::default()
};
let mut d = Document::new();
d.body = vec![Arc::new(Block::Table(table))];
let bytes = export(&d, &PdfOptions { compress: false, tagged: true, ..Default::default() }).unwrap();
let pdf = hayro_syntax::Pdf::new(bytes).unwrap();
let annots = pdf.pages()[0].raw().get::<Array>(b"Annots").expect("page Annots");
let annot_ids: Vec<String> = annots.iter::<Dict>().map(|a| format!("{:?}", a.obj_id().expect("indirect annot"))).collect();
assert_eq!(annot_ids.len(), 2, "{name}: expected two link annotations, got {annot_ids:?}");
let root = pdf.xref().get::<Dict>(pdf.xref().root_id()).unwrap();
let struct_tree = root.get::<Dict>(b"StructTreeRoot").expect("StructTreeRoot");
fn children<'a>(dict: &Dict<'a>) -> Vec<Object<'a>> {
match dict.get::<Object>(b"K") {
Some(Object::Array(a)) => a.iter::<Object>().collect(),
Some(other) => vec![other],
None => Vec::new(),
}
}
fn collect_links(d: &Dict, out: &mut Vec<(bool, Option<String>)>) {
if d.get::<Name>(b"S").is_some_and(|s| s.as_ref() == b"Link") {
let mut has_mcid = false;
let mut objr = None;
for item in children(d) {
match item {
Object::Number(_) => has_mcid = true,
Object::Dict(o) if o.get::<Name>(b"Type").is_some_and(|t| t.as_ref() == b"OBJR") => {
objr = o.get::<Dict>(b"Obj").and_then(|obj| obj.obj_id()).map(|id| format!("{id:?}"));
}
_ => {}
}
}
out.push((has_mcid, objr));
}
for item in children(d) {
if let Object::Dict(c) = item {
collect_links(&c, out);
}
}
}
fn collect_tds(dict: &Dict, out: &mut Vec<Vec<(bool, Option<String>)>>) {
if dict.get::<Name>(b"S").is_some_and(|s| s.as_ref() == b"TD") {
let mut cell_links = Vec::new();
collect_links(dict, &mut cell_links);
out.push(cell_links);
return;
}
for item in children(dict) {
if let Object::Dict(c) = item {
collect_tds(&c, out);
}
}
}
let mut tds = Vec::new();
collect_tds(&struct_tree, &mut tds);
assert_eq!(tds.len(), 2, "{name}: expected 2 TD cells, got {tds:?}");
assert_eq!(tds[0].len(), 1, "{name}: first TD should hold 1 Link: {tds:?}");
assert_eq!(tds[1].len(), 1, "{name}: second TD should hold 1 Link: {tds:?}");
assert!(tds[0][0].0 && tds[1][0].0, "{name}: both cell Links must hold an MCID: {tds:?}");
let objr0 = tds[0][0].1.as_deref().expect("first TD Link OBJR");
let objr1 = tds[1][0].1.as_deref().expect("second TD Link OBJR");
assert_ne!(objr0, objr1, "{name}: cells must reference distinct OBJR annotations: {tds:?}");
assert!(annot_ids.iter().any(|id| id == objr0) && annot_ids.iter().any(|id| id == objr1), "{name}: OBJRs must match page Annots");
}
}
/// 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");
}
+2 -2
View File
@@ -17,7 +17,7 @@ craft = { workspace = true, features = [
"text-find", "web-api", "web-host", "window",
] }
craft-html = { workspace = true }
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
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 }
@@ -77,7 +77,7 @@ craft-ui-test-kit = { workspace = true }
craft = { workspace = true, features = ["ui-testing"] }
[build-dependencies]
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", features = ["subset"] }
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", features = ["subset"] }
serde_json = { workspace = true }
toml = "1"
+24 -24
View File
@@ -86,7 +86,7 @@ fn synthetic_session() -> Session {
}
let mut doc = Document::from_text(&text);
for i in (0..1156).step_by(20) {
doc.format_paragraphs(&Pos::body(i, 0), &Pos::body(i, 0), &|p| p.style = Some("Heading1".into())).expect("synthetic: heading style");
let _ = doc.format_paragraphs(&Pos::body(i, 0), &Pos::body(i, 0), &|p| p.style = Some("Heading1".into()));
}
let mut table = Table::new(250, 8, 468.0);
@@ -97,7 +97,7 @@ fn synthetic_session() -> Session {
cell.props.width = w;
}
}
doc.insert_block(StoryRef::Body, &Path::top(50), Block::Table(table)).expect("synthetic: table");
let _ = doc.insert_block(StoryRef::Body, &Path::top(50), Block::Table(table));
for img_idx in 0..16_u8 {
let mut rgba = image::RgbaImage::new(256, 256);
@@ -109,31 +109,31 @@ fn synthetic_session() -> Session {
255,
]);
}
let png = wordcraft_geom::picture::encode_png(&image::DynamicImage::ImageRgba8(rgba)).expect("synthetic: image encoding");
let key = doc.add_media(png, "png");
let block_idx = 2 + usize::from(img_idx) * 2;
doc.insert_object(
&Pos::body(block_idx, 0),
InlineObject::Image {
media: key,
w: 144.0,
h: 144.0,
alt: format!("Synthetic image {img_idx}"),
float: Default::default(),
crop: [0.0; 4],
fx: Default::default(),
ole: None,
},
&Default::default(),
)
.expect("synthetic: image");
if let Ok(png) = wordcraft_geom::picture::encode_png(&image::DynamicImage::ImageRgba8(rgba)) {
let key = doc.add_media(png, "png");
let block_idx = 2 + usize::from(img_idx) * 2;
let _ = doc.insert_object(
&Pos::body(block_idx, 0),
InlineObject::Image {
media: key,
w: 144.0,
h: 144.0,
alt: format!("Synthetic image {img_idx}"),
float: Default::default(),
crop: [0.0; 4],
fx: Default::default(),
ole: None,
},
&Default::default(),
);
}
}
let mut session = Session::new(doc);
session.run("review.trackChanges", &json!({"enabled": true})).expect("synthetic: track changes on");
session.run("caret.set", &json!({"pos": {"story": "body", "path": [0], "off": 0}})).expect("synthetic: caret");
session.run("text.insert", &json!({"text": "Tracked prefix "})).expect("synthetic: tracked insertion");
session.run("review.trackChanges", &json!({"enabled": false})).expect("synthetic: track changes off");
let _ = session.run("review.trackChanges", &json!({"enabled": true}));
let _ = session.run("caret.set", &json!({"pos": {"story": "body", "path": [0], "off": 0}}));
let _ = session.run("text.insert", &json!({"text": "Tracked prefix "}));
let _ = session.run("review.trackChanges", &json!({"enabled": false}));
session
}
-2
View File
@@ -138,8 +138,6 @@ impl WordApp {
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(),
+9 -11
View File
@@ -54,19 +54,17 @@ const GATED_UI_COMMANDS: &[(&str, &str)] = &[
];
/// Word feature catalog entries whose command is not yet registered in `registry`: each gets a
/// 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])> + '_ {
/// 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)> + '_ {
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, [tab, group]))
(registry.get(id).is_none() && seen.insert(id)).then_some((id, feature))
})
}
@@ -118,7 +116,7 @@ impl CommandStatesCache {
.chain(GATED_UI_COMMANDS.iter().map(|(id, _)| *id))
.map(|id| (id, CommandRef::new(id), None))
.collect();
let unimplemented = unimplemented_catalog_commands(&registry).map(|(id, ..)| (id, CommandRef::new(id), None)).collect();
let unimplemented = unimplemented_catalog_commands(&registry).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() }
@@ -219,9 +217,9 @@ impl WordApp {
for (id, label) in GATED_UI_COMMANDS {
defs.push(CommandDef::new(CommandRef::new(*id), tl!(*label), Scope::app()));
}
for (id, feature, path) in unimplemented_catalog_commands(&registry) {
for (id, feature) in unimplemented_catalog_commands(&registry) {
if seen.insert(id) {
defs.push(CommandDef::new(CommandRef::new(id), tl!(feature), Scope::app()).with_path(path.map(str::to_owned).into()));
defs.push(CommandDef::new(CommandRef::new(id), tl!(feature), Scope::app()));
}
}
// Word's Alt chords (Alt+Q, Alt+F7, Ctrl+Alt+1…) fire while the person types in the page:
+12 -36
View File
@@ -8,7 +8,7 @@ use super::{
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, paste_picture};
use crate::colors;
/// The document's own save stamps: zoom, last-modified-by, created, modified and revision.
type SaveStamps = (Option<wordcraft_doc::Zoom>, String, String, String, u32);
@@ -44,10 +44,6 @@ impl WordApp {
{
return Ok(result);
}
if id == "ui.quit" {
self.clear_command_targets(id);
return Ok(json!({"quit": self.quit()}));
}
// Undo and Redo act on whole steps: a SmartArt typing run still open is folded into its one step first,
// or Undo would take back only the last keystroke of it.
if matches!(id, "edit.undo" | "edit.undoTo" | "edit.redo") {
@@ -77,14 +73,12 @@ impl WordApp {
}
// All ordinary Paste controls use the same system clipboard formats.
let mut params = params;
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,
};
if let Some(r) = system_clipboard::fill(self, id, &mut params) {
return r;
}
let applied = applied_font(id, &params);
let previous = std::mem::replace(&mut self.user_origin, true);
let r = if bitmap_if_empty { self.execute_command(id, params, true) } else { self.execute_user(id, params) };
let r = 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()) {
@@ -154,10 +148,6 @@ 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);
@@ -287,17 +277,11 @@ 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, &params) } else { self.session.run(id, &params) };
// 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());
let r = if self.ime_origin {
self.session.run_ime(id, &params).map_err(|e| e.to_string())
} else {
self.session.run(id, &params).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
@@ -875,16 +859,8 @@ impl WordApp {
};
return Some(self.answer_save_changes(answer));
}
// Programmatic calls (`execute`, control channel, MCP) never open the Save prompt:
// unsaved work needs `{"force": true}`, as `app.quit` does (#8709, #8793).
// The app menu's Quit (⌘Q) runs through `WordApp::run`, which calls `self.quit()`.
"ui.quit" => {
if let Some(e) = crate::control::quit_refused(self, p) {
return Some(Err(e.into()));
}
self.quit_requested = true;
json!({"quit": true})
}
// 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!({})
+15 -7
View File
@@ -69,12 +69,7 @@ pub(crate) fn page_rulers(app: &mut WordApp, ui: &mut Ui, out: &craft::pages::ui
// A section whose columns `column_drag` refuses shows its gaps without grips.
let gaps_draggable = cg.as_ref().is_none_or(|cg| super::column_ruler::draggable(&cg.sect));
let mut margins = Margins::uniform(0.0);
margins.top = f64::from(sect.margin_top);
margins.bottom = f64::from(sect.margin_bottom);
margins.left = f64::from(sect.margin_left);
margins.right = f64::from(sect.margin_right);
let edges = PageEdges::new(margins);
let edges = page_edges(&sect);
let mirrored = app.session.doc.settings.mirror_margins && page.number.is_multiple_of(2);
let unit = DocUnit::new(unit_kind(app.session.units()), 96.0);
let kind = ruler_align(app.canvas.tab_kind).unwrap_or_default();
@@ -260,8 +255,21 @@ fn indent_params(shown: &RulerValues, v: &RulerValues, col_x: f32, w: f32) -> Op
(!p.is_empty()).then_some(Value::Object(p))
}
/// The page's margins as the ruler shows and clamps them. An exact (negative) top or bottom margin (#7107) counts at
/// its size, where the layout puts the body's edge: it is shown there, and a drag of the opposite edge keeps an inch
/// of text beside it, as `layout.margins` checks it. Only a moved edge is sent back ([`margin_params`]), so the exact
/// margin stays exact unless it is the one dragged.
pub(super) fn page_edges(sect: &wordcraft_doc::section::SectionProps) -> PageEdges {
let mut margins = Margins::uniform(0.0);
margins.top = f64::from(sect.margin_top.abs());
margins.bottom = f64::from(sect.margin_bottom.abs());
margins.left = f64::from(sect.margin_left);
margins.right = f64::from(sect.margin_right);
PageEdges::new(margins)
}
/// `layout.margins` params for the margins `v` moved from `shown`.
fn margin_params(shown: &PageEdges, v: &PageEdges) -> Option<Value> {
pub(super) fn margin_params(shown: &PageEdges, v: &PageEdges) -> Option<Value> {
let (a, b) = (&shown.margins, &v.margins);
let mut p = Map::new();
for (key, was, now) in [("left", a.left, b.left), ("right", a.right, b.right), ("top", a.top, b.top), ("bottom", a.bottom, b.bottom)] {
+36
View File
@@ -137,6 +137,42 @@ fn dragging_the_bottom_margin_on_the_ruler_keeps_the_view_and_follows_the_pointe
assert_eq!(h.state().session.undo_depth(), depth + 1, "one undo step for the drag");
}
/// #7107: an exact (negative) top or bottom margin counts at its size on the vertical ruler, so a
/// drag of the opposite edge keeps an inch of text beside it and `layout.margins` accepts it, and
/// the exact margin, not dragged, stays exact.
#[test]
fn ruler_margin_drags_clamp_against_an_exact_opposite_margin() {
use crate::canvas::rulers::{margin_params, page_edges};
use craft::pages::ui::{MarginEdge, MarginRules, dragged_margin};
let s = wordcraft_doc::section::SectionProps {
page_w: 612.0,
page_h: 792.0,
margin_left: 72.0,
margin_right: 72.0,
margin_top: -72.0,
margin_bottom: -72.0,
gutter: 0.0,
..Default::default()
};
let rules = MarginRules::new((612.0, 792.0), page_edges(&s));
assert_eq!(dragged_margin(MarginEdge::Bottom, 72.0, &rules).points, 792.0 - 72.0 - 72.0);
assert_eq!(dragged_margin(MarginEdge::Top, 720.0, &rules).points, 792.0 - 72.0 - 72.0);
// Through the command: the clamped value fits beside the exact top margin, which stays exact.
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
app.session.doc.last_section.margin_top = -72.0;
let sect = wordcraft_engine::cmd::page::sect(&app.session);
let shown = page_edges(&sect);
let moved = shown.with(dragged_margin(MarginEdge::Bottom, 72.0, &MarginRules::new((f64::from(sect.page_w), f64::from(sect.page_h)), shown)));
let p = margin_params(&shown, &moved).expect("the bottom margin moved");
assert!(p.get("top").is_none(), "the exact top margin is not sent: {p}");
app.run("layout.margins", p).unwrap();
let after = wordcraft_engine::cmd::page::sect(&app.session);
assert_eq!(after.margin_top, -72.0);
assert!(after.page_h - after.margin_top.abs() - after.margin_bottom >= 72.0 - 0.01);
}
/// #1878: in Multiple Pages both rulers belong to the caret's page: the margin splitters of the
/// horizontal ruler lie over that page's width and the vertical ruler's over its height, and
/// they follow the caret to another page of the row and to the next row.
+2 -5
View File
@@ -181,7 +181,7 @@ pub enum Target {
/// What the pick is remembered as.
remember: Remember,
},
/// Run nothing: the pick is only reported in [`ColorPick::picked`].
/// Run nothing: the pick is only reported in [`ColorPick::picked`] (a gradient stop's colour).
Pick,
}
@@ -258,10 +258,7 @@ fn cell_shading(table: &wordcraft_doc::Table, cells: impl IntoIterator<Item = (u
/// differs across the selection, or cannot be read (a picture's icon colour is not stored).
fn current_of(app: &mut WordApp, target: &Target) -> Option<Rgb> {
use wordcraft_doc::InlineObject;
let Target::Run { cmd, params, at, .. } = target else { return None };
if let Some(c) = params.pointer(at).and_then(Value::as_str).and_then(parse) {
return Some(c);
}
let Target::Run { cmd, .. } = target else { return None };
let s = &app.session;
let shapes = |o: &InlineObject| matches!(o, InlineObject::Shape { .. }) || o.is_canvas();
let objects = || wordcraft_engine::cmd::objects::target_objects(s, shapes).into_iter().map(|(_, o)| o);
+1 -1
View File
@@ -21,7 +21,7 @@
mod handler;
mod screenshots;
pub(crate) use handler::{close_refused, quit_refused};
pub(crate) use handler::close_refused;
pub use handler::{handle, inspect};
#[cfg(test)]
mod doc_tests;
+2 -6
View File
@@ -47,12 +47,8 @@ pub fn inspect(app: &mut WordApp, ctx: &egui::Context) -> Value {
let rect = |r: egui::Rect| [r.left(), r.top(), r.width(), r.height()];
// PLAN: assumed `Label::as_str` and `Tone: Debug` (sh.A3 `status_message`, expiry handled there)
let status = app.status_message().map(|m| json!({"text": m.text.as_str(), "tone": format!("{:?}", m.tone).to_lowercase()}));
// `prefs` stores recent documents as `~/...`; clients pass these entries to `file.open`, which
// needs the full path (#8421).
let mut ui = app.prefs();
ui.recent.clone_from(&app.ui.recent);
json!({
"ui": ui,
"ui": app.prefs(),
"view": app.session.view,
"windows": app.session.windows,
"proofing": app.spelling_review,
@@ -129,7 +125,7 @@ const COMMENT_UNSAVED: &str = "a comment is still being edited: finish it first,
/// Quitting closes every open document, so unsaved work needs the same explicit `force` as
/// `file.close` rather than going silently (#1268, #3274). The interactive path asks about
/// each document in turn; a programmatic call never prompts, so it refuses.
pub(crate) fn quit_refused(app: &WordApp, params: &Value) -> Option<&'static str> {
fn quit_refused(app: &WordApp, params: &Value) -> Option<&'static str> {
let force = params.get("force").and_then(Value::as_bool) == Some(true);
if force {
return None;
+6 -38
View File
@@ -126,28 +126,17 @@ fn closing(form: &str, force: Option<&Value>, target: u64, background: bool) ->
("file.closeDocument", Value::Object(params))
}
"app.quit" => ("app.quit", Value::Object(params)),
"ui.quit" => ("ui.quit", Value::Object(params)),
"engine.execute:ui.quit" => ("engine.execute", json!({"command": "ui.quit", "params": Value::Object(params)})),
_ => ("file.close", Value::Object(params)),
}
}
/// Every way to close or quit over the control channel keeps unsaved work unless `force` is the
/// boolean true, for the active document and for one in the background (#1268, #3274, #8793).
/// boolean true, for the active document and for one in the background (#1268, #3274).
#[test]
fn programmatic_close_guard_covers_every_form() {
let ctx = crate::test_harness::context();
let forces: [(Option<Value>, bool); 4] = [(None, false), (Some(json!("yes")), false), (Some(json!(1)), false), (Some(json!(true)), true)];
let forms = [
"engine.execute",
"command",
"file.close",
"engine.execute:closeDocument",
"file.closeDocument",
"app.quit",
"ui.quit",
"engine.execute:ui.quit",
];
let forms = ["engine.execute", "command", "file.close", "engine.execute:closeDocument", "file.closeDocument", "app.quit"];
for form in forms {
for background in [false, true] {
// A direct `file.close` method has no `doc`.
@@ -165,14 +154,13 @@ fn programmatic_close_guard_covers_every_form() {
let what = format!("{form} background={background} {params}: {r}");
assert_eq!(r["ok"], json!(*accepted), "{what}");
if *accepted {
if matches!(form, "app.quit" | "ui.quit" | "engine.execute:ui.quit") {
if form == "app.quit" {
assert!(a.quit_requested, "{what}");
} else {
assert!(!a.session.is_open(first), "{what}");
}
} else {
assert!(!a.quit_requested && a.session.is_open(first), "{what}");
assert!(prompt(&a).is_none() && a.closing.is_none(), "{what}");
}
}
}
@@ -184,13 +172,7 @@ fn programmatic_close_guard_covers_every_form() {
#[test]
fn programmatic_close_keeps_a_save_the_picker_hasnt_finished() {
let ctx = crate::test_harness::context();
for (method, params) in [
("engine.execute", json!({"command": "file.close"})),
("file.close", json!({})),
("app.quit", json!({})),
("ui.quit", json!({})),
("engine.execute", json!({"command": "ui.quit"})),
] {
for (method, params) in [("engine.execute", json!({"command": "file.close"})), ("file.close", json!({})), ("app.quit", json!({}))] {
let (mut a, saves) = web_picker_app();
a.run("file.close", json!({})).unwrap();
let r = a.run("ui.saveChanges", json!({"answer": "save"})).unwrap();
@@ -385,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. 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.
/// 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` and `ui.text` (while `ui.drag` moved to `{from, to}`).
#[test]
fn every_method_the_protocol_doc_lists_is_answered() {
let doc = include_str!("../../../../docs/control-protocol.md");
@@ -411,17 +393,3 @@ fn every_method_the_protocol_doc_lists_is_answered() {
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));
}
/// #8421: `ui.inspect` lists recent documents as full paths that `file.open` can open, not the
/// `~/...` form the preferences file keeps.
#[test]
fn inspect_lists_recent_documents_as_full_paths() {
let full = crate::prefs::expand_recent_path("~/Documents/report.docx");
assert!(!full.starts_with('~'), "the test needs a home folder");
assert_eq!(crate::prefs::contract_recent_path(&full), "~/Documents/report.docx", "the stored form is contracted");
let mut a = app();
a.ui.recent = vec![full.clone()];
let (req, _rx) = ControlRequest::new("ui.inspect", json!({}));
let Reply::Done(r) = control::handle(&mut a, &installed(), &req) else { panic!("ui.inspect answers at once") };
assert_eq!(r["result"]["ui"]["recent"], json!([full]), "{r}");
}
@@ -339,26 +339,6 @@ 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,16 +55,7 @@ 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 {
// 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 {
match body_field(app, "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,50 +238,6 @@ 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]
+21 -3
View File
@@ -25,6 +25,10 @@ pub(crate) struct PaperLabels {
/// `layout.size` keeps the section's orientation; `layout.orientation` then turns the page and
/// its margins to what the dialog shows. A size equal to the opened one (either way round,
/// within 0.01 pt) doesn't run `layout.size`.
/// An exact (negative) top or bottom the dialog still shows as the section has it, on a page
/// not turned, is left out of `layout.margins`, which keeps a side left out (a negative given
/// counts as zero): changing another side keeps it exact, as the ruler does. The fit checks
/// count an exact margin at its size.
pub(super) fn page_layout_commands(
app: &WordApp,
(paper, was): ((f32, f32), (f32, f32)),
@@ -33,6 +37,20 @@ pub(super) fn page_layout_commands(
) -> Result<Vec<(String, Value)>, &'static str> {
use wordcraft_engine::cmd::page::{MARGINS_DONT_FIT, margins_fit, sect};
let cur = sect(&app.session);
let kept = |shown: f32, now: f32| landscape == cur.landscape && now < 0.0 && shown == now;
let (keep_top, keep_bottom) = (kept(m.0, cur.margin_top), kept(m.1, cur.margin_bottom));
let sizes = |(t, b, l, r): (f32, f32, f32, f32)| (t.abs(), b.abs(), l, r);
// `layout.margins` with the sides it sets: all but the exact ones kept.
let set_margins = |(t, b, l, r): (f32, f32, f32, f32)| {
let mut v = json!({"top": t, "bottom": b, "left": l, "right": r});
for (keep, k) in [(keep_top, "top"), (keep_bottom, "bottom")] {
if keep && let Some(o) = v.as_object_mut() {
o.remove(k);
}
}
("layout.margins".to_string(), v)
};
let m = sizes(m);
if !margins_fit(paper, m, cur.gutter) {
return Err(MARGINS_DONT_FIT);
}
@@ -41,8 +59,8 @@ pub(super) fn page_layout_commands(
let new_size = (w0 - w1).abs() >= 0.01 || (h0 - h1).abs() >= 0.01;
let size = ("layout.size".to_string(), json!({"width": paper.0, "height": paper.1}));
let orientation = ("layout.orientation".to_string(), json!({"value": if landscape { "landscape" } else { "portrait" }}));
let margins = ("layout.margins".to_string(), json!({"top": m.0, "bottom": m.1, "left": m.2, "right": m.3}));
let old_margins = (cur.margin_top, cur.margin_bottom, cur.margin_left, cur.margin_right);
let margins = set_margins(m);
let old_margins = sizes((cur.margin_top, cur.margin_bottom, cur.margin_left, cur.margin_right));
Ok(if !new_size || margins_fit(turned(cur.landscape, paper), old_margins, cur.gutter) {
let mut v = if new_size { vec![size] } else { Vec::new() };
v.extend([orientation, margins]);
@@ -50,7 +68,7 @@ pub(super) fn page_layout_commands(
} else if margins_fit(turned(landscape, (cur.page_w, cur.page_h)), m, cur.gutter) {
vec![orientation, margins, size]
} else {
vec![orientation, ("layout.margins".to_string(), json!({"top": 0.0, "bottom": 0.0, "left": 0.0, "right": 0.0})), size, margins]
vec![orientation, set_margins((0.0, 0.0, 0.0, 0.0)), size, margins]
})
}
+21 -33
View File
@@ -763,39 +763,6 @@ fn paragraph_dialog_changes_direction() {
// ---------------------------------------------------------------- Font
#[test]
fn font_dialog_shows_the_east_asian_theme_face_and_only_replaces_it_when_edited() {
use std::sync::Arc;
use wordcraft_doc::props::ThemeFont;
use wordcraft_doc::{Path, StoryRef};
let mut app = app_with("Example");
let doc = &mut app.session.doc;
Arc::make_mut(&mut doc.styles).default_chr.font_ea = Some("Times New Roman".into());
doc.passthrough.insert("wordcraft:theme.fonts".into(), Arc::new(b"minor\tface\tea\tExample CJK Face\n".to_vec()));
let para = doc.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
para.format(0, para.len(), &|props| props.font_ea_theme = Some(ThemeFont::MinorEastAsia)).unwrap();
app.session.touch();
app.run("select.all", json!({})).unwrap();
let mut h = app_harness(app);
h.run_steps(2);
apply_font(&mut h, |form| {
assert!(form.asian);
assert_eq!(form.font_ea, "Example CJK Face");
});
let props = char_props_at_start(h.state());
assert_eq!(props.font_ea_theme, Some(ThemeFont::MinorEastAsia), "unchanged OK keeps the theme slot");
assert!(props.font_ea.is_none(), "the inherited name stays inherited");
apply_font(&mut h, |form| {
form.font_ea = "Times New Roman".into();
});
let props = char_props_at_start(h.state());
assert_eq!(props.font_ea.as_deref(), Some("Times New Roman"));
assert!(props.font_ea_theme.is_none(), "choosing the inherited name makes it an explicit replacement");
}
#[test]
fn font_dialog_sets_the_asian_and_latin_fonts_separately() {
// #505: the Asian text font box and the Latin text font box each set their own font, and
@@ -1173,6 +1140,27 @@ fn page_setup_refuses_margins_that_dont_fit_and_applies_smaller_ones_first() {
assert_eq!((s.page_w.round(), s.page_h.round(), s.margin_left.round(), s.margin_top.round()), (100.0, 500.0, 18.0, 18.0));
}
/// #7108: an exact (negative) top or bottom margin Page Setup's OK didn't change stays exact
/// when another side changes, as with the ruler and `layout.margins`; one changed in the
/// dialog takes the value shown.
#[test]
fn page_setup_keeps_an_exact_margin_it_didnt_change() {
let mut h = app_harness(app_with("Page"));
h.run_steps(2);
let sect = |h: &egui_kittest::Harness<'_, WordApp>| wordcraft_engine::cmd::page::sect(&h.state().session);
{
let x = &mut h.state_mut().session.doc.last_section;
(x.margin_top, x.margin_bottom) = (-60.0, -40.0);
}
page_setup(&mut h, |f| f.margins.left = 80.0);
assert!(!is_open(h.state(), "pageSetup"));
let x = sect(&h);
assert_eq!((x.margin_top, x.margin_bottom, x.margin_left), (-60.0, -40.0, 80.0), "the exact margins kept");
page_setup(&mut h, |f| f.margins.top = 50.0);
let x = sect(&h);
assert_eq!((x.margin_top, x.margin_bottom, x.margin_left), (50.0, -40.0, 80.0), "the changed one set, the other kept");
}
/// #1433: one OK in Page Setup is one undo step, whichever order its commands run in (the
/// size first; the margins first; margins of 0 in between), and Undo restores the section.
#[test]
+11 -76
View File
@@ -13,7 +13,7 @@ use craft::theme::Srgba;
use craft::theme::variant::Tone;
use craft::ui::buttons::Button;
use craft::ui::choice::{Checkbox, Radio, RadioGroup};
use craft::ui::contract::{Bind, Entry, Outcome as _, Props as _, Show as _, ShowContainer as _, Trigger, clicked};
use craft::ui::contract::{Bind, Entry, Outcome as _, Props as _, Show as _, ShowContainer as _, Trigger};
use craft::ui::form::{Field, SliderField};
use craft::ui::layout_components::Stack;
use craft::ui::menu::Menu;
@@ -509,9 +509,7 @@ fn solid(app: &mut WordApp, ui: &mut Ui, theme: &[Rgb], color: Rgb, transparency
let mut hex = color.hex();
let label: Label = tl!("Color").into();
let picked = color_field(ui, &label, &mut hex, &ColorFieldEmpty::NoColor, &palette);
if picked.more_colors {
colors::open_for(app, &Target::cmd("shape.fill"), Some(color), craft::color_ui::ui::ColorPickerTab::Standard);
} else if picked.changed
if picked.changed
&& let Some(n) = Rgb::parse(&hex)
{
let _ = app.run("shape.fill", json!({"color": n.hex()}));
@@ -679,22 +677,17 @@ fn gradient(app: &mut WordApp, ui: &mut Ui, g: &Gradient) {
// PLAN: the framework has no public kept-value write; the open flag goes through the saved value
let was: bool = saved_value(&ctx, &key);
let mut open = was || editor.color_requested.is_some();
let stop_at = editor.color_requested.as_ref().map(|c| c.index).or(match editor.selected {
Some(StopRef::Color(at)) => Some(at),
_ => None,
});
let stop_target = match stop_at.filter(|&at| at < g.stops.len()) {
Some(at) => Target::at("shape.fill", shape_fill::params(Some(&Fill::Gradient(Arc::new(g.clone())))), &format!("/gradient/stops/{at}/color")),
None => Target::Pick,
};
let mut close_popover = false;
let mut chosen = None;
Popover::new(tl!("Stop color"), Bind::bound(&mut open)).opened_by(editor.response()).show(ui, |ui, _| {
let pick = colors::palette(ui, app, stop_target.clone());
if pick.picked.is_some() || clicked(&pick.response) {
close_popover = true;
}
// PLAN: assumed colors::palette(ui, app, Target::Pick) -> ColorPick (ribbon-w11, rb.A4)
chosen = colors::palette(ui, app, Target::Pick).picked;
});
if close_popover {
if let (Some(color), Some(StopRef::Color(at))) = (chosen, editor.selected) {
let mut stops = stops_of(g);
if let Some(stop) = stops.color.get_mut(at) {
stop.color = srgba(color, stop.color.a);
apply(app, Some(&with_stops(g, &stops)));
}
open = false;
}
if open != was {
@@ -1073,64 +1066,6 @@ mod tests {
assert_eq!(stroke(h.state()), Some(wordcraft_doc::Rgb(255, 0, 0)));
}
/// Selecting More Colors… in the Solid fill color picker applies the custom color via `shape.fill`
/// while preserving transparency.
#[test]
fn format_shape_pane_solid_more_colors_applies_fill() {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
a.run("insert.shape", json!({"kind": "rectangle"})).unwrap();
a.run("shape.fill", json!({"color": "112233", "transparency": 35})).unwrap();
a.run("view.formatShapePane", json!({"value": true})).unwrap();
let mut h = harness(a);
h.run_steps(4);
h.query_all_by_role_and_label(egui::accesskit::Role::Button, "Color #112233").last().expect("solid fill color field").click();
h.run_steps(3);
h.get_by_label("More Colors…").click();
h.run_steps(3);
let dialog = h.state_mut().dialog_host.get_mut::<craft::color_ui::ui::ColorPickerDialog>().expect("Colors dialog opened");
assert_eq!(dialog.opening().map(|p| super::rgb_of(p.color)), Some(wordcraft_doc::Rgb(0x11, 0x22, 0x33)));
dialog.set_color(craft::color_ui::ui::PickedColor::rgb(craft::theme::Srgba::rgb(0.0, 1.0, 0.0)));
let ctx = h.ctx.clone();
assert!(h.state_mut().dialog_host.confirm::<craft::color_ui::ui::ColorPickerDialog>(&ctx));
crate::dialogs::host::settle(h.state_mut(), &ctx);
assert_eq!(fill(h.state()), Some(Fill::Solid { color: wordcraft_doc::Rgb(0, 255, 0), transparency: 35.0 }));
}
/// Selecting More Colors… from a gradient stop's color popover applies the custom color to that
/// stop while keeping the other stops and gradient settings intact.
#[test]
fn format_shape_pane_gradient_stop_more_colors_applies_stop_color() {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
a.run("insert.shape", json!({"kind": "rectangle"})).unwrap();
let stops = json!([{"pos": 0, "color": "FFFFFF", "transparency": 20}, {"pos": 100, "color": "156082", "transparency": 50}]);
a.run("shape.fill", json!({"gradient": {"stops": stops, "angle": 90}})).unwrap();
a.run("view.formatShapePane", json!({"value": true})).unwrap();
let mut h = harness(a);
h.run_steps(4);
h.get_by_label("Color stop 2 of 2").click();
h.run_steps(3);
h.key_press(egui::Key::Enter);
h.run_steps(3);
h.get_by_label("More Colors…").click();
h.run_steps(3);
let dialog = h.state_mut().dialog_host.get_mut::<craft::color_ui::ui::ColorPickerDialog>().expect("Colors dialog opened");
assert_eq!(dialog.opening().map(|p| super::rgb_of(p.color)), Some(wordcraft_doc::Rgb(0x15, 0x60, 0x82)));
dialog.set_color(craft::color_ui::ui::PickedColor::rgb(craft::theme::Srgba::rgb(1.0, 0.0, 0.0)));
let ctx = h.ctx.clone();
assert!(h.state_mut().dialog_host.confirm::<craft::color_ui::ui::ColorPickerDialog>(&ctx));
crate::dialogs::host::settle(h.state_mut(), &ctx);
let Some(Fill::Gradient(g)) = fill(h.state()) else { panic!("expected gradient fill, got {:?}", fill(h.state())) };
assert_eq!(g.stops.len(), 2);
assert_eq!(g.stops[0].color, wordcraft_doc::Rgb(0xFF, 0xFF, 0xFF));
assert_eq!(g.stops[1].color, wordcraft_doc::Rgb(255, 0, 0));
assert_eq!(g.stops[1].transparency, 50.0);
}
fn png_data() -> String {
let img = image::RgbaImage::from_fn(20, 10, |x, y| {
if x > 2 && x < 17 && y > 2 && y < 7 { image::Rgba([200, 30, 30, 255]) } else { image::Rgba([255, 255, 255, 255]) }
-103
View File
@@ -1652,109 +1652,6 @@ 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())
.filter(|b| b.x0 >= picker.x0 && b.x1 <= picker.x1 && b.y0 >= picker.y0 && b.y1 <= picker.y1)
.collect::<Vec<_>>()
};
let search = *in_picker("Search").first().expect("the picker's Search field");
// The picker has two Close buttons: one in its title bar, above the Search field, and the footer's below
// it. Which comes first in the tree depends on the node ids, so take the footer's by position.
let close = in_picker("Close")
.into_iter()
.filter(|b| b.y0 >= search.y1)
.min_by(|a, b| a.y0.total_cmp(&b.y0))
.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]
-4
View File
@@ -437,10 +437,6 @@ 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,
-2
View File
@@ -187,7 +187,6 @@ pub(crate) fn members(app: &mut WordApp, ui: &mut Ui, preview: bool) {
Row::new().gap(Gap::Tight).show(ui, |ui, _| {
let mut family = st.get("font").and_then(Value::as_str).unwrap_or("").to_string();
let picked = crate::widgets::font_box::font_box(ui, app, tl!("Font").to_string(), &mut family);
crate::ribbon::common::painted_ibeam_over(ui, &picked.edit.response);
follow_list(app, preview, &picked.preview, |f| Some(("format.font".to_string(), json!({"name": f}))));
if let Some(f) = &picked.picked {
let _ = app.run("format.font", json!({"name": f}));
@@ -201,7 +200,6 @@ pub(crate) fn members(app: &mut WordApp, ui: &mut Ui, preview: bool) {
let mut text = size.clone();
// `text` is rebuilt from the selection on every pass: the box keeps what is typed until Enter.
let combo = ComboBox::new(tl!("Font Size").to_string(), Bind::bound(&mut text).policy(EditPolicy::OnCommit), &sizes).show(ui);
crate::ribbon::common::painted_ibeam_over(ui, &combo.edit.response);
follow_list(app, preview, &combo.preview, |v| {
v.trim().parse::<f64>().ok().map(|x| ("format.size".to_string(), json!({"size": x})))
});
+3 -5
View File
@@ -448,8 +448,7 @@ impl PreferencesModel for OptionsModel<'_> {
vec![
GroupSpec::new(Some(tl!("Save documents")), {
// The browser can't write to the user's files, so AutoSave can't be turned on there (#176).
let autosaving = !browser && app.autosave && app.autosave_choice != Some(false);
let row = b("save.autosave", tl!("AutoSave documents you have saved in WordCraft"), autosaving).enabled(!browser);
let row = b("save.autosave", tl!("AutoSave documents you have saved in WordCraft"), app.autosave && !browser).enabled(!browser);
vec![row.help(if browser {
&s.autosave_reason
} else {
@@ -667,9 +666,8 @@ 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 clears a document opt-out so ticking it re-enables saved
// documents; an opened-only file's switch approval (`Some(true)`) is kept.
if v && self.app.autosave_choice == Some(false) {
// The Options row explicitly enables AutoSave for the active saved document.
if v && self.app.saved_here() {
self.app.autosave_choice = None;
}
}

Some files were not shown because too many files have changed in this diff Show More