Compare commits

...
Author SHA1 Message Date
Martin BallandClaude Opus 5.5 8d9031e6c9 Release: version 0.20.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx
2026-12-03 20:25:25 +00:00
autocraft-bot[bot] 8d75a12b48 Merge pull request #4207 2026-12-03 19:02:47 +00:00
autocraft-bot[bot] ba179cb3d1 Merge pull request #8643 2026-12-03 19:02:47 +00:00
autocraft-bot[bot] 6d27b1a4a1 Merge pull request #8644 2026-12-03 19:02:47 +00:00
autocraft-bot[bot] faf55fad76 Merge pull request #8629 2026-12-03 19:02:47 +00:00
Martin BallandClaude Opus 5.5 30458a8e0b Status bar: a sliver of the page above isn't the page in view (#7149 item 7) (#7154)
* viewed_page: #7149 item 7, a sliver of the page above is not the page in view

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* viewed_page: #7149 item 7, measure the sliver gap to the page below in Columns and Two Up

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* viewed_page: #7149 item 7, find the page below by band top, not by column offset

The gap to measure is the one to the first later page whose shown band starts at or below this
page end. An incomplete last row in Columns and a Two Up cover (page 0 alone in row 0) have no
page columns entries later, which gave a gap of 0. Hide White Space still resolves to its seam.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* viewed_page: #7149 item 7, measure the sliver gap from the row's bottom

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* fix(canvas): measure the page-in-view gap to the next spread's real top (#7149)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

* test(canvas): build the next-spread-top regression from the real Two Up layout (#7149)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

---------

Co-authored-by: Claude Sonnet 5.5 <[email protected]>
2026-12-03 19:02:47 +00:00
autocraft-bot[bot] 6d2f0d7759 All three failing checks (ubuntu gate, Windows and macOS Print) fail on
All three failing checks (ubuntu gate, Windows and macOS Print) fail on one test, the_autosave_knob_sits_right_when_on_and_mirrors_right_to_left (chrome/tests.rs:812). Cause: the test sets session.path and autosave_path to fake a file saved here, then toggles file.autosave on, off and on again. Turning it off clears autosave_path, and turning it on again needs the file to count as read from disk (read_from == session.path, per autosave_switch_block). The test never set read_from, so the second 'on' returned the NotSavedHere refusal. A real save sets both fields (note_file_on_disk), so the test setup was wrong, not the code. Fix: the test now also sets a.read_from = Some(path); its assertions are unchanged. The failing test passes in the pod, cargo fmt --check is clean, and clippy on wordcraft-ui-egui --all-targets is clean apart from an existing unused-dependency warning (egui_extras). I did not run the full suite.
2026-12-03 18:36:52 +00:00
batistalucasv 53b22e61f2 Layout: anchor space-before Top-and-Bottom band to first line's original top 2026-12-03 15:10:13 -03:00
batistalucasv f641b83a2f layout: filter Top-and-Bottom exclusions by applied space before 2026-12-03 15:08:49 -03:00
autocraft-bot[bot] 49ef461bc3 Merge pull request #6634
With AutoCraft's conflict resolution b76731e9.
2026-12-03 17:57:56 +00:00
autocraft-bot[bot] 2bfc68964b Merge pull request #8636 2026-12-03 17:57:56 +00:00
batistalucasv ddb8fa164b layout: move ligature kerning pair to its last cluster
A ligature glyph sits on the head cluster, so Cluster::kern recorded the ligature's kerning pair with the following glyph on the head cluster rather than on the last cluster of the ligature. Move head.kern to the last cluster in split_ligature_advances so a forced character wrap inside the ligature does not subtract a pair that belongs after the whole ligature, and a line ending after the ligature drops that pair.

Closes #8618.
2026-12-03 14:57:56 -03:00
autocraft-bot[bot] 8d9a614e15 Merge pull request #8635 2026-12-03 17:53:45 +00:00
batistalucasv 0e4d52a5aa Layout: remove stray doc comment above body_lines 2026-12-03 14:53:45 -03:00
autocraft-bot[bot] 9abd324244 Merge pull request #8628 2026-12-03 17:45:03 +00:00
autocraft-bot[bot] 77dc3e75b9 Merge pull request #8630 2026-12-03 17:45:03 +00:00
batistalucasv 8082743bb8 docs(layout-parity): remove duplicate stale footnote and table rows (#8587) 2026-12-03 14:45:03 -03:00
batistalucasv 4f4827a7c0 Tests: continuous section first-page rule for header/footer tables and footers (#8580) 2026-12-03 14:45:02 -03:00
batistalucasv 54cf516adf Fields: CREATEDATE inserted into an opened file without a creation date shows today (#8612)
Fixes #8612. When update_fields_in evaluates CREATEDATE for an opened file whose creation date is empty or unreadable, it now preserves only non-empty cached results and formats today's date when the field's result is empty (such as right after insert.field).
2026-12-03 14:44:57 -03:00
autocraft-bot[bot] 3db40dabac Merge pull request #8382 2026-12-03 16:56:56 +00:00
autocraft-bot[bot] 4ea1fe935a Merge pull request #8610 2026-12-03 16:56:56 +00:00
autocraft-bot[bot] 9a2d6902f4 Merge pull request #2340 2026-12-03 16:56:56 +00:00
autocraft-bot[bot] 8a2e47f8c3 CI failed at the clippy step because number_formats in crates/doc/src/
CI failed at the clippy step because `number_formats` in crates/doc/src/section.rs had a cognitive complexity of 31 against a limit of 30. The seven assertions this PR added pushed it over: Hex for 10, 15, 16 and 255, CardinalText and OrdinalText for 1,000,000, and CardinalText for 2,000,000,000. I moved those assertions, unchanged, into a new `hex_and_large_number_text` test, as the maintainer asked. No test was weakened, removed or changed in what it asserts. Fmt, clippy and tests did not run this time: the shell dropped on three consecutive calls. A search of the file shows the new test at line 1016 and no Hex assertion left in `number_formats`. The same edit passed `rustfmt --check`, `cargo clippy --offline -p wordcraft-doc --all-targets -- -D warnings` and `cargo test -p wordcraft-doc section` (12 passed) in an earlier run on an earlier merge of main.
2026-12-03 16:56:56 +00:00
autocraft-bot[bot] c4cd11c5ff Merge main (1580f46c) into the pull request
Resolved the only conflict, in markup_pdf_takes_the_track_changes_option

Resolved the only conflict, in markup_pdf_takes_the_track_changes_option_colours in crates/engine/src/tests.rs. The default branch already pins the document creation date in that test (2026-01-01, with an explanatory comment), so I kept its lines and dropped the PR's duplicate pin (2024-01-01). The PR's change is now redundant. No conflict markers remain. I did not build or run tests, and did not run cargo fmt --check, because the edit only removed the PR's side of the conflict and the markers.
2026-12-03 16:34:56 +00:00
batistalucasv 3a7a3b4b95 test(engine): cover first-character toggles on text boxes and column selections (#8589) 2026-12-03 12:50:18 -03:00
autocraft-bot[bot] 1ec83a1a2f Merge pull request #6578
With AutoCraft's conflict resolution 0de83145.
2026-12-03 15:10:05 +00:00
autocraft-bot[bot] 72ef3083e7 Merge pull request #8210
With AutoCraft's conflict resolution d24d3034.
2026-12-03 15:10:05 +00:00
autocraft-bot[bot] 27672b2448 Merge pull request #4614
With AutoCraft's conflict resolution 7c41404c.
2026-12-03 15:10:05 +00:00
autocraft-bot[bot] 67d5297c08 Merge pull request #8599 2026-12-03 15:10:05 +00:00
Mat Strange 4c1dfa6367 Say what Ctrl+K does with a column selection
The doc said the link lands at the block's top-left corner; it says now
that insert.link inserts the link text there and leaves the block's own
text unlinked, which is what the command does (#8602).

Refs #8581
2026-12-03 15:10:05 +00:00
Mat Strange ccf405de52 Document the Ctrl+K rule for a column selection
The typing-parity doc now says that a column (block) selection isn't one
line of text, so Text to display shows <<Selection in Document>> and the
block keeps its text, and that the link still lands at the block's
top-left corner.

Refs #8581
2026-12-03 14:58:12 +00:00
Mat Strange da072c3e74 Treat a column selection as not one line of text
A column (block) selection over the wrapped lines of one paragraph has both
its ends in that paragraph and no break characters, so one_line_selection
took it for one line of text: Text to display showed the block flattened
and an edit to it retyped the whole run between the corners, text outside
the block included.

one_line_selection now returns None while a column selection is active, so
the dialog shows <<Selection in Document>> and the selection keeps its text.

Refs #8581
2026-12-03 14:42:52 +00:00
autocraft-bot[bot] 1580f46cee Merge pull request #7454 2026-12-03 14:35:38 +00:00
autocraft-bot[bot] ab58acfa09 Merge pull request #7191 2026-12-03 14:35:38 +00:00
autocraft-bot[bot] c013dff332 Merge pull request #8593 2026-12-03 14:35:38 +00:00
autocraft-bot[bot] e976e6aa69 Merge pull request #8343
With AutoCraft's conflict resolution aa696738.
2026-12-03 14:35:38 +00:00
autocraft-bot[bot] f03da28fb5 Merge pull request #8592 2026-12-03 14:35:38 +00:00
reubgrandMuse Lane 48f0ad7496 validate: Fail DrawingML arcTo radii in the measured decimal spellings Word refuses (#8231) (#8461)
* wip(#8231): partial implementation recovered from the quota-killed Neon lane — unreviewed, audit against log/BRIEF.md before building on it

* validate: delimit the measured DrawingML coordinate evidence

* validate: type-check DrawingML custom geometry literals (#8231)

* validate: restrict DML-COORDINATE Observed failure to decimal a:arcTo radii (#8231)

* validate: scope DML-COORDINATE Observed Fail to measured lexical set (#8231)

* validate: keep unresolvable DML entities as warnings and preserve errors past warning cap (#8231)

* validate: check DML integer schema bounds and cap overflow error notes (#8231)

* validate: narrow DML-COORDINATE Error to measured MCE and Transitional contexts (#8231)

* validate: replace MCE Requires family prefix with explicit Word capability allowlist (#8231)

* validate: withhold DML-COORDINATE Error inside unresolved AlternateContent (#8231)

* validate: record r1/r2 measurements in EVIDENCE.md and strengthen Strict test (#8231)

* validate: match Word MCE capability URIs directly to satisfy clippy and observation audit (#8231)

* validate: enforce three-state MCE selection, unresolved part profile, and Warning precedence (#8231)

* validate: add profile-by-branch decision-table and Round 4 regression tests (#8231)

---------

Co-authored-by: Muse Lane <muse@localhost>
2026-12-03 15:35:38 +01:00
Mat Strange d48ca8d3ec PDF: only the top header rows are tagged TH 2026-12-03 13:52:13 +00:00
Mat Strange 425f6d990d Layout: a page break before after a page-anchored frame keeps one page
The fresh-column check gained a page-anchored frame's wrap area in #8521,
to say whether moving on gains room. The page-break-before decision used
the same check to ask whether anything was placed above on the page, and a
frame outside the flow is not content above it: a document that opens with
an address or title frame and then a heading styled with page break before
gained a page that held only the frame.

The two meanings are now separate: the break asks only whether the
paragraph is at the top of the page's text, and the frame's wrap area
moves the text below or beside the frame as before.

Fixes #8577
2026-12-03 13:39:49 +00:00
autocraft-bot[bot] e3878d2b83 Merge pull request #7276 2026-12-03 12:29:58 +00:00
autocraft-bot[bot] a1b04eaa52 Merge pull request #8584 2026-12-03 12:29:58 +00:00
autocraft-bot[bot] f98d9c2515 Merge pull request #6337
With AutoCraft's conflict resolution f89481c5.
2026-12-03 12:29:58 +00:00
Zaxaerith d8f1a821c7 docs: scope the animation override to desktop CPU adapters 2026-12-03 20:29:58 +08:00
autocraft-bot[bot] b400a7bbb8 Merge pull request #8582 2026-12-03 12:29:58 +00:00
Zaxaerith c84c1b9e44 Merge remote-tracking branch 'upstream/main' into docs/animation-control-effective-state 2026-12-03 20:29:22 +08:00
Martin BallandClaude Opus 5.5 bee380b2e8 test(print): fewer UI steps in the Print buttons guard (#7171)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx
2026-12-03 11:41:55 +00:00
autocraft-bot[bot] dc266c5e55 Batch 265 failed to compile the PR's new test dictate_icon_geometry_and_
Batch 265 failed to compile the PR's new test dictate_icon_geometry_and_rendering in crates/ui-egui/src/icons.rs: it built DrawEnv without the `mark` field that main's pinned craft-libs (d73e274) added after the PR branched. The test now paints through craft::ui::testing::style::paint_frame, which builds the env inside craft, instead of a DrawEnv struct literal. I removed the unused Draw/DrawEnv/PaintRecord import and the record variable. The assertions and sizes are unchanged; only how the test paints changed. An earlier fix that added `mark: Default::default()` was refused by AutoCraft's checks with E0560, so I avoided the struct literal. In the pod, fmt --check, clippy -D warnings on wordcraft-ui-egui --all-targets, and the dictate test all pass. The egui_extras warning at Cargo.toml:28 is only a manifest warning and did not fail clippy, so I left it.
2026-12-03 11:37:18 +00:00
autocraft-bot[bot] 95bfd5af43 The gate's clippy step failed because the merge with main left `place_pa
The gate's clippy step failed because the merge with main left `place_page_text_frame` in crates/layout/src/flow.rs calling `ctx.para_labelled` with 5 arguments. The PR changed the signature to take `space_before: f32`, so the call didn't compile. I passed `0.0` there, as the other calls with no preceding flow do. `cargo clippy --workspace --all-targets -- -D warnings` and `cargo fmt --check` are now clean. `cargo test -p wordcraft-layout` gives 888 passed and 4 failed. The four are hyphenation tests, which the PR description says also fail on clean main on the author's machine. The craft-i18n checkout is missing from this workspace, which I take to be the cause. I only confirmed that `auto_hyphenation_breaks_long_words` fails with 'no hyphenated lines' and did not run the other three on their own. They were not in the CI log, because the test step was skipped after clippy failed.
2026-12-03 11:18:19 +00:00
Martin BallandClaude Opus 5.5 c7bb1c9636 Merge origin/main into fix/7171-print-options-clipped
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx
2026-12-03 11:17:09 +00:00
Zaxaerith 463552ac36 test(dialogs): check the To caption in both mail merge dialogs 2026-12-03 17:32:18 +08:00
Bra1nZ 870bbffddf Layout: tests for the turned-text fallbacks (#6528 follow-up)
The at-least probe in layout_table takes the minimum height as the turned
text's length only while the lines wrapped to it fit across the column, and
it is skipped inside a text box. Neither branch had a test.

- turned_text_in_a_narrow_cell_keeps_its_unwrapped_length: the lines at the
  minimum height would stack wider than the cell, so the text keeps its
  unwrapped length and the row grows instead of spilling sideways.
- a_text_box_skips_the_min_height_probe_for_turned_text: the same table in a
  text box keeps the unwrapped length even where the probe would fit.

Both fail with their branch removed and pass on main (layout 881 passed; the
three hyphenation tests fail on a clean main too, for lack of dictionaries
in this environment).
2026-12-03 12:25:14 +03:00
Zaxaerith a2d8bbdb4d docs: explain the effective animation control state 2026-12-03 16:18:51 +08:00
autocraft-bot[bot] 4f6dbbb5fd Merge main (98e61780) into the pull request 2026-12-03 07:58:05 +00:00
midasmatterhorn f5c9da1b70 Merge main into fix/issue-7143-topbottom-space-before 2026-12-03 09:38:18 +03:00
autocraft-bot[bot] a6d1534889 Part 1: the Outline view fuzz in outline_level_changes_are_undoable (c
Part 1: the Outline view fuzz in `outline_level_changes_are_undoable` (crates/engine/src/tests.rs) now keeps the `Session::run` result instead of discarding it. It builds the registry once and asserts `!caught_panic(&reg, &r)`, with the command id, the junk input and the result in the failure message. The message format matches the one in `hostile_params_never_panic`. `cargo fmt --check` and `cargo clippy` on `wordcraft-engine` are clean. `outline_level_changes_are_undoable` and `caught_panic_flags_a_command_that_panics` both pass. I did not run the full engine test suite.
2026-12-03 05:35:02 +00:00
midasmatterhorn 1de5a93974 layout: check Top-and-Bottom floats only within applied space before 2026-12-03 04:59:11 +03:00
Muse f1e8793b7a tests(engine): pin document creation date in markup PDF colour test 2026-12-02 09:35:19 -06:00
dfgodvan f55fabaac6 Merge main into w1/line-end-kern
# Conflicts:
#	crates/layout/src/tests.rs
#	docs/layout-parity.md
2026-12-02 16:54:16 +03:00
dfgodvan 78b0a6929c Layout: the right-tab rule applies to right tabs only, and not beside a float
A decimal tab keeps main's fit: its digits after the point run on to the right
of the stop, so taking text up to the stop let a number run past the margin.
Where a floating object narrows the line, text after a right tab keeps to the
narrowed edge instead of running into the object.
2026-12-02 16:05:51 +03:00
dfgodvan 870bec1839 Merge main into fix/right-tab-beyond-indent 2026-12-02 16:02:02 +03:00
fluorineandClaude Haiku 5.5 aeba356814 xtask: gate the stats test imports that only unix tests use
On Windows the one test that uses Counts and walk is compiled out, so
clippy -D warnings fails with unused imports.

Co-Authored-By: Claude Haiku 5.5 <[email protected]>
2026-11-30 14:39:43 -04:00
batistalucasv d46ecf3ab1 test(icons): verify stroke clearance and rendered bounds for dictate icon 2026-11-30 01:43:28 -03:00
FredApps 869160692f Merge origin/main into fix/fuzz-panics-autosave 2026-11-28 10:16:45 +07:00
batistalucasv dd2d40a5f5 test(icons): verify dictate.svg viewBox, attribute boundary, and 16-22 pt rendering 2026-11-27 08:36:52 -03:00
batistalucasv ee05e88fa0 Address review feedback on dictate icon test (#7450) 2026-11-27 00:27:40 -03:00
batistalucasv 81aae389b3 Icons: adjust Dictate microphone icon geometry to prevent capsule cutting across U-stand (#7450) 2026-11-27 00:25:15 -03:00
Martin BallandClaude Opus 5.5 8803a95a2d #7171: Print settings buttons stay clear of the scroll bar and the preview
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 02:18:15 +00:00
ljkx 7777eba6e4 Merge remote-tracking branch 'origin/main' into fix/createdate-keeps-date
# Conflicts:
#	docs/layout-parity.md
2026-11-23 03:04:48 +01:00
midasmatterhorn 4722d7d2fe A Top-and-Bottom object in a paragraph's space before pushes it down
Exclusions were relative to the first line's top and dropped when they
ended above it, so an object wholly inside the paragraph's space
before never moved the paragraph; and when an object reached into the
first line, the line moved to the object's bottom without the space
before being laid out again under it. Exclusion filtering keeps
Top-and-Bottom areas above the first line now, and the line breaker
looks one space before above its top for them and starts the line
below the object plus the space before. Objects in the previous
paragraph's space after stay where they were.
2026-11-22 00:02:35 +03:00
jayzed80 f674177095 Layout: binary-search the run when checking East Asian font coverage (#6591) 2026-11-19 04:34:29 +00:00
jayzed80 cb0aeadd2f Merge remote-tracking branch 'upstream/main' into fix/autospace-eastasia-font-6591
# Conflicts:
#	crates/layout/src/para/grid.rs
#	docs/layout-parity.md
2026-11-18 23:35:02 +00:00
FredApps d789f82465 Merge remote-tracking branch 'origin/main' into pr-2340 2026-11-18 21:05:53 +07:00
FredApps 6da8a86a41 Merge remote-tracking branch 'origin/main' into fix/section-hex-numformat-and-cardinal-millions 2026-11-18 20:21:58 +07:00
Martin Ball af9dca95de Merge branch 'main' into fix/right-tab-beyond-indent 2026-11-17 16:59:34 +01:00
Martin Ball 1392290eec Merge branch 'main' into fix/right-tab-beyond-indent 2026-11-17 08:53:46 +01:00
Martin Ball 3310e9f5ee Merge branch 'main' into fix/right-tab-beyond-indent 2026-11-17 05:33:56 +01:00
ljkx 554a7d689e #6331: CREATEDATE reads a creation date without seconds
W3CDTF allows hh:mm without seconds (2019-05-05T12:00Z), which
parse_from_rfc3339 refuses, so such a file kept its cached result.
created_at now reads that form too, with Z or an offset.
2026-11-17 04:32:55 +01:00
ljkx 2c32076416 #6331: layout-parity status line and revision row for CREATEDATE at the top 2026-11-17 04:32:54 +01:00
ljkx 19b8dfece6 Merge remote-tracking branch 'upstream/main' into fix/createdate-keeps-date 2026-11-17 04:32:14 +01:00
jayzed80 104fa6133d Layout: no automatic space beside an ideograph its run's installed East Asian font lacks (#6591)
Word adds no autoSpaceDE/autoSpaceDN room when the run's w:eastAsia font
has no ideographs, though a substituted face draws them. A declared font
that isn't installed keeps the space.
2026-11-14 06:50:23 +00:00
jayzed80 b687f1cd6f Address review: keep separated link runs in separate Link elements (#6464) 2026-11-14 01:18:00 +00:00
jayzed80 8f8bec4ad7 Tag PDF link annotations with Link and OBJR (#6464) 2026-11-13 23:04:30 +00:00
dfgodvan 7fd2dc9127 layout: a letter ending a line keeps the half of its kerning pair with the letter before
A shaper splits a pair from an old-style kern table between its two letters, half in the first
one's advance and half in the second one's advance and offset. The kerning kept for the line-end
measure (a letter ending a line inside a word is measured without its pair with the next) took the
second letter's half for its pair with the next letter, so a letter after a kerned pair was measured
wider than it is at the end of a line. Word for Windows, a font with only a kern table: Word set
"...3Vy" of a base64 token on one line, WordCraft moved the "y" on.

Test: a_letter_ending_a_line_keeps_its_pair_with_the_letter_before (fails before this change).
2026-11-12 23:53:33 +03:00
dfgodvan cf0f6876b9 layout: a letter ending a line is measured without its kerning pair with the next
Word lays each line out on its own: a long word broken by letters fits only as far as its letters
fit without the pair they kern with the letter that goes on to the next line. A cell's width swept
a twip at a time in Word for Windows (Times New Roman 10 pt, kerning on): the first 12 letters of
a 15-letter word fit from their width alone, 0.34 pt more than they take with the pair after them,
so narrow cells broke a letter later than Word. Each cluster keeps what kerning added to its
advance; the fit check drops it when a letter follows.

Test: a_word_broken_by_letters_ends_without_its_kerning_pair (fails before this change).
2026-11-12 23:46:48 +03:00
dfgodvan c120c09423 Layout: a right tab past the right indent takes its text up to the stop, as in Word
A TOC entry in Word's TOC styles has a right indent and a right tab with a dot leader at
the margin, past that indent. Word keeps the page number on the entry's line whenever it
fits between the text and the stop, so the number ends past the indent. WordCraft checked
the first character after the tab against the right indent (the tab has no room yet), and
moved the tab and its number to the next line when the text ended less than a digit short
of the indent.

Measured in Word for Mac 16.93 (Times New Roman 12pt, right indent 1cm, stop at the margin):
entries whose text ends 0.4, 1, 2, 3, 4, 5 and 5.8pt short of the indent all keep their dot
leader and number on the line, the number ending at the stop. With a 0.2cm indent the
number stays on the line when 18.7pt are left before the stop and goes to the next line
when 16.7pt are left.

Text after a right or decimal tab now fits while it ends before the stop. The running
shift of the tab also no longer counts the tab's own room as text: it dropped back to
nothing after every second character, so those characters were checked against the
indent as well. A tab whose text is pending starts with no room on the line it goes to.
2026-11-12 23:12:43 +03:00
ljkx 1336bc27cb #6331 review: CREATEDATE in documents from templates, opened files without a date, date-only values
A document made from a template no longer inherits the template's creation
date: it has none until it is saved, so CREATEDATE shows today. A file
opened without a creation date keeps the field's cached result, as one with
an unreadable date already did; only a new, never-saved document uses
today. A date-only creation date (2019-05-05, which W3CDTF allows) shows as
that calendar day in every time zone. The test's expected date for
12:00 UTC now follows the local offset, so it passes east of UTC+12 too.
2026-11-12 14:16:39 +01:00
ljkx a525210f48 #6331: Updating fields keeps CREATEDATE on the document's creation date
CREATEDATE is formatted from the document's creation date (dcterms:created) in local time, not from the clock. A creation date that can't be read keeps the field's result; a document never saved (no creation date yet) still shows today.
2026-11-11 19:03:44 +01:00
VoiceLessQ 3b73a84082 AutoSave: the switch shows a document opened from bytes as blocked
The title bar lifted NotSavedHere whatever read_from said, while set_autosave refused unless the document was read from its path, so the switch of a document opened from bytes looked available and a click did nothing. Both now use autosave_switch_block: the switch shows the block and offers Save As. file.autosave also puts a refusal on the status line, as other commands do, instead of returning early without it.
2026-11-03 17:51:02 -02:00
VoiceLessQ 1603a5f34f AutoSave: only an open that read a file records it
file.open with a null path only asks for the Open picker, and its
result has no alreadyOpen, so the check recorded the shown document's
path as read from disk: a document opened from bytes then passed the
AutoSave switch's check. The path must now be a string and alreadyOpen
false. A data value that isn't a string is ignored by the engine,
which reads the file from disk, so it no longer clears the record.
2026-10-29 16:25:01 -02:00
VoiceLessQ d5239891f6 AutoSave: switching it off holds for that document
The AutoSave preference is shared by all documents, but each keeps its
own go-ahead (the file it may write). Switching AutoSave off cleared
only the preference, so turning it on in another document brought it
back for the first one too, which then wrote its file with its switch
showing off. Switching off now also withdraws the document's go-ahead.
Turning it back on covers the same file again without a save, since
the document was read from or saved to it.
2026-10-29 15:30:43 -02:00
VoiceLessQ 9c7ec843b6 AutoSave: the switch covers only a file the document was read from
file.open with data only names the file (the bytes come with the call),
but the name becomes the document's path, and since #3307 the AutoSave
switch gave the go-ahead to write it. A control-channel caller could
open any bytes under the name of an existing .docx, and turning AutoSave
on then wrote over that file. The window now notes, per document, the
file it was read from or saved to, and the switch's go-ahead needs the
path to be that file. A document opened from bytes still gets AutoSave
after an explicit save.
2026-10-29 15:30:34 -02:00
VoiceLessQ 777fedb14a Engine tests: the fuzz also fails on a panic in a command another ran
Review of #4207. Commands run other commands through Session::run
(outline.promote runs para.promote), and the inner guard names the inner
command: "para.promote panicked: ...". run_junk only looked for the
fuzzed command's own id, so such a panic passed. caught_panic now takes
any registered command's id before " panicked: "; an error that only
echoes those words (developer.control quoting its input) still doesn't
count.
2026-10-29 14:23:50 -02:00
VoiceLessQ 02de1488cb Merge origin/main 2026-10-29 14:21:19 -02:00
VoiceLessQ 9c05751014 Merge origin/main
Main split lib.rs and chrome.rs, so the AutoSave changes now live in app/files.rs, state.rs, tests.rs and chrome/tests.rs.
2026-10-27 16:39:42 -02:00
VoiceLessQ 6d51d93bb6 AutoSave: a value that isn't true or false is an error (#3307)
`file.autosave` read `value` with as_bool and toggled when that gave nothing. Since the switch can now turn AutoSave on for a file only opened here, `{"value":"false"}` on such a file turned it on and gave AutoSave the go-ahead to rewrite it. A missing value still toggles; anything other than a bool is now refused, the way the focus ribbon and other ui commands already do it. Found in review.

Test: turning_autosave_on_covers_a_file_only_opened_here sends "false" as a string and checks AutoSave stays off; it fails with the old parsing.
2026-10-24 21:28:50 -01:00
VoiceLessQ fe69231544 AutoSave: the switch turns it on for a file you opened (#3307)
Opening a saved .docx greyed the AutoSave switch out. Clicking it asked
for Save As, so a file you work on every day needed a save before each
session's AutoSave would cover it.

The rule behind it stays. #151 stopped AutoSave from rewriting a file
that was only opened, because a save drops what the readers don't model
(content controls, charts, SmartArt), and that loss should follow the
user's own choice. Clicking the switch is such a choice.

So a file opened in this window now shows the switch off, not greyed
out, and clicking it (or file.autosave from a script) turns AutoSave on
for that file. Opening alone never rewrites anything. The browser and
lossy-format blocks are unchanged.

Tests: turning_autosave_on_covers_a_file_only_opened_here (open, type,
nothing written; switch on, file written) and
clicking_autosave_on_an_opened_file_turns_it_on (the real title bar,
no Save As). Dropping the go-ahead in set_autosave fails both; keeping
the switch greyed fails the second.
2026-10-24 21:00:37 -01:00
VoiceLessQ dd20b23d4d Engine tests: the command fuzz fails on a panic Session::run caught
hostile_params_never_panic runs every command with junk parameters, but
it threw the result away. Session::run turns a panic inside a command
into Err(Failed("<id> panicked: ...")) and restores the document, so a
command that panicked on junk passed the test: the one check the
never-crash rule points to could not see the panics it exists for. The
Outline view fuzz in outline_level_changes_are_undoable had the same gap.

Both now go through run_junk, which fails on that error. Today no command
panics there (611 commands, 8 junk inputs each), so nothing else changes.

Tests: making edit.repeat panic on null params fails the fuzz with
"edit.repeat panicked: mutation"; before this change the same mutation
passed.
2026-10-24 21:00:37 -01:00
Divyanshu Gupta ab35bfa946 fix(doc): format hex number format as uppercase hex and support millions in cardinal text 2026-10-16 07:27:30 +05:30
62 changed files with 4224 additions and 157 deletions
Generated
+19 -19
View File
@@ -9132,7 +9132,7 @@ dependencies = [
[[package]]
name = "wordcraft"
version = "0.18.1"
version = "0.20.0"
dependencies = [
"craft",
"craft-nightly",
@@ -9159,7 +9159,7 @@ dependencies = [
[[package]]
name = "wordcraft-cli"
version = "0.18.1"
version = "0.20.0"
dependencies = [
"craft-zip",
"image",
@@ -9177,11 +9177,11 @@ dependencies = [
[[package]]
name = "wordcraft-control-key"
version = "0.18.1"
version = "0.20.0"
[[package]]
name = "wordcraft-doc"
version = "0.18.1"
version = "0.20.0"
dependencies = [
"base64 0.23.1",
"craft-codepage",
@@ -9197,7 +9197,7 @@ dependencies = [
[[package]]
name = "wordcraft-docbin"
version = "0.18.1"
version = "0.20.0"
dependencies = [
"cfb",
"craft-doc-binary",
@@ -9209,7 +9209,7 @@ dependencies = [
[[package]]
name = "wordcraft-docx"
version = "0.18.1"
version = "0.20.0"
dependencies = [
"base64 0.23.1",
"cfb",
@@ -9228,7 +9228,7 @@ dependencies = [
[[package]]
name = "wordcraft-engine"
version = "0.18.1"
version = "0.20.0"
dependencies = [
"cfb",
"chrono",
@@ -9266,7 +9266,7 @@ dependencies = [
[[package]]
name = "wordcraft-fonts"
version = "0.18.1"
version = "0.20.0"
dependencies = [
"brotli-decompressor 5.0.3",
"harfrust 0.13.3",
@@ -9281,7 +9281,7 @@ dependencies = [
[[package]]
name = "wordcraft-formats"
version = "0.18.1"
version = "0.20.0"
dependencies = [
"chardetng",
"chrono",
@@ -9311,7 +9311,7 @@ dependencies = [
[[package]]
name = "wordcraft-geom"
version = "0.18.1"
version = "0.20.0"
dependencies = [
"craft-image-codecs",
"craft-tiff",
@@ -9321,7 +9321,7 @@ dependencies = [
[[package]]
name = "wordcraft-layout"
version = "0.18.1"
version = "0.20.0"
dependencies = [
"craft-metafile",
"craft-proof",
@@ -9341,7 +9341,7 @@ dependencies = [
[[package]]
name = "wordcraft-mcp"
version = "0.18.1"
version = "0.20.0"
dependencies = [
"craft",
"craft-mcp-server",
@@ -9355,7 +9355,7 @@ dependencies = [
[[package]]
name = "wordcraft-pdf"
version = "0.18.1"
version = "0.20.0"
dependencies = [
"chrono",
"craft-metafile",
@@ -9376,7 +9376,7 @@ dependencies = [
[[package]]
name = "wordcraft-render"
version = "0.18.1"
version = "0.20.0"
dependencies = [
"craft-metafile",
"image",
@@ -9390,7 +9390,7 @@ dependencies = [
[[package]]
name = "wordcraft-ui-egui"
version = "0.18.1"
version = "0.20.0"
dependencies = [
"cfb",
"chrono",
@@ -9423,7 +9423,7 @@ dependencies = [
[[package]]
name = "wordcraft-validate"
version = "0.18.1"
version = "0.20.0"
dependencies = [
"craft-image-codecs",
"craft-tiff",
@@ -9438,7 +9438,7 @@ dependencies = [
[[package]]
name = "wordcraft-web"
version = "0.18.1"
version = "0.20.0"
dependencies = [
"craft",
"eframe",
@@ -9458,7 +9458,7 @@ dependencies = [
[[package]]
name = "wordcraft-zotero"
version = "0.18.1"
version = "0.20.0"
dependencies = [
"log",
"proptest",
@@ -9676,7 +9676,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
[[package]]
name = "xtask"
version = "0.18.1"
version = "0.20.0"
dependencies = [
"serde",
"serde_json",
+1 -1
View File
@@ -13,7 +13,7 @@ run_slots = 3
test_threads = 4
[workspace.package]
version = "0.18.1"
version = "0.20.0"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
+22 -3
View File
@@ -296,6 +296,7 @@ impl NumFormat {
use crate::cjk_numbers as cjk;
match self {
NumFormat::DecimalZero => format!("{n:02}"),
NumFormat::Hex => format!("{n:X}"),
NumFormat::ThaiNumbers => thai_digits(n),
NumFormat::UpperRoman => roman(n).to_uppercase(),
NumFormat::LowerRoman => roman(n),
@@ -341,7 +342,6 @@ impl NumFormat {
NumFormat::Chosung => cjk::chosung(n),
NumFormat::Decimal
| NumFormat::DecimalHalfWidth
| NumFormat::Hex
| NumFormat::VietnameseCounting
| NumFormat::Hebrew1
| NumFormat::Hebrew2
@@ -496,13 +496,21 @@ pub fn cardinal_text(n: u32) -> String {
let h = format!("{} hundred", words(n / 100));
if n.is_multiple_of(100) { h } else { format!("{h} {}", words(n % 100)) }
}
_ => {
1_000..=999_999 => {
let th = format!("{} thousand", words(n / 1000));
if n.is_multiple_of(1000) { th } else { format!("{th} {}", words(n % 1000)) }
}
1_000_000..=999_999_999 => {
let m = format!("{} million", words(n / 1_000_000));
if n.is_multiple_of(1_000_000) { m } else { format!("{m} {}", words(n % 1_000_000)) }
}
_ => {
let b = format!("{} billion", words(n / 1_000_000_000));
if n.is_multiple_of(1_000_000_000) { b } else { format!("{b} {}", words(n % 1_000_000_000)) }
}
}
}
capitalize(&words(n.min(999_999)))
capitalize(&words(n))
}
/// English ordinal words (`Twenty-First`).
@@ -1004,6 +1012,17 @@ mod tests {
assert_eq!(NumFormat::from_ooxml("klingon"), NumFormat::Decimal, "unknown formats are decimal");
}
#[test]
fn hex_and_large_number_text() {
assert_eq!(NumFormat::Hex.format(10), "A");
assert_eq!(NumFormat::Hex.format(15), "F");
assert_eq!(NumFormat::Hex.format(16), "10");
assert_eq!(NumFormat::Hex.format(255), "FF");
assert_eq!(NumFormat::CardinalText.format(1_000_000), "One Million");
assert_eq!(NumFormat::OrdinalText.format(1_000_000), "One Millionth");
assert_eq!(NumFormat::CardinalText.format(2_000_000_000), "Two Billion");
}
/// #5757: Thai numbers are the decimal number in Thai digits, every digit, at any length.
#[test]
fn thai_numbers_use_thai_digits() {
+2
View File
@@ -342,6 +342,8 @@ pub(crate) fn new_from_template(s: &mut Session, v: &Value) -> CmdResult {
let path = p::req_str(v, "path")?;
let (mut doc, _) = read_document(s, path, v)?;
doc.settings.attached_template = Some(path.to_string());
// A new document: not created when the template was. Saving stamps its creation date.
doc.core.created.clear();
if p::bool(v, "replaceBlank") == Some(true) && s.used_because().is_none() {
s.set_document(doc);
} else {
+5
View File
@@ -92,6 +92,11 @@ const NOT_ONE_LINE: [char; 7] = {
/// The raw text of the selection when it is one run of one paragraph without breaks, pictures or fields.
fn one_line_selection(s: &Session) -> Option<&str> {
// A column (block) selection has both ends in one paragraph but holds a piece of each line it
// covers: it isn't one line of text (#8581).
if s.column_segments().is_some_and(|segs| !segs.is_empty()) {
return None;
}
let (a, b) = s.sel.ordered();
if a.story != b.story || a.path != b.path {
return None;
+35 -2
View File
@@ -402,7 +402,7 @@ pub fn update_fields_in(s: &mut Session, all: bool) -> Result<(), CmdError> {
}
let mut updates: Vec<(usize, String)> = Vec::new();
for (k, o) in p.objects.iter().enumerate() {
let InlineObject::Field { instr, locked: false, .. } = o else { continue };
let InlineObject::Field { instr, result, locked: false, .. } = o else { continue };
// A table formula reads the cells around its own cell again.
if instr.trim_start().starts_with('=') {
if let Some((tp, r, c)) = path.cell()
@@ -422,7 +422,22 @@ pub fn update_fields_in(s: &mut Session, all: bool) -> Result<(), CmdError> {
"DATE" | "TIME" | "CREATEDATE" | "SAVEDATE" | "PRINTDATE" => {
let lang = field_lang(&s.doc, p, k);
let pic = date_picture(instr).unwrap_or_else(|| default_picture(&name, lang.as_deref()));
updates.push((k, text_result(instr, crate::cmd::insert::format_date_in(&pic, lang.as_deref()))));
let created = s.doc.core.created.trim();
// CREATEDATE shows when the document was created (ECMA-376 §17.16.5.11). A new
// document, never saved, has no creation date yet and saving stamps now. A
// file opened without one, or with one that can't be read, keeps any result
// it already has; when inserted with none, it shows today's date (the date
// a save would stamp).
let text = if name == "CREATEDATE"
&& let Some((unix, offset)) = created_at(created)
{
crate::cmd::insert::format_date_at_in(&pic, lang.as_deref(), unix, offset)
} else if name != "CREATEDATE" || result.is_empty() || (created.is_empty() && s.path.is_none()) {
crate::cmd::insert::format_date_in(&pic, lang.as_deref())
} else {
continue;
};
updates.push((k, text_result(instr, text)));
}
"REF" | "PAGEREF" => {
let f = FieldCode::parse(instr);
@@ -572,6 +587,24 @@ fn field_lang(doc: &wordcraft_doc::Document, p: &wordcraft_doc::Paragraph, k: us
doc.styles.resolve_char(p.props.style.as_deref(), p.props_of_char(off)).lang
}
/// A core-properties creation date as seconds since the epoch and the UTC offset to show it at:
/// an instant (`2019-05-05T12:00:00Z`, any offset or fraction, or without the seconds,
/// `2019-05-05T12:00Z`, as W3CDTF allows) at the local offset, or a calendar date (`2019-05-05`)
/// at its own midnight, whatever the time zone. `None` for another form or a date before 1970.
fn created_at(stamp: &str) -> Option<(u64, i64)> {
let instant = chrono::DateTime::parse_from_rfc3339(stamp).ok().or_else(|| {
// `%:z` takes `+01:00` but not `Z`.
let utc = stamp.strip_suffix(['Z', 'z']).map(|t| format!("{t}+00:00"));
chrono::DateTime::parse_from_str(utc.as_deref().unwrap_or(stamp), "%Y-%m-%dT%H:%M%:z").ok()
});
if let Some(t) = instant {
let unix = u64::try_from(t.timestamp()).ok()?;
return Some((unix, crate::cmd::local_offset_secs(unix)));
}
let day = chrono::NaiveDate::parse_from_str(stamp, "%Y-%m-%d").ok()?;
Some((u64::try_from(day.and_hms_opt(0, 0, 0)?.and_utc().timestamp()).ok()?, 0))
}
/// Word's default date or time picture when a field instruction carries no `\@` picture switch.
fn default_picture(name: &str, lang: Option<&str>) -> String {
if name == "TIME" { "h:mm am/pm".into() } else { crate::cmd::insert::default_date_picture(lang).into() }
+70
View File
@@ -506,6 +506,76 @@ fn update_fields_all_covers_every_story() {
s.run("references.updateFields", &json!({"all": "yes"})).unwrap();
}
/// CREATEDATE shows when the document was created (ECMA-376 §17.16.5.11), not today's date.
#[test]
fn createdate_keeps_the_creation_date_on_update() {
let mut s = Session::new(wordcraft_doc::Document::new());
s.doc.core.created = "2019-05-05T12:00:00Z".into();
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#, "result": "2019-05"})).unwrap();
s.run("insert.field", &json!({"instr": "CREATEDATE"})).unwrap();
s.run("references.updateFields", &json!({})).unwrap();
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
// 12:00 UTC is 5 May from UTC-12 to UTC+11:59, the next day east of that.
let unix = 1_557_057_600;
let (_, _, day, _, _) = crate::cmd::local_civil(unix, crate::cmd::local_offset_secs(unix));
assert_eq!(results, ["2019-05".to_string(), format!("5/{day}/2019")]);
assert!(day == 5 || day == 6, "{day}");
// W3CDTF may leave out the seconds; that is the same instant.
for minutes in ["2019-05-05T12:00Z", "2019-05-05T14:00+02:00", "2019-05-05T07:00-05:00"] {
// From another date first, so an unread stamp, which keeps the result, shows.
s.doc.core.created = "2001-02-03".into();
s.run("references.updateFields", &json!({})).unwrap();
assert_eq!(fields(&s)[1].1, "2/3/2001");
s.doc.core.created = minutes.into();
s.run("references.updateFields", &json!({})).unwrap();
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
assert_eq!(results, ["2019-05".to_string(), format!("5/{day}/2019")], "{minutes}");
}
// A date without a time is that calendar day in every time zone.
s.doc.core.created = "2019-06-07".into();
s.run("references.updateFields", &json!({})).unwrap();
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
assert_eq!(results, ["2019-06", "6/7/2019"]);
}
/// A creation date that can't be read leaves the field's result as it was; a document that has
/// never been saved is created now (saving stamps that time as its creation date).
#[test]
fn createdate_without_a_readable_creation_date() {
let mut s = Session::new(wordcraft_doc::Document::new());
s.doc.core.created = "sometime in May".into();
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#, "result": "2019-05"})).unwrap();
assert_eq!(fields(&s)[0].1, "2019-05");
// A file opened without a creation date keeps the result too.
s.doc.core.created.clear();
s.path = Some(std::env::temp_dir().join("opened.docx"));
s.run("references.updateFields", &json!({})).unwrap();
assert_eq!(fields(&s)[0].1, "2019-05");
s.path = None;
s.run("references.updateFields", &json!({})).unwrap();
assert_eq!(fields(&s)[0].1, crate::cmd::insert::format_date("yyyy-MM"));
}
/// Inserting CREATEDATE into an opened file that has no creation date (plain text, Markdown, or a
/// DOCX without `dcterms:created`) shows today's date rather than an empty result, while an
/// existing field with a cached result keeps it.
#[test]
fn createdate_inserted_into_opened_file_without_creation_date() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Notes"));
s.path = Some(std::env::temp_dir().join("notes.txt"));
s.doc.core.created.clear();
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#, "result": "2019-05"})).unwrap();
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#})).unwrap();
let expected = crate::cmd::insert::format_date("yyyy-MM");
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
assert_eq!(results, ["2019-05".to_string(), expected.clone()]);
// An unreadable creation date behaves the same way: cached results stay, empty ones fill in.
s.doc.core.created = "sometime in May".into();
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#})).unwrap();
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
assert_eq!(results, ["2019-05".to_string(), expected.clone(), expected]);
}
#[test]
fn toc_tabs_ignore_nonentries() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Before\nContents\nOld\t9\nAfter"));
@@ -136,6 +136,30 @@ fn a_selected_column_is_edited_cell_by_cell() {
assert_eq!(s.cell_range().map(|r| r.cols), Some((1, 1)), "undo brings the column selection back");
}
/// Toggling a format on a selected table column follows the first character in document order (#8589).
#[test]
fn toggle_on_a_selected_table_column_follows_first_character() {
let toggled = |bold_row: usize| -> Vec<bool> {
let mut s = table_session(3, 3);
fill(&mut s);
let p = cell_pos(&s, bold_row, 1);
s.sel = Selection { anchor: p.clone(), focus: Pos { off: 4, ..p } };
s.run("format.bold", &json!({"value": true})).unwrap();
// Start from the bottom row so the caret is not on row 0.
s.sel = Selection::caret(cell_pos(&s, 2, 1));
s.run("table.selectColumn", &json!({})).unwrap();
s.run("format.bold", &json!({})).unwrap();
for r in 0..3 {
assert!(!bold(&s, r, 0) && !bold(&s, r, 2), "row {r}'s other cells stay plain");
}
(0..3).map(|r| bold(&s, r, 1)).collect()
};
// First row bold, later rows plain: Bold turns off across the column.
assert_eq!(toggled(0), vec![false, false, false]);
// First row plain, middle row bold: Bold turns on across the column.
assert_eq!(toggled(1), vec![true, true, true]);
}
/// Numbering a column numbers its cells as one list, like Word.
#[test]
fn numbering_a_column_makes_one_list() {
+23
View File
@@ -337,6 +337,29 @@ mod tests {
let _ = std::fs::remove_dir_all(&d);
}
/// A document made from a template is created now, not when the template was: it has no
/// creation date until it is saved, so CREATEDATE in it shows today.
#[test]
fn new_from_template_has_no_creation_date_of_its_own_yet() {
let d = scratch("created");
let path = d.join("Dated.dotx");
let mut t = Session::new(wordcraft_doc::Document::new());
t.run("document.setText", &json!({"text": "Dated"})).unwrap();
t.doc.core.created = "2019-05-05T12:00:00Z".into();
crate::io::save_path(&path, &t.doc).unwrap();
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("file.newFromTemplate", &json!({"path": path.to_string_lossy()})).unwrap();
assert_eq!(s.doc.core.created, "");
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy""#, "result": "2019"})).unwrap();
s.run("references.updateFields", &json!({})).unwrap();
assert!(s.doc.plain_text(wordcraft_doc::StoryRef::Body).contains(&crate::cmd::insert::format_date("yyyy")));
// The template itself keeps its date.
let mut again = Session::new(wordcraft_doc::Document::new());
again.run("file.open", &json!({"path": path.to_string_lossy()})).unwrap();
assert_eq!(again.doc.core.created, "2019-05-05T12:00:00Z");
let _ = std::fs::remove_dir_all(&d);
}
/// #3433: a template the platform hands the app takes an untouched blank document's place
/// (`replaceBlank`), as a file `file.open` opens does; otherwise, and without the flag, the
/// new document opens beside the others, as File › New's does. Either way the template on
+56 -2
View File
@@ -1118,6 +1118,58 @@ fn toggle_on_a_selection_from_an_empty_paragraph_follows_the_first_text() {
assert_eq!(toggled(false, true), Some(false));
}
/// Toggling a format on a selected text box follows the first character of its text (#8589).
#[test]
fn toggle_on_a_selected_text_box_follows_first_character() {
let toggled = |first_bold: bool, second_bold: bool, leading_empty_bold: Option<bool>| -> String {
let mut s = s();
let id = run(&mut s, "insert.textBox", json!({}))["story"].as_u64().unwrap() as u32;
let boxed = StoryRef::Part(id);
if let Some(mark_bold) = leading_empty_bold {
s.doc.para_mut(boxed, &wordcraft_doc::Path::top(0)).unwrap().mark.bold = Some(mark_bold);
run(&mut s, "text.newParagraph", json!({}));
}
let text_block = usize::from(leading_empty_bold.is_some());
run(&mut s, "text.insert", json!({"text": "ab"}));
let box_pos = |off| Pos { story: boxed, path: wordcraft_doc::Path::top(text_block), off };
run(&mut s, "select.range", json!({"anchor": box_pos(0), "focus": box_pos(1)}));
run(&mut s, "format.bold", json!({"value": first_bold}));
run(&mut s, "select.range", json!({"anchor": box_pos(1), "focus": box_pos(2)}));
run(&mut s, "format.bold", json!({"value": second_bold}));
let anchor = s.doc.text_box_anchor(id).unwrap();
run(&mut s, "select.range", json!({"anchor": Pos { off: anchor.off - "\u{FFFC}".len(), ..anchor.clone() }, "focus": anchor}));
run(&mut s, "format.bold", json!({}));
let p = s.doc.para(boxed, &wordcraft_doc::Path::top(text_block)).unwrap();
(0..2).map(|i| if p.props_of_char(i).bold == Some(true) { 'B' } else { '.' }).collect()
};
// First character bold, second plain: Bold turns off across the box.
assert_eq!(toggled(true, false, None), "..");
// First character plain, second bold: Bold turns on across the box.
assert_eq!(toggled(false, true, None), "BB");
// A bold empty paragraph at the top of the box does not override plain text after it.
assert_eq!(toggled(false, true, Some(true)), "BB");
}
/// Toggling a format on a column block follows the first character in document order (#8589).
#[test]
fn toggle_on_a_column_block_follows_first_character() {
let toggled = |bold_row: usize, top_to_bottom: bool| -> Vec<bool> {
let mut s = column_doc();
run(&mut s, "select.range", json!({"anchor": {"block": bold_row, "off": 2}, "focus": {"block": bold_row, "off": 4}}));
run(&mut s, "format.bold", json!({"value": true}));
let (a, f) = if top_to_bottom { (Pos::body(0, 2), Pos::body(2, 4)) } else { (Pos::body(2, 4), Pos::body(0, 2)) };
run(&mut s, "select.column", json!({"anchor": a, "focus": f}));
run(&mut s, "format.bold", json!({}));
(0..3).map(|i| s.doc.para_at(&Pos::body(i, 0)).unwrap().props_of_char(2).bold == Some(true)).collect()
};
// Row 0 bold, rows 1-2 plain: Bold turns off across the block even when selected bottom-to-top.
assert_eq!(toggled(0, true), vec![false, false, false]);
assert_eq!(toggled(0, false), vec![false, false, false]);
// Row 0 plain, row 1 bold: Bold turns on across the block even when selected bottom-to-top.
assert_eq!(toggled(1, true), vec![true, true, true]);
assert_eq!(toggled(1, false), vec![true, true, true]);
}
#[test]
fn bold_at_a_caret_takes_a_word_with_a_typographic_apostrophe() {
// Word bolds `don’t` and `dogs’` whole: `’` is part of the word like `'` (#6517).
@@ -12623,10 +12675,12 @@ fn outline_level_changes_are_undoable() {
assert!(s.run("outline.level", &json!({"level": 12})).is_err());
assert!(s.run("outline.level", &json!({})).is_err());
// Every outline command survives junk parameters in Outline view.
for spec in cmd::registry().all().iter().filter(|c| c.id.starts_with("outline.")) {
let reg = cmd::registry();
for spec in reg.all().iter().filter(|c| c.id.starts_with("outline.")) {
for j in [json!(null), json!({"block": 99999, "level": "x", "value": 5}), json!({"block": -1, "level": 0})] {
let mut s = outline_doc();
let _ = s.run(spec.id, &j);
let r = s.run(spec.id, &j);
assert!(!caught_panic(&reg, &r), "{} panicked on {j}: {r:?}", spec.id);
let _ = s.layout();
}
}
+32
View File
@@ -1653,6 +1653,38 @@ fn a_link_keeps_a_selection_it_cannot_retype() {
assert_eq!(s.doc.field_ranges(StoryRef::Body).len(), 1);
}
#[test]
fn a_column_selection_in_one_paragraph_is_not_one_line() {
// A column (block) selection over the wrapped lines of one paragraph: both its ends are in
// that paragraph, but it holds a piece of each line, so Word shows <<Selection in Document>>
// for it and the text to display can't retype it (#8581).
let mut s = typed("alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron pi rho sigma tau");
let (first, second) = {
let l = s.layout();
let len = s.doc.para_at(&Pos::body(0, 0)).unwrap().text.len();
let mut top = None;
let mut first = None;
let mut second = None;
for off in 0..=len {
let Some(c) = l.caret_on(&Pos::body(0, off), 0) else { continue };
if top.is_some_and(|t| t != c.top) && second.is_none() {
second = Some(off + 10);
break;
}
if top.is_none() {
top = Some(c.top);
first = Some(off);
}
}
(first.expect("the paragraph is laid out"), second.expect("the paragraph wraps"))
};
run(&mut s, "select.column", json!({"anchor": Pos::body(0, first), "focus": Pos::body(0, second)}));
let segs = s.column_segments().expect("the block is one paragraph's lines").to_vec();
assert_eq!(segs.len(), 2, "the block holds a piece of each of the paragraph's two lines");
assert!(segs.iter().all(|(a, b)| a.path == segs[0].0.path && b.path == segs[0].0.path), "both pieces are in one paragraph");
assert!(!crate::cmd::insert::selection_is_one_line(&s), "a column selection is not one line of text");
}
#[test]
fn typing_then_selecting_then_typing_are_two_undo_steps() {
// #419: a selection that moves the insertion point ends the typing group, like a caret move.
+1 -1
View File
@@ -152,7 +152,7 @@ pub(crate) fn add(ctx: &mut Ctx, lay: &mut DocLayout) {
author_name(&cm.author),
CharProps { bold: Some(true), size: Some(9.0), color: Some(TextColor::Rgb(color)), ..Default::default() },
);
let pl = ctx.para_labelled(&head, inner, None, &[], None);
let pl = ctx.para_labelled(&head, inner, None, &[], 0.0, None);
let lead = pl.lines.first().map_or(0.0, |l| l.top.max(0.0));
push_para(&mut items, (story, &[HEADER_PATH]), &pl, (0, pl.lines.len()), (x, y + lead), inner, Edges::own(&pl, 0, pl.lines.len()));
y += pl.height + 2.0;
+7 -6
View File
@@ -280,13 +280,13 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
let p = taken.as_ref().map_or(p, |t| &t.para);
let label = ctx.next_label(p);
let listed = label.is_some();
let mut pl = ctx.para_labelled(p, width, table, &[], label.clone());
let mut pl = ctx.para_labelled(p, width, table, &[], 0.0, label.clone());
// A text frame (a footer's page number in a frame, say) is placed apart, like a
// floating object, and the text after it wraps around it; it takes no room in
// the flow.
if let Some(fr) = pl.rp.frame.clone().filter(|fr| frames && cell_frame(fr)) {
let fw = fr.w.unwrap_or_else(|| natural_width(&pl)).clamp(1.0, 1584.0);
let pf = if (fw - width).abs() > 0.01 { ctx.para_labelled(p, fw, table, &[], label) } else { pl };
let pf = if (fw - width).abs() > 0.01 { ctx.para_labelled(p, fw, table, &[], 0.0, label) } else { pl };
let h = match fr.h {
Some(h) if fr.h_exact => h,
Some(h) => h.max(pf.height),
@@ -318,7 +318,8 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
// body path. Keep text and wrap exclusions relative to the text's actual top.
// A paragraph going on from a shared line has its origin at that line's top.
let para_top = taken.as_ref().map_or(y, |t| t.joint.top);
y += if i == 0 { before } else { before.max(0.0) };
let applied = if i == 0 { before } else { before.max(0.0) };
y += applied;
TakenUp::start(taken.as_ref(), &mut y, &mut excl);
// Floating objects anchored here: place them, then wrap the text around them.
// One left out of the layout (hidden, or deleted in the final text) takes no room.
@@ -362,9 +363,9 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
}
floats.insert(oi, r);
}
let rel = rel_exclusions(&excl, 0.0, y);
let rel = rel_exclusions(&excl, 0.0, y, applied);
if !rel.is_empty() {
pl = ctx.para_labelled(p, width, table, &rel, label);
pl = ctx.para_labelled(p, width, table, &rel, applied, label);
}
TakenUp::clear(taken.as_ref(), &mut excl);
// Bordered paragraphs: room for their borders, those of a group joined in one box.
@@ -800,7 +801,7 @@ impl Joint {
/// taller than the text going on from it), with the room for its bottom border (Word).
pub(crate) fn fit(&self, ctx: &mut Ctx, q: &Paragraph, width: f32, table: Option<&para::CellText>) -> (f32, Vec<WrapArea>) {
let eq = ctx.eq_count;
let probe = again(ctx, eq, |ctx| ctx.para_labelled(q, width, table, &[], None));
let probe = again(ctx, eq, |ctx| ctx.para_labelled(q, width, table, &[], 0.0, None));
let (gap, height) = probe.lines.first().map_or((0.0, self.height), |l| ((self.baseline - (l.baseline - l.top)).max(0.0), l.height));
let rect = Rect::new(self.left, self.top, (self.end - self.left).max(0.0), (gap + height - 0.01).max(0.01));
let mut areas = vec![(rect, false, None, WrapText::Right, false)];
+3
View File
@@ -16,6 +16,9 @@ pub(crate) struct Key {
pub(crate) table: u64,
pub(crate) notes: u64,
pub(crate) excl: u64,
/// The space before the paragraph layout applied above it, which a Top-and-Bottom object in
/// it is laid out again below ([`para::ParaEnv::space_before`]).
pub(crate) space_before: u32,
pub(crate) eq: u32,
pub(crate) read_spacing: Option<u32>,
pub(crate) grid: (u32, u32, u32, bool),
+23 -5
View File
@@ -113,12 +113,21 @@ struct ParaEnvInput<'a> {
label: Option<(String, Level)>,
table: Option<&'a para::CellText>,
exclusions: &'a [para::Exclusion],
space_before: f32,
eq_number: u32,
typing_word: Option<(usize, usize)>,
fitted: &'a [(usize, f32)],
joined: bool,
}
/// The flow's wrap context for a paragraph's layout, as its cache key needs it: the areas text
/// flows around (relative to its first line) and the space before it the flow laid out, which
/// reaches up to them (see [`para::ParaEnv::space_before`]).
struct WrapAreas<'a> {
exclusions: &'a [para::Exclusion],
space_before: f32,
}
/// A header or footer (`story`) laid out for page `number` of a section (`sect`, `mirror`): its
/// table cells' floats placed on the page rather than in their cell ([`Float::outside_cell`],
/// Word's picture watermark in a header that starts with a table), drawn behind the header's
@@ -252,6 +261,7 @@ impl Ctx<'_> {
typing_word: None,
numeral: self.opts.numeral,
exclusions: &[],
space_before: 0.0,
eq_number: 0,
read_line_spacing: None,
grid: para::Grid::default(),
@@ -299,16 +309,18 @@ impl Ctx<'_> {
/// Lay out `p` with its already counted `label`, so laying a paragraph out again (around
/// floating objects, or after it moved) doesn't advance the list counters twice.
/// `space_before` is the space before `p` that the flow laid out above it ([`para::ParaEnv`]).
pub(crate) fn para_labelled(
&mut self,
p: &Paragraph,
width: f32,
table: Option<&para::CellText>,
exclusions: &[para::Exclusion],
space_before: f32,
label: Option<(String, Level)>,
) -> Arc<ParaLayout> {
let fitted = self.fitted_boxes(p);
let (key, eq_number) = self.para_key(p, width, table, exclusions, label.as_ref(), &fitted);
let (key, eq_number) = self.para_key(p, width, table, WrapAreas { exclusions, space_before }, label.as_ref(), &fitted);
self.cache.used.insert(key.clone());
if let Some(pl) = self.cache.paras.get(&key) {
self.cache.hits += 1;
@@ -323,6 +335,7 @@ impl Ctx<'_> {
label,
table,
exclusions,
space_before,
eq_number,
typing_word: typing,
fitted: &fitted,
@@ -347,7 +360,7 @@ impl Ctx<'_> {
return None;
}
let kept = (self.eq_count, self.uses_totals);
let (key, eq_number) = self.para_key(p, width, None, &[], label.as_ref(), &[]);
let (key, eq_number) = self.para_key(p, width, None, WrapAreas { exclusions: &[], space_before: 0.0 }, label.as_ref(), &[]);
(self.eq_count, self.uses_totals) = kept;
if key.typing.is_some() {
return None;
@@ -365,6 +378,7 @@ impl Ctx<'_> {
label,
table: None,
exclusions: &[],
space_before: 0.0,
eq_number,
typing_word: None,
fitted: &[],
@@ -387,7 +401,7 @@ impl Ctx<'_> {
measure: impl FnOnce(&ParaLayout) -> (f32, f32),
) -> (f32, f32) {
let fitted = self.fitted_boxes(p);
let (key, eq_number) = self.para_key(p, width, table, &[], label.as_ref(), &fitted);
let (key, eq_number) = self.para_key(p, width, table, WrapAreas { exclusions: &[], space_before: 0.0 }, label.as_ref(), &fitted);
self.cache.used.insert(key.clone());
if let Some(m) = self.cache.measures.get(&key) {
self.cache.hits += 1;
@@ -402,6 +416,7 @@ impl Ctx<'_> {
label,
table,
exclusions: &[],
space_before: 0.0,
eq_number,
typing_word: typing,
fitted: &fitted,
@@ -455,10 +470,11 @@ impl Ctx<'_> {
p: &Paragraph,
width: f32,
table: Option<&para::CellText>,
exclusions: &[para::Exclusion],
wrap: WrapAreas<'_>,
label: Option<&(String, Level)>,
fitted: &[(usize, f32)],
) -> (Key, u32) {
let WrapAreas { exclusions, space_before } = wrap;
let page = if has_page_fields(p) { Some(self.fields.page_key()) } else { None };
if self.track_totals && !self.uses_totals && has_total_fields(p) {
self.uses_totals = true;
@@ -483,6 +499,7 @@ impl Ctx<'_> {
table: table.map(|t| self.table_key(t)).unwrap_or(0),
notes: if p.objects.iter().any(|o| matches!(o, InlineObject::NoteRef { .. })) { self.notes_hash } else { 0 },
excl: if exclusions.is_empty() { 0 } else { hash_of(&format!("{exclusions:?}")) },
space_before: space_before.to_bits(),
eq: if eq_here > 0 { eq_number } else { 0 },
read_spacing: if self.opts.view == ViewMode::Read { self.opts.read_line_spacing.map(f32::to_bits) } else { None },
grid: self.grid.key(),
@@ -512,7 +529,7 @@ impl Ctx<'_> {
}
fn para_env<'b>(&'b self, input: ParaEnvInput<'b>) -> para::ParaEnv<'b> {
let ParaEnvInput { width, label, table, exclusions, eq_number, typing_word, fitted, joined } = input;
let ParaEnvInput { width, label, table, exclusions, space_before, eq_number, typing_word, fitted, joined } = input;
para::ParaEnv {
doc: self.doc,
width,
@@ -526,6 +543,7 @@ impl Ctx<'_> {
typing_word,
numeral: self.opts.numeral,
exclusions,
space_before,
eq_number,
read_line_spacing: if self.opts.view == ViewMode::Read { self.opts.read_line_spacing } else { None },
grid: self.grid,
+12 -6
View File
@@ -219,8 +219,10 @@ pub(crate) fn wrap_area(r: Rect, float: &Float, outline: Option<&[(f32, f32)]>)
Some((Rect::new(r.x - side, r.y - top, r.w + side * 2.0, r.h + top + bottom), float.wrap == Wrap::TopAndBottom, None, float.wrap_text, false))
}
/// Wrap areas relative to a paragraph whose column starts at `x0` and whose top is `y0`.
pub(crate) fn rel_exclusions(excl: &[WrapArea], x0: f32, y0: f32) -> Vec<para::Exclusion> {
/// Wrap areas relative to a paragraph whose column starts at `x0` and whose top is `y0`, with
/// `space_before` the space before it that the flow laid out above it.
pub(crate) fn rel_exclusions(excl: &[WrapArea], x0: f32, y0: f32, space_before: f32) -> Vec<para::Exclusion> {
let before = if space_before > 0.0 { space_before } else { 0.0 };
excl.iter()
.map(|(r, tb, c, side, table)| para::Exclusion {
top: r.y - y0,
@@ -232,7 +234,11 @@ pub(crate) fn rel_exclusions(excl: &[WrapArea], x0: f32, y0: f32) -> Vec<para::E
side: *side,
table: *table,
})
.filter(|e| e.bottom > 0.0)
// Top-and-Bottom areas ending within the paragraph's applied space before can still take
// room, with that space laid out again below them (#7143). Any ending at or above it
// (like side-wrapping areas above the first line) cannot reach the paragraph and is
// dropped so paragraphs below keep empty exclusions and hit the cache (#8613).
.filter(|e| e.bottom > 0.0 || (e.top_bottom && e.bottom > -before))
.collect()
}
@@ -525,8 +531,8 @@ fn anchor_floats_but(
}
}
}
let rel = rel_exclusions(&body_wraps(ctx, pb), col_x, y0);
let pl = ctx.para_labelled(p, width, None, &rel, label.clone());
let rel = rel_exclusions(&body_wraps(ctx, pb), col_x, y0, before);
let pl = ctx.para_labelled(p, width, None, &rel, before, label.clone());
(rects, pl, rel)
}
@@ -861,7 +867,7 @@ pub(crate) fn place_objects(ctx: &mut Ctx, req: &ObjectPlacement) -> (Vec<Placed
/// touch its lines and are left out.
pub(crate) fn continued_exclusions(rel: &[para::Exclusion], excl: &[WrapArea], x0: f32, y: f32, t: f32, width: f32) -> Vec<para::Exclusion> {
let before = rel.iter().filter(|e| e.top < t).map(|e| para::Exclusion { bottom: e.bottom.min(t), ..e.clone() });
let here = rel_exclusions(excl, x0, y - t)
let here = rel_exclusions(excl, x0, y - t, 0.0)
.into_iter()
.filter(|e| e.bottom > t && e.right > -width && e.left < 2.0 * width)
.map(|e| if e.top < t && e.contour.is_none() { para::Exclusion { top: t, ..e } } else { e });
+16 -6
View File
@@ -109,7 +109,7 @@ fn place_page_text_frame(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, blo
}
let width = fr.w.unwrap_or_else(|| pb.col_w()).clamp(1.0, 1584.0);
let label = ctx.next_label(p);
let pl = ctx.para_labelled(p, width, None, &[], label);
let pl = ctx.para_labelled(p, width, None, &[], 0.0, label);
let notes = para_notes(ctx.doc, p, &pl);
let mut new_notes = Vec::new();
for line in &pl.lines {
@@ -272,6 +272,10 @@ struct Flow<'a> {
label: Option<(String, Level)>,
/// Where it was expected to start; floats anchored here are placed again if it starts elsewhere.
guess: f32,
/// The space before it that its layout (`pl`) was broken with: the declared space before
/// until the flow settles what it really lays out, then that, so a later relay keeps a
/// Top-and-Bottom object in it pushing the first line to the same place.
space_applied: f32,
excl_mark: usize,
/// Where its automatic equation numbers start: each layout of it again counts from here.
eq_start: u32,
@@ -339,6 +343,7 @@ impl<'a> Flow<'a> {
width,
label,
guess,
space_applied: space_before,
excl_mark,
eq_start,
float_rects,
@@ -375,13 +380,14 @@ impl<'a> Flow<'a> {
});
(self.float_rects, self.pl, self.rel) = (rects, pl, rel);
self.late = LateFloats::new(&late);
self.space_applied = before;
(self.laid_page, self.laid_width) = (pb.number, pb.col_w());
}
/// Lay the paragraph out again around the wrap areas `rel`, with its fields on their pages.
fn relay(&mut self, ctx: &mut Ctx, rel: &[para::Exclusion]) -> Arc<ParaLayout> {
let (p, width, eq_start, label) = (self.p, self.laid_width, self.eq_start, &self.label);
with_page_map(ctx, &mut self.page_map, |ctx| again(ctx, eq_start, |ctx| ctx.para_labelled(p, width, None, rel, label.clone())))
let (p, width, eq_start, label, space_before) = (self.p, self.laid_width, self.eq_start, &self.label, self.space_applied);
with_page_map(ctx, &mut self.page_map, |ctx| again(ctx, eq_start, |ctx| ctx.para_labelled(p, width, None, rel, space_before, label.clone())))
}
/// The space before the paragraph, after the one between it and the previous paragraph is
@@ -827,6 +833,7 @@ impl<'a> Flow<'a> {
(self.float_rects, self.pl, self.rel) = (rects, relaid, relaid_rel);
(self.laid_page, self.laid_width) = (pb.number, pb.col_w());
self.anchor_y = y0;
self.space_applied = 0.0;
self.l0 = k;
}
}
@@ -1040,8 +1047,10 @@ fn place_para_in_flow(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block:
let mut f = Flow::new(ctx, pb, p, (block, body_top));
let spot = |pb: &PageBuilder| (pb.pages.len(), pb.col);
let placed_at = spot(pb);
// A continuous section's top mid-page is not a page top, so the break still applies.
let broke_before = f.pl.rp.page_break_before && !f.fresh(pb) && !pb.web;
// A continuous section's top mid-page is not a page top, so the break still applies. A
// page-anchored frame is not content above the paragraph, so it does not make the break
// apply either: the frame's wrap area moves the text below or beside it (#8577).
let broke_before = f.pl.rp.page_break_before && !pb.at_page_top() && !pb.web;
if broke_before {
pb.new_page(block, body_top);
}
@@ -1136,7 +1145,7 @@ pub(crate) fn place_outline_para(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragr
let width = (pb.col_w() - indent - outline::SYMBOL_W).max(72.0);
let q = outline::outline_para(ctx.doc, p, o.view.plain);
ctx.fields.page = pb.number;
let pl = ctx.para_labelled(&q, width, None, &[], label);
let pl = ctx.para_labelled(&q, width, None, &[], 0.0, label);
pb.y += pl.rp.space_before.max(0.0);
let n = pl.lines.len();
let l1 = if o.view.first_line_only && level >= outline::BODY { n.min(1) } else { n };
@@ -1248,6 +1257,7 @@ fn next_first_line(ctx: &mut Ctx, block: usize, width: f32, depth: usize, new_pa
typing_word: None,
numeral: ctx.opts.numeral,
exclusions: &[],
space_before: 0.0,
eq_number: ctx.eq_count,
read_line_spacing: if ctx.opts.view == ViewMode::Read { ctx.opts.read_line_spacing } else { None },
grid: ctx.grid,
+6 -1
View File
@@ -514,7 +514,12 @@ impl PageBuilder<'_> {
/// `reach` is how far the text reaches past the column's left and right edges (a paragraph's
/// negative indents).
pub(crate) fn fresh(&self, reach: (f32, f32)) -> bool {
self.at_top() && self.top <= self.page_top + 0.01 && !self.framed_here(reach)
self.at_page_top() && !self.framed_here(reach)
}
/// At the top of the page's text with nothing placed above it. A page-anchored frame is not
/// content above it: a paragraph with a page break before needs no new page for one.
pub(crate) fn at_page_top(&self) -> bool {
self.at_top() && self.top <= self.page_top + 0.01
}
/// A page-anchored body text frame's wrap area reaches into the current column's text,
/// widened by `reach` on the left and right.
+2
View File
@@ -367,6 +367,7 @@ mod label_spacing_tests {
field_codes: false,
grid: Grid::default(),
exclusions: &[],
space_before: 0.0,
eq_number: 0,
numeral: crate::NumeralMode::default(),
read_line_spacing: None,
@@ -513,6 +514,7 @@ mod tests {
field_codes: false,
grid: Grid::default(),
exclusions: &[],
space_before: 0.0,
eq_number: 0,
numeral: Default::default(),
read_line_spacing: None,
+49 -2
View File
@@ -502,12 +502,15 @@ impl<'a> Builder<'a> {
let ge = bounds.get(bi + 1).copied().unwrap_or(shape_text.len());
let g0 = self.glyphs.len() as u32;
let mut adv = 0.0f32;
// What kerning added to the last glyph's advance: its pair with the next glyph.
let mut kern = 0.0f32;
while let Some(g) = shaped.get(gi) {
if g.cluster >= ge {
break;
}
self.glyphs.push(Glyph { gid: g.gid, dx: adv + g.x_offset as f32 * k * hscale, dy: g.y_offset as f32 * k });
adv += g.x_advance as f32 * k * hscale;
kern = if rc.kerned() && !key.rtl { pair_with_next(g, st.face.advance(g.gid)) * k * hscale } else { 0.0 };
gi += 1;
}
let g1 = self.glyphs.len() as u32;
@@ -535,6 +538,7 @@ impl<'a> Builder<'a> {
obj_h: 0.0,
obj_d: 0.0,
dot: s == "." || s == ",",
kern: if kind == ClKind::Text && g1 == g0 + 1 { kern } else { 0.0 },
});
}
if matches!(dir, Dir::Para) {
@@ -577,6 +581,13 @@ impl<'a> Builder<'a> {
}
}
}
// The ligature glyph's kerning pair with the following glyph belongs after its last
// letter, not on the head inside the ligature (#8618).
if let Some((head, rest)) = self.clusters.get_mut(i..=i + n).and_then(|cs| cs.split_first_mut())
&& let Some(last) = rest.last_mut()
{
last.kern = std::mem::take(&mut head.kern);
}
i += n + 1;
}
}
@@ -607,6 +618,7 @@ impl<'a> Builder<'a> {
obj_h: 0.0,
obj_d: 0.0,
dot: false,
kern: 0.0,
});
return;
};
@@ -640,7 +652,20 @@ impl<'a> Builder<'a> {
let style = first.style;
let g1 = added.last().map(|c| c.g1).unwrap_or(g0);
self.shown.push((self.clusters.len(), text.to_string(), ranges));
self.clusters.push(Cluster { start, end, adv: x, kind: ClKind::Text, style, g0, g1, break_after: false, obj_h: 0.0, obj_d: 0.0, dot: false });
self.clusters.push(Cluster {
start,
end,
adv: x,
kind: ClKind::Text,
style,
g0,
g1,
break_after: false,
obj_h: 0.0,
obj_d: 0.0,
dot: false,
kern: 0.0,
});
}
/// Shape `texts` on top of one another as one cluster for `start..end`: each aligned within
@@ -690,11 +715,33 @@ impl<'a> Builder<'a> {
if !text.is_empty() {
self.shown.push((k, text, ranges));
}
self.clusters.push(Cluster { start, end, adv, kind: ClKind::Text, style, g0, g1, break_after: false, obj_h: 0.0, obj_d: 0.0, dot: false });
self.clusters.push(Cluster {
start,
end,
adv,
kind: ClKind::Text,
style,
g0,
g1,
break_after: false,
obj_h: 0.0,
obj_d: 0.0,
dot: false,
kern: 0.0,
});
Some(k)
}
}
/// What kerning added to a glyph's advance (in font units) for its pair with the next glyph. An
/// old-style `kern` table's pair is split between its two glyphs, the second's half in its advance
/// and its offset alike: that half is the pair with the glyph before, which stays on the line.
fn pair_with_next(g: &wordcraft_fonts::ShapedGlyph, plain_advance: f64) -> f32 {
let added = g.x_advance as f32 - plain_advance as f32;
let before = if added != 0.0 { g.x_offset as f32 } else { 0.0 };
added - before
}
/// Times New Roman or one of its metric twins.
fn is_times_twin(family: &str) -> bool {
["Times New Roman", "Liberation Serif", "Tinos"].iter().any(|f| family.eq_ignore_ascii_case(f))
+13 -5
View File
@@ -99,14 +99,17 @@ fn auto_space_room(st: &StyleRun) -> f32 {
/// size for Times New Roman, 0.2203 for Arial, 0.2575 for Calibri, 0.2980 for Courier New,
/// 0.3041 for Cambria — which is half each face's average character width. With different sizes
/// either side, the room after the Latin run takes the Latin size, not the Asian one.
pub(super) fn auto_space(b: &mut Builder, text: &str, de: bool, dn: bool) -> Vec<(usize, f32)> {
///
/// `ea_lacks(at, c)`: the run at byte `at` names an installed East Asian font that has no glyph
/// for `c`. Word adds no room beside such a character, though a substituted face draws it (#6591).
pub(super) fn auto_space(b: &mut Builder, text: &str, de: bool, dn: bool, ea_lacks: impl Fn(usize, char) -> bool) -> Vec<(usize, f32)> {
let mut out = Vec::new();
if !de && !dn {
return out;
}
let mut shown = b.shown.iter().map(|s| (s.0, s.1.as_str())).peekable();
// The previous text cluster: index and its last character.
let mut prev: Option<(usize, char)> = None;
// The previous text cluster: index, its last character and its start byte.
let mut prev: Option<(usize, char, usize)> = None;
for k in 0..b.clusters.len() {
let Some(c) = b.clusters.get(k) else { break };
match c.kind {
@@ -126,8 +129,13 @@ pub(super) fn auto_space(b: &mut Builder, text: &str, de: bool, dn: bool) -> Vec
prev = None;
continue;
};
if let Some((pk, pc)) = prev
let start = c.start;
if let Some((pk, pc, pstart)) = prev
&& let Some(side) = crate::kinsoku::auto_space(pc, first, de, dn)
&& !match side {
crate::kinsoku::AsianSide::Left => ea_lacks(pstart, pc),
crate::kinsoku::AsianSide::Right => ea_lacks(start, first),
}
{
let style = b.clusters.get(pk).map(|p| p.style as usize);
let st = style.and_then(|i| b.styles.get(i));
@@ -142,7 +150,7 @@ pub(super) fn auto_space(b: &mut Builder, text: &str, de: bool, dn: bool) -> Vec
out.push((pk, gap));
}
}
prev = Some((k, last));
prev = Some((k, last, start));
}
out
}
+56 -6
View File
@@ -14,6 +14,9 @@ const MIN_LINE_WIDTH: f32 = 1.0;
struct Breaker<'e> {
level: Option<&'e Level>,
rp: wordcraft_doc::resolve::ResolvedPara,
/// The space before the paragraph that the flow laid out above it, which a Top-and-Bottom
/// object in it is laid out again below (see [`ParaEnv::space_before`]).
space_before: f32,
mark_style: u32,
exclusions: &'e [Exclusion],
n: usize,
@@ -220,6 +223,7 @@ impl<'e> Breaker<'e> {
// Exact spacing fixes the table-contact boundary even when the mark has other metrics.
// Keep the existing estimate for shapes and for non-exact spacing.
table_h: if let LineSpacing::Exactly(h) = rp.line_spacing { h } else { est_h },
space_before: env.space_before,
rp,
first_x0: None,
hcache: Vec::new(),
@@ -262,6 +266,26 @@ impl<'e> Breaker<'e> {
let mut guard = 0;
loop {
let lo = self.row_left(pl);
// A Top-and-Bottom object ending in the paragraph's space before (or reaching into
// its first line) is a block the first line must start below, with that space before
// laid out again under it (#7143). Exclusions are relative to the first line'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 = (-before, self.est_h + before, self.table_h);
if let Some(below) = self
.exclusions
.iter()
.filter(|e| e.top_bottom)
.filter(|e| e.intersects_row(row.0, row.1, row.2, lo, self.base_right))
.map(|e| e.bottom)
.reduce(f32::max)
{
self.top = self.top.max(below + before);
}
}
let row = (self.top, self.est_h, self.table_h);
match row_spans(self.exclusions, row, (lo, self.base_right), self.tight_indent).map(|mut spans| (spans.pop_front(), spans)) {
Ok((Some((a, b)), rest)) => {
@@ -926,19 +950,33 @@ impl Scan {
}
self.x += w;
}
_ => self.pending_tab = Some((j, stop, self.x)),
_ => {
// A right tab's room grows from nothing with its text (a tab moved on from the
// line before may still hold the width it had there).
if stop.align == TabAlign::Right
&& let Some(c) = pl.clusters.get_mut(j)
{
c.adv = 0.0;
}
self.pending_tab = Some((j, stop, self.x));
}
}
if stop.leader != TabLeader::None {
self.leaders.push((j, stop.leader));
}
}
/// Whether text after a right/centre tab grows leftwards into the tab's space first.
/// Whether text after a right/centre tab grows leftwards into the tab's space first. Up to a
/// right stop it fits even past the right indent (Word: a TOC entry whose text ends
/// less than a digit short of the indent keeps its page number on its line when the stop is
/// at the margin); unshifted, the text after the tab ends at `x - room`.
fn absorbs(&self, pl: &ParaLayout, advance: f32) -> bool {
self.pending_tab.is_some_and(|(tj, stop, _)| {
let room = pl.clusters.get(tj).map(|t| t.adv).unwrap_or(0.0);
match stop.align {
TabAlign::Right | TabAlign::Decimal => room >= advance,
// Not where a floating object narrows the line: the text would run into it.
TabAlign::Right => room >= advance || (!self.narrowed && self.x - room + advance <= stop.pos + 0.01),
TabAlign::Decimal => room >= advance,
TabAlign::Center => room >= advance / 2.0 && self.x + advance / 2.0 <= self.right_edge + 0.01,
_ => false,
}
@@ -964,7 +1002,7 @@ impl Scan {
0.0
};
let fits = absorbs
|| self.x + advance - pl.auto_space_after(j) <= self.right_edge + shrink + 0.01
|| self.x + advance - pl.auto_space_after(j) - line_end_kern(pl, j) <= self.right_edge + shrink + 0.01
|| c.kind == ClKind::Space
|| c.kind == ClKind::Marker;
if !fits && pl.is_edit_boundary(c.start) && (c0..j).any(|k| pl.clusters.get(k).is_some_and(takes_room)) {
@@ -1014,7 +1052,9 @@ impl Scan {
/// Text after a decimal/centre/right tab shifts as it grows.
fn shift_pending_tab(&mut self, pl: &mut ParaLayout) {
let Some((tj, stop, tx)) = self.pending_tab else { return };
let seg_w = self.x - tx;
// For a right tab `x` includes the room the tab has so far (it starts from none).
let old = pl.clusters.get(tj).map(|c| c.adv).unwrap_or(0.0);
let seg_w = self.x - tx - if stop.align == TabAlign::Right { old } else { 0.0 };
let shift = match stop.align {
TabAlign::Right => stop.pos - tx - seg_w,
TabAlign::Center => stop.pos - tx - seg_w / 2.0,
@@ -1023,7 +1063,6 @@ impl Scan {
_ => 0.0,
};
let shift = shift.max(0.0);
let old = pl.clusters.get(tj).map(|c| c.adv).unwrap_or(0.0);
if (shift - old).abs() > 0.001 {
let delta = shift - old;
if let Some(c) = pl.clusters.get_mut(tj) {
@@ -1131,6 +1170,17 @@ impl Scan {
}
}
/// The kerning cluster `j` loses when the line ends after it inside a word: Word measures a line's
/// last letter without its pair with the letter that goes on to the next line (a cell's width
/// swept a twip at a time in Word: the letters before a broken kerning pair fit only where they
/// fit on their own, without the pair).
fn line_end_kern(pl: &ParaLayout, j: usize) -> f32 {
match (pl.clusters.get(j), pl.clusters.get(j + 1)) {
(Some(c), Some(next)) if next.kind == ClKind::Text => c.kern,
_ => 0.0,
}
}
/// Narrowest span text flows into beside a floating object, points. Word puts an empty
/// paragraph beside a floating table in a 21.3pt gap but not in an 18.6pt one.
const MIN_SPAN: f32 = 20.0;
+10 -1
View File
@@ -147,6 +147,9 @@ pub struct Cluster {
pub obj_d: f32,
/// The cluster is a decimal separator (decimal tabs align on it).
pub dot: bool,
/// The kerning between this cluster and the next (part of `adv`, usually negative): a line
/// that ends between them lays the cluster out without it.
pub kern: f32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -391,8 +394,14 @@ pub struct ParaEnv<'a> {
/// How digits look on screen (an unresolved `System` shows Western digits).
pub numeral: NumeralMode,
/// Areas text must flow around (floating objects), relative to the paragraph: x from the
/// column's left edge, y from the top of the first line.
/// column's left edge, y from the top of the first line (its top with the space before
/// applied, which is where [`ParaEnv::space_before`] reaches up to).
pub exclusions: &'a [Exclusion],
/// The space before the paragraph that the flow above it actually laid out: its declared
/// space before less what collapsing against the previous paragraph's space after, contextual
/// spacing or a page top took away (and the negative space applied at a page top). A
/// Top-and-Bottom object reaching into it is laid out again below it (#7143).
pub space_before: f32,
/// Automatic equation numbers used before this paragraph.
pub eq_number: u32,
pub read_line_spacing: Option<f32>,
+23 -1
View File
@@ -62,6 +62,7 @@ impl Slot {
obj_h,
obj_d,
dot: false,
kern: 0.0,
}
}
}
@@ -662,6 +663,22 @@ fn shown_text(cx: &Cx) -> Option<String> {
Some(shown)
}
/// Each run's end byte and the installed East Asian font (`w:eastAsia`) it names, `None` when it
/// names none or one that isn't installed. Empty when `wanted` is false or the text is ASCII, which
/// has no East Asian characters to look the fonts up for.
fn installed_east_asian_fonts(cx: &Cx, wanted: bool) -> Vec<(usize, Option<wordcraft_fonts::FaceRef>)> {
if !wanted || cx.p.text.is_ascii() {
return Vec::new();
}
cx.p.run_ranges()
.map(|(range, props)| {
let rc = cx.res.char(props);
let face = rc.font_ea.as_deref().filter(|f| !f.trim().is_empty()).map(|f| wordcraft_fonts::word::resolve(f, rc.bold, rc.italic));
(range.end, face.filter(|r| !r.substituted).map(|r| r.face))
})
.collect()
}
/// Lay out one paragraph.
pub fn layout_para(p: &Paragraph, env: &ParaEnv) -> ParaLayout {
#[cfg(test)]
@@ -697,7 +714,12 @@ pub fn layout_para(p: &Paragraph, env: &ParaEnv) -> ParaLayout {
let auto_space = if rp.snap_to_grid && env.grid.snap_all && env.grid.chars.is_some() {
Vec::new()
} else {
auto_space(&mut sh.b, &p.text, rp.auto_space_de, rp.auto_space_dn)
let ea = installed_east_asian_fonts(&cx, rp.auto_space_de || rp.auto_space_dn);
// Runs come in order, so their ends rise: the run holding `at` is a binary search away.
let ea_lacks = |at: usize, c: char| {
ea.get(ea.partition_point(|(end, _)| *end <= at)).and_then(|(_, face)| *face).is_some_and(|f: wordcraft_fonts::FaceRef| !f.covers(c))
};
auto_space(&mut sh.b, &p.text, rp.auto_space_de, rp.auto_space_dn, ea_lacks)
};
let mut skip = sh.left.clone();
skip.extend(sh.bare.iter().cloned());
+1
View File
@@ -248,6 +248,7 @@ pub fn measure_table_columns(doc: &wordcraft_doc::Document, t: &Table) -> Vec<(f
// Measurement uses a fixed environment (like show_hidden/proofing above).
numeral: crate::NumeralMode::default(),
exclusions: &[],
space_before: 0.0,
eq_number: 0,
read_line_spacing: None,
grid: crate::para::Grid::default(),
+710 -1
View File
@@ -17,6 +17,7 @@ mod header_legacy_float;
mod joined;
mod keep_next_section;
mod ligature;
mod line_end_kern;
pub(crate) mod linear;
mod missing_glyphs;
mod nbsp;
@@ -1002,7 +1003,7 @@ fn a_megabyte_long_word_lays_out_quickly() {
/// A cluster with the given advance and kind, for the tests that measure a word by hand.
fn word_cluster(kind: para::ClKind, adv: f32, break_after: bool) -> para::Cluster {
para::Cluster { start: 0, end: 1, adv, kind, style: 0, g0: 0, g1: 1, break_after, obj_h: 0.0, obj_d: 0.0, dot: false }
para::Cluster { start: 0, end: 1, adv, kind, style: 0, g0: 0, g1: 1, break_after, obj_h: 0.0, obj_d: 0.0, dot: false, kern: 0.0 }
}
/// A word that a negative advance makes narrower still fits beside a float: the width of a word
@@ -2009,6 +2010,54 @@ fn leader_dots_are_spaced_and_placed_as_in_word() {
}
}
/// A TOC entry with a right indent and its right tab at the margin, past the indent (Word's TOC
/// styles): the page number may end past the indent, up to the stop. Like Word, the number stays
/// on the text's line whenever it fits between the text and the stop, also when the text ends
/// less than a digit short of the indent; when it doesn't fit there, the tab and the number go
/// to the next line as before.
#[test]
fn right_tab_past_the_right_indent_takes_its_number_up_to_the_stop() {
use wordcraft_doc::props::{TabAlign, TabLeader, TabStop};
let stop = 72.0 + 468.0;
let mut close = 0;
for indent in [28.35f32, 6.0] {
let edge = stop - indent;
for m in 20..40 {
for r in 2..7 {
let text = format!("{}{}\t104", "abc ".repeat(m), "y".repeat(r));
let n = text.chars().count();
let tab = n - 4;
let mut d = Document::from_text(&text);
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| {
p.indent_right = Some(indent);
p.tabs = Some(vec![TabStop { pos: 468.0, align: TabAlign::Right, leader: TabLeader::Dot }]);
})
.unwrap();
let l = lay(&d);
let Some(para) = l.pages[0].items.iter().find_map(|i| if let Placed::Lines { para, .. } = i { Some(para.clone()) } else { None })
else {
panic!("no lines")
};
let line_of = |k: usize| para.lines.iter().position(|l| l.c0 <= k && k < l.c1).unwrap();
// Where the text ends and how wide the number is (the text's last letter and the number
// are each on one line; the last two letters are both a "y").
let last = l.caret(&Pos::body(0, tab - 1)).unwrap().x;
let text_end = last + (last - l.caret(&Pos::body(0, tab - 2)).unwrap().x);
let end = l.caret(&Pos::body(0, n)).unwrap().x;
let number = end - l.caret(&Pos::body(0, n - 3)).unwrap().x;
assert!((end - stop).abs() < 0.5, "indent {indent}, {m} words + {r}: number ends at {end}");
assert_eq!(line_of(tab), line_of(n - 1), "indent {indent}, {m} words + {r}: the tab and its number are on different lines");
let same = line_of(tab) == line_of(tab - 1);
assert_eq!(same, text_end + number <= stop + 0.01, "indent {indent}, {m} words + {r}: text ends at {text_end}, number {number} wide");
if same && text_end > edge - number / 3.0 {
close += 1;
}
}
}
}
assert!(close > 0, "no entry whose text ends within a digit of the indent");
}
/// A left tab whose only stop is past the right indent wraps; on the next line it still can't
/// reach that stop, so it takes no room there and its text starts at the indent instead of
/// going to a line of its own.
@@ -3754,6 +3803,74 @@ fn turned_text_uses_min_height() {
}
}
/// A minimum height is the turned text's length only while the lines wrapped to it fit across the
/// column. In a narrow cell they would pile up sideways, so the text keeps its unwrapped length
/// instead: it runs on past the minimum and the row grows to hold it, rather than spilling out.
#[test]
fn turned_text_in_a_narrow_cell_keeps_its_unwrapped_length() {
use wordcraft_doc::props::HeightRule;
crate::test_fonts();
for turn in [TextDirection::Up, TextDirection::Down] {
let mut d = Document::from_text("After");
let mut t = Table::new(1, 2, 60.0);
t.props.style = None;
t.rows[0].props.height = Some(80.0);
t.rows[0].props.height_rule = HeightRule::AtLeast;
t.rows[0].cells[1].props.text_direction = turn;
t.rows[0].cells[1].blocks = vec![wordcraft_doc::para_block(Paragraph::with_text(&"word ".repeat(12), Default::default()))];
d.insert_block(StoryRef::Body, &Path::top(0), wordcraft_doc::Block::Table(t)).unwrap();
let l = lay(&d);
let it = l.pages[0].items.iter().find(|it| matches!(it, Placed::Lines { path, .. } if path.0 == [0, 0, 1, 0])).unwrap();
let lines = if let Placed::Lines { l0, l1, .. } = it { l1 - l0 } else { 0 };
assert_eq!(lines, 1, "{turn:?}: the lines at 80pt would not fit across the narrow cell");
let b = it.turned_bounds().unwrap();
assert!(b.w < 20.0, "{turn:?}: one line across the cell, not a stack spilling sideways: {b:?}");
assert!(b.h > 80.0, "{turn:?}: the text keeps its unwrapped length and the row grows: {b:?}");
}
}
/// The probe is skipped inside a text box: the box's own layout decides its size, so turned text
/// there keeps its unwrapped length even when the lines at the minimum height would fit across
/// the cell (which is exactly when a body table would take the minimum as the length).
#[test]
fn a_text_box_skips_the_min_height_probe_for_turned_text() {
use wordcraft_doc::props::HeightRule;
crate::test_fonts();
let mut d = Document::from_text("Before\nafter");
let mut t = Table::new(1, 2, 468.0);
t.props.style = None;
t.rows[0].props.height = Some(80.0);
t.rows[0].props.height_rule = HeightRule::AtLeast;
t.rows[0].cells[1].props.text_direction = TextDirection::Down;
t.rows[0].cells[1].blocks = vec![wordcraft_doc::para_block(Paragraph::with_text(&"word ".repeat(12), Default::default()))];
let id = d.add_part(wordcraft_doc::PartKind::TextBox, vec![wordcraft_doc::Block::Table(t).into()]);
let shape = InlineObject::Shape {
kind: wordcraft_doc::para::ShapeKind::TextBox,
w: 468.0,
h: 400.0,
fill: None,
stroke: None,
stroke_width: 1.0,
float: Default::default(),
story: Some(id),
effects: Default::default(),
freeform: None,
extra: Default::default(),
};
let off = d.para(StoryRef::Body, &Path::top(0)).map_or(0, |p| p.len());
d.insert_object(&Pos::body(0, off), shape, &Default::default()).unwrap();
let l = lay(&d);
let it = l.pages[0]
.items
.iter()
.find(|it| matches!(it, Placed::Lines { story: StoryRef::Part(s), path, .. } if *s == id && path.0 == [0, 0, 1, 0]))
.unwrap();
let lines = if let Placed::Lines { l0, l1, .. } = it { l1 - l0 } else { 0 };
assert_eq!(lines, 1, "the text box skips the probe: the text keeps its unwrapped length");
let b = it.turned_bounds().unwrap();
assert!(b.h > 80.0, "and so it runs on past the minimum height: {b:?}");
}
#[test]
fn turned_text_wraps_to_merged_rows_height() {
use wordcraft_doc::props::{HeightRule, VMerge};
@@ -8566,6 +8683,286 @@ fn top_and_bottom_float_pushes_its_own_first_line_down() {
assert!((c.top - top).abs() < 2.0, "{c:?} vs {top}");
}
/// #7143: a Top-and-Bottom rectangle anchored to one paragraph that ends inside the *next*
/// paragraph's space before (or reaches into its first line) pushes that paragraph down to the
/// rectangle's bottom **plus** the space before. A rectangle in the previous paragraph's space
/// after must move nothing.
#[test]
fn paragraph_drops_below_an_object_in_its_space_before() {
crate::test_fonts();
use wordcraft_doc::para::{Anchor, Float, Wrap};
use wordcraft_doc::props::LineSpacing;
const BEFORE: f32 = 12.0;
const RULE_H: f32 = 1.0;
// Paragraph 0 holds the rule; paragraph 1 has the space before. Exact 14 pt lines keep the
// geometry steady. The gap between them is paragraph 1's space before, or (case 3) paragraph
// 0's space after.
let document = |rule_y: Option<f32>, before: f32, after: f32| {
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(after);
p.props.line_spacing = Some(LineSpacing::Exactly(14.0));
}
}
if let Some(y) = rule_y {
let f = Float { wrap: Wrap::TopAndBottom, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, y, ..Default::default() };
d.insert_object(&Pos::body(0, 0), rect_shape(144.0, RULE_H, f), &Default::default()).unwrap();
}
if let Some(wordcraft_doc::Block::Para(p)) = d.body.get_mut(1).map(Arc::make_mut) {
p.props.space_before = Some(before);
}
d
};
let lines = |d: &Document| {
let l = lay(d);
let top = |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 rules = shapes(&l.pages[0].items);
(top(0), top(1), rules)
};
let (anchor, probe, _) = lines(&document(None, BEFORE, 0.0));
assert!(probe > anchor + 14.0, "the probe starts below the anchor line and its space before");
// Case 1: the rule ends 6 pt into the probe's 12 pt space before (wholly inside it).
// Case 2: the rule ends 6 pt into the probe's first line.
let mut failures = Vec::new();
for (rule_bottom, label) in [(probe - 6.0, "inside space before"), (probe + 6.0, "over first line")] {
let y = rule_bottom - RULE_H - anchor;
let (_, top, shapes) = lines(&document(Some(y), BEFORE, 0.0));
assert_eq!(shapes.len(), 1, "{label}: one rule drawn: {shapes:?}");
let bottom = shapes[0].bottom();
assert!((bottom - rule_bottom).abs() < 1.0, "{label}: rule bottom {bottom} vs {rule_bottom}");
if top < bottom + BEFORE - 0.01 {
failures.push(format!("{label}: probe first line {top} must start at rule bottom {bottom} + {BEFORE} space before"));
}
}
assert!(failures.is_empty(), "{}", failures.join("; "));
// Case 3: the same rule in the previous paragraph's 12 pt space after (the probe has no
// space before of its own) takes no room, as in Word.
let (anchor, plain, _) = lines(&document(None, 0.0, BEFORE));
let y = plain - 6.0 - RULE_H - anchor;
let (_, top, shapes) = lines(&document(Some(y), 0.0, BEFORE));
assert_eq!(shapes.len(), 1, "in space after: one rule drawn: {shapes:?}");
assert!((top - plain).abs() < 0.01, "in space after: probe first line {top} must not move from {plain}");
}
/// #7143, #7276 follow-up: only the space before that is really laid out above a paragraph can
/// hold a Top-and-Bottom object. Space before removed by collapsing against the paragraph above,
/// by same-style contextual spacing, or at the top of a page takes no room, so a rule there must
/// not push the paragraph down. The part of the gap that *is* applied still counts.
#[test]
fn top_and_bottom_float_in_space_before_not_laid_out_takes_no_room() {
crate::test_fonts();
use wordcraft_doc::para::{Anchor, Float, Wrap};
use wordcraft_doc::props::LineSpacing;
const RULE_H: f32 = 1.0;
// Paragraph 1's space before and paragraph 0's space after make the gap between them, which
// Word merges. Exact 14 pt lines keep the geometry steady. Paragraph 1's own contextual
// spacing (or its page break) can remove the space before, leaving paragraph 0's after.
let document = |after: f32, before: f32, contextual: bool, page_break: bool| {
let mut d = Document::from_text("Anchor line.\nProbe line with several words in it.");
for block in &mut d.body {
if let wordcraft_doc::Block::Para(p) = Arc::make_mut(block) {
p.props.space_before = Some(0.0);
p.props.space_after = Some(after);
p.props.line_spacing = Some(LineSpacing::Exactly(14.0));
p.props.contextual_spacing = Some(false);
}
}
if let Some(wordcraft_doc::Block::Para(p)) = d.body.get_mut(1).map(Arc::make_mut) {
p.props.space_before = Some(before);
p.props.contextual_spacing = Some(contextual);
p.props.page_break_before = Some(page_break);
}
d
};
// The page and top of block `block`'s first line.
let top_in = |l: &DocLayout, block: u32| {
l.pages.iter().enumerate().find_map(|(pi, page)| {
page.items.iter().find_map(|i| match i {
Placed::Lines { story: StoryRef::Body, path, y, .. } if path.0 == [block] => Some((pi, *y)),
_ => None,
})
})
};
// The rule's bottom is `above` points above the probe's first line; it is anchored in
// paragraph `anchor`. Returns the probe's page, its top, and the drawn rules.
let lines = |after: f32, before: f32, contextual: bool, page_break: bool, anchor: u32, above: f32| {
let plain = lay(&document(after, before, contextual, page_break));
let (pi, probe) = top_in(&plain, 1).unwrap();
let (_, anchor_top) = top_in(&plain, anchor).unwrap();
let mut d = document(after, before, contextual, page_break);
let f = Float {
wrap: Wrap::TopAndBottom,
h_rel: Anchor::Column,
v_rel: Anchor::Paragraph,
y: probe - above - RULE_H - anchor_top,
..Default::default()
};
d.insert_object(&Pos::body(anchor as usize, 0), rect_shape(144.0, RULE_H, f), &Default::default()).unwrap();
let l = lay(&d);
let (page, top) = top_in(&l, 1).unwrap();
let rules = shapes(&l.pages[page].items);
(page == pi, probe, top, rules)
};
let mut failures = Vec::new();
let mut check = |after: f32, before: f32, contextual: bool, page_break: bool, anchor: u32, above: f32, delta: f32, label: &str| {
let (same_page, plain, top, rules) = lines(after, before, contextual, page_break, anchor, above);
if !same_page {
failures.push(format!("{label}: the probe moved to another page: {rules:?}"));
} else if rules.len() != 1 {
failures.push(format!("{label}: {} rules drawn, not one: {rules:?}", rules.len()));
} else if (top - plain - delta).abs() >= 0.01 {
failures.push(format!("{label}: probe first line {top} moved {} from {plain}, expected {delta}", top - plain));
}
};
// 12 pt before collapsed against 12 pt after: none of the space before is laid out, so the
// rule in that 12 pt space after moves nothing.
check(12.0, 12.0, false, false, 0, 6.0, 0.0, "collapsed space before");
// 12 pt before against 8 pt after: 4 pt of it is laid out, so a rule ending 2 pt above the
// first line passes it to 2 pt below the rule...
check(8.0, 12.0, false, false, 0, 2.0, 2.0, "applied part of a merged space before");
// ...but the 8 pt collapsed above it still takes no room.
check(8.0, 12.0, false, false, 0, 6.0, 0.0, "collapsed part of a merged space before");
// A rule reaching into the first line below a collapsed space before takes the line below it
// with no space (none was laid out above), not with the whole declared 12 pt.
check(12.0, 12.0, false, false, 0, -6.0, 6.0, "line under a rule with the space before collapsed");
// The same when part of the gap is laid out: the line goes under the rule plus those 4 pt.
check(8.0, 12.0, false, false, 0, -2.0, 6.0, "line under a rule with part of the space before applied");
// Contextual spacing removes paragraph 1's space before; paragraph 0's after remains.
check(12.0, 12.0, true, false, 0, 6.0, 0.0, "contextual space before");
// At the top of a page (a page break before) the space before is suppressed.
check(0.0, 12.0, false, true, 1, 6.0, 0.0, "space before at a page top");
assert!(failures.is_empty(), "{}", failures.join("; "));
}
/// #7276 follow-up: a paragraph moved whole to the next page by Keep lines together lays out no
/// space before there, so a Top-and-Bottom object at its top takes only its own height above the
/// first line, not the space before it declares.
#[test]
fn moved_kept_paragraph_lays_out_no_space_before_under_an_object_at_its_top() {
crate::test_fonts();
use wordcraft_doc::para::{Anchor, Float, Wrap};
use wordcraft_doc::props::LineSpacing;
// 53 lines of 12 pt leave one line of the 648 pt body, too little for the kept paragraph.
const FILL: usize = 53;
const RULE_H: f32 = 2.0;
let text = format!("{}word {}", "x\n".repeat(FILL), "word ".repeat(40));
let mut d = Document::from_text(&text);
for i in 0..=FILL {
let p = d.para_mut(StoryRef::Body, &Path::top(i)).unwrap();
p.props.line_spacing = Some(LineSpacing::Exactly(12.0));
p.props.space_before = Some(0.0);
p.props.space_after = Some(0.0);
p.props.widow_control = Some(false);
}
let probe = d.para_mut(StoryRef::Body, &Path::top(FILL)).unwrap();
probe.props.keep_lines = Some(true);
probe.props.space_before = Some(12.0);
let f = Float { wrap: Wrap::TopAndBottom, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, ..Default::default() };
d.insert_object(&Pos::body(FILL, 0), rect_shape(144.0, RULE_H, f), &Default::default()).unwrap();
let l = lay(&d);
assert_eq!(l.pages.len(), 2, "the filler keeps the kept paragraph off page 1");
let top = l.pages[1]
.items
.iter()
.find_map(|i| match i {
Placed::Lines { story: StoryRef::Body, path, y, .. } if path.0 == [FILL as u32] => Some(*y),
_ => None,
})
.expect("the kept paragraph starts page 2");
let rules = shapes(&l.pages[1].items);
assert_eq!(rules.len(), 1, "the rule is drawn with the paragraph: {rules:?}");
let bottom = rules[0].bottom();
assert!((top - bottom).abs() < 0.01, "the first line {top} starts at the rule's bottom {bottom}, with no space before laid out above it");
}
/// #8614: when a side-wrapping object pushes the first line down before it is placed, the
/// space-before Top-and-Bottom band must stay anchored to the first line's original top (0), not
/// shift down with `self.top` into the paragraph's area and re-apply `space_before` below a
/// Top-and-Bottom object ending there.
#[test]
fn side_wrapping_push_does_not_shift_space_before_band_into_para_area() {
crate::test_fonts();
use wordcraft_doc::para::{Anchor, Float, Wrap};
use wordcraft_doc::props::LineSpacing;
const BEFORE: f32 = 12.0;
let build = |with_top_bottom: bool| {
let mut d = Document::from_text("Anchor line.\nProbe line with several words in it.");
for block in &mut d.body {
if let wordcraft_doc::Block::Para(p) = Arc::make_mut(block) {
p.props.space_before = Some(0.0);
p.props.space_after = Some(0.0);
p.props.line_spacing = Some(LineSpacing::Exactly(14.0));
}
}
if let Some(wordcraft_doc::Block::Para(p)) = d.body.get_mut(1).map(Arc::make_mut) {
p.props.space_before = Some(BEFORE);
}
let plain = lay(&d);
let top_of = |l: &DocLayout, block: u32| {
l.pages[0]
.items
.iter()
.find_map(|i| match i {
Placed::Lines { story: StoryRef::Body, path, y, .. } if path.0 == [block] => Some(*y),
_ => None,
})
.unwrap()
};
let anchor_y = top_of(&plain, 0);
let probe_y = top_of(&plain, 1);
// Full-width side-wrapping object starting at the probe's original top and extending 30 pt
// down, pushing the probe's first line to probe_y + 30.
let side = Float { wrap: Wrap::Square, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, y: probe_y - anchor_y, ..Default::default() };
d.insert_object(&Pos::body(0, 0), rect_shape(500.0, 30.0, side), &Default::default()).unwrap();
if with_top_bottom {
// Top-and-Bottom object inside the side-wrapped vertical span (18..22 pt below probe_y),
// below the original first line [0, 14] and above the Square object's bottom (30).
let tb = Float {
wrap: Wrap::TopAndBottom,
h_rel: Anchor::Column,
v_rel: Anchor::Paragraph,
y: probe_y + 18.0 - anchor_y,
..Default::default()
};
d.insert_object(&Pos::body(0, 0), rect_shape(144.0, 4.0, tb), &Default::default()).unwrap();
}
let l = lay(&d);
top_of(&l, 1)
};
let plain_wrap_top = build(false);
let with_tb_top = build(true);
assert!(
(with_tb_top - plain_wrap_top).abs() < 0.01,
"probe first line {with_tb_top} must stay at plain-wrap position {plain_wrap_top} without re-applying space_before"
);
}
#[test]
fn float_follows_its_paragraph_to_the_next_page() {
crate::test_fonts();
@@ -17974,6 +18371,186 @@ fn continuous_section_first_paragraph_running_over_keeps_first_page_header_hidde
assert!(l.pages[next..].iter().all(|p| p.hf_slot == crate::HfSlot::Default));
}
/// A continuous section starting mid-page has no first page of its own, so on its second page
/// `header_table_areas` checks its default header rather than its first-page header.
#[test]
fn continuous_section_second_page_ignores_first_page_header_table() {
use wordcraft_doc::para::Anchor;
use wordcraft_doc::props::{HeightRule, LineSpacing, TableFloat};
use wordcraft_doc::section::SectionStart;
for start in [SectionStart::Continuous, SectionStart::NextPage] {
let mut paras: Vec<String> = (0..10).map(|i| format!("Section 1 {i}")).collect();
paras.extend((0..24).map(|i| format!("Section 2 {i}")));
let mut d = Document::from_text(&paras.join("\n"));
for block in &mut d.body {
let Block::Para(p) = Arc::make_mut(block) else { panic!("paragraph") };
p.props =
ParaProps { space_before: Some(0.0), space_after: Some(0.0), line_spacing: Some(LineSpacing::Exactly(20.0)), ..Default::default() };
}
d.settings.compat_mode = 15;
let make_table = |y, height| {
let mut t = Table::new(1, 2, 300.0);
t.props.cell_margins = Some([0.0; 4]);
t.props.float = Some(TableFloat { h_rel: Anchor::Page, v_rel: Anchor::Page, x: 72.0, y, overlap: false, ..Default::default() });
t.rows[0].props.height = Some(height);
t.rows[0].props.height_rule = HeightRule::Exact;
t
};
let first_hdr = d.add_part(wordcraft_doc::PartKind::Header, vec![Arc::new(Block::Table(make_table(60.0, 80.0)))]);
let s1 = d.last_section.clone();
d.para_mut(StoryRef::Body, &Path::top(9)).unwrap().section = Some(Box::new(s1));
d.last_section.start = start;
d.last_section.title_page = true;
d.last_section.headers.first = Some(first_hdr);
d.body.push(Arc::new(Block::Table(make_table(100.0, 48.0))));
let l = lay(&d);
let begins = l.caret(&Pos::body(10, 0)).unwrap().page;
let target = match start {
SectionStart::Continuous => {
assert_eq!(l.caret(&Pos::body(9, 0)).unwrap().page, begins, "section 2 starts mid-page");
begins + 1
}
_ => begins,
};
let cell_top = l.pages[target]
.items
.iter()
.filter_map(|it| match it {
Placed::Cell { rect, .. } => Some(rect.y),
_ => None,
})
.fold(f32::MAX, f32::min);
let expected = if start == SectionStart::Continuous { 100.0 } else { 140.0 };
assert!((cell_top - expected).abs() < 0.01, "{start:?}: body floating table top {cell_top} on page {target}, expected {expected}");
}
}
/// The same for `footer_table_wraps`: body lines on a continuous section's second page do not wrap
/// around a floating table in the section's first-page footer.
#[test]
fn continuous_section_second_page_ignores_first_page_footer_table_wrap() {
use wordcraft_doc::para::Anchor;
use wordcraft_doc::props::{HeightRule, LineSpacing, TableFloat};
use wordcraft_doc::section::SectionStart;
const FLOAT_TOP: f32 = 100.0;
const TABLE_HEIGHT: f32 = 80.0;
const TABLE_WIDTH: f32 = 468.0;
for start in [SectionStart::Continuous, SectionStart::NextPage] {
let mut paras: Vec<String> = (0..10).map(|i| format!("Section 1 {i}")).collect();
let long = "Body wrap word ".repeat(22);
paras.extend((0..14).map(|_| long.clone()));
let mut d = Document::from_text(&paras.join("\n"));
for block in &mut d.body[10..] {
let Block::Para(p) = Arc::make_mut(block) else { panic!("paragraph") };
p.props =
ParaProps { space_before: Some(0.0), space_after: Some(0.0), line_spacing: Some(LineSpacing::Exactly(24.0)), ..Default::default() };
}
let mut table = Table::new(1, 1, TABLE_WIDTH);
table.props.cell_margins = Some([0.0; 4]);
table.props.float = Some(TableFloat { y: FLOAT_TOP, h_rel: Anchor::Page, v_rel: Anchor::Page, ..Default::default() });
table.rows[0].props.height = Some(TABLE_HEIGHT);
table.rows[0].props.height_rule = HeightRule::Exact;
let first_ftr = d.add_part(wordcraft_doc::PartKind::Footer, vec![Arc::new(Block::Table(table))]);
let s1 = d.last_section.clone();
d.para_mut(StoryRef::Body, &Path::top(9)).unwrap().section = Some(Box::new(s1));
d.last_section.start = start;
d.last_section.title_page = true;
d.last_section.footers.first = Some(first_ftr);
let l = lay(&d);
let begins = l.caret(&Pos::body(10, 0)).unwrap().page;
let target = match start {
SectionStart::Continuous => {
assert_eq!(l.caret(&Pos::body(9, 0)).unwrap().page, begins, "section 2 starts mid-page");
begins + 1
}
_ => begins,
};
assert!(l.pages.len() > target, "{start:?}: expected page {target}");
let margin_left = d.last_section.margin_left;
let beside: Vec<_> = (10..d.body.len() as u32)
.flat_map(|b| line_boxes(&l, target, b, margin_left))
.filter(|(_, top, _, bottom)| *bottom > FLOAT_TOP + 0.01 && *top < FLOAT_TOP + TABLE_HEIGHT - 0.01)
.collect();
assert!(!beside.is_empty(), "{start:?}: no body lines beside footer table band on page {target}");
if start == SectionStart::Continuous {
assert!(
beside.iter().all(|(left, ..)| (*left - margin_left).abs() < 0.01),
"{start:?}: continuous second page wrapped around first-page footer table: {beside:?}"
);
} else {
assert!(
beside.iter().all(|(left, ..)| *left >= TABLE_WIDTH - 0.01),
"{start:?}: new-page section failed to wrap around first-page footer table: {beside:?}"
);
}
}
}
/// The same `begins_section` rule governs `footer_story` (first-page versus default footer), both
/// when the continuous section starts mid-page with separate paragraphs and when its first
/// paragraph runs over onto the next page.
#[test]
fn continuous_section_first_page_footer_is_not_shown_on_its_second_page() {
use wordcraft_doc::section::SectionStart;
for start in [SectionStart::Continuous, SectionStart::NextPage] {
let text = (0..140).map(|i| format!("Paragraph {i}")).collect::<Vec<_>>().join("\n");
let mut d = Document::from_text(&text);
let part = |d: &mut Document, t: &str| {
d.add_part(wordcraft_doc::PartKind::Footer, vec![wordcraft_doc::para_block(Paragraph::with_text(t, Default::default()))])
};
let (one, first, two) = (part(&mut d, "ONE"), part(&mut d, "FIRST"), part(&mut d, "TWO"));
let mut s1 = d.last_section.clone();
s1.footers.default = Some(one);
d.para_mut(StoryRef::Body, &Path::top(19)).unwrap().section = Some(Box::new(s1));
d.last_section.start = start;
d.last_section.title_page = true;
d.last_section.footers.first = Some(first);
d.last_section.footers.default = Some(two);
let l = lay(&d);
let begins = l.caret(&Pos::body(20, 0)).unwrap().page;
let shown: Vec<_> = l.pages.iter().map(|p| p.footer_story).collect();
assert!(l.pages.len() > begins + 2, "{start:?}: the second section runs over several pages");
match start {
SectionStart::Continuous => {
assert_eq!(l.caret(&Pos::body(19, 0)).unwrap().page, begins, "the second section starts part-way down a page");
assert_eq!(shown[begins], Some(one), "{start:?}: the page where it starts keeps the first section's footer");
assert!(
shown[begins + 1..].iter().all(|f| *f == Some(two)),
"{start:?}: then its default footer, never its first-page one: {shown:?}"
);
}
_ => {
assert_eq!(shown[begins], Some(first), "{start:?}: a section on a new page shows its first-page footer there");
assert!(shown[begins + 1..].iter().all(|f| *f == Some(two)), "{start:?}: {shown:?}");
}
}
}
let mut paras: Vec<String> = (0..44).map(|i| format!("Paragraph {i}")).collect();
paras.push("word ".repeat(1200));
paras.extend((0..60).map(|i| format!("After {i}")));
let mut d = Document::from_text(&paras.join("\n"));
let part = |d: &mut Document, t: &str| {
d.add_part(wordcraft_doc::PartKind::Footer, vec![wordcraft_doc::para_block(Paragraph::with_text(t, Default::default()))])
};
let (one, first, two) = (part(&mut d, "ONE"), part(&mut d, "FIRST"), part(&mut d, "TWO"));
let mut s1 = d.last_section.clone();
s1.footers.default = Some(one);
d.para_mut(StoryRef::Body, &Path::top(43)).unwrap().section = Some(Box::new(s1));
d.last_section.start = SectionStart::Continuous;
d.last_section.title_page = true;
d.last_section.footers.first = Some(first);
d.last_section.footers.default = Some(two);
let l = lay(&d);
let begins = l.caret(&Pos::body(44, 0)).unwrap().page;
assert_eq!(l.caret(&Pos::body(43, 0)).unwrap().page, begins, "the second section starts part-way down a page");
let next = begins + 1;
assert!(l.pages.get(next).is_some_and(|p| p.first_block == 44), "its first paragraph runs over onto the next page");
let shown: Vec<_> = l.pages.iter().map(|p| p.footer_story).collect();
assert_eq!(shown[begins], Some(one));
assert!(shown[next..].iter().all(|f| *f == Some(two)), "{shown:?}");
}
/// Sections starting continuously one after another still go onto new pages: a paragraph that
/// doesn't fit below the text above it moves on rather than running off the page (#3907). A
/// hundred one-line sections lay out like a hundred plain paragraphs.
@@ -18924,6 +19501,25 @@ fn many_list_definitions_keep_the_list_numbering_in_order() {
assert_eq!(labels.last().copied(), Some("512."));
}
/// The right-tab rule above is for right tabs only: a decimal tab whose number doesn't fit by the
/// margin still wraps, as on main (the review's case: with the rule applied to decimal tabs too
/// the number stayed on the line and ran 38 pt past the margin).
#[test]
fn a_decimal_tab_by_the_margin_still_wraps_its_number() {
use wordcraft_doc::props::{TabAlign, TabLeader, TabStop};
let text = format!("{}\t12.3456789", "x".repeat(84));
let n = text.chars().count();
let mut d = Document::from_text(&text);
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| {
p.indent_right = Some(6.0);
p.tabs = Some(vec![TabStop { pos: 468.0, align: TabAlign::Decimal, leader: TabLeader::None }]);
})
.unwrap();
let l = lay(&d);
let (first, end) = (l.caret(&Pos::body(0, 0)).unwrap(), l.caret(&Pos::body(0, n)).unwrap());
assert!(end.top > first.top, "the number stays on the first line and ends at {}", end.x);
}
/// Page-anchored body text frames use page coordinates; other anchors remain in body flow.
#[test]
fn a_body_text_frame_respects_its_anchors() {
@@ -19008,6 +19604,44 @@ fn body_text_wraps_around_a_page_anchored_text_frame() {
assert!(next.top < 172.0, "text on the next page starts at its top: {}", next.top);
}
/// A page-anchored text frame is not content above the paragraph after it: a paragraph with a
/// page break before stays on the frame's page, and the frame's wrap area moves it below or
/// beside the frame.
#[test]
fn a_page_break_before_after_a_page_anchored_frame_keeps_one_page() {
crate::test_fonts();
use wordcraft_doc::props::TextFrame;
let caret_after = |wrap: &str| {
let mut d = Document::new();
let mut framed = wordcraft_doc::Paragraph::with_text("Framed line", Default::default());
framed.props.frame = Some(TextFrame {
w: Some(150.0),
h: Some(100.0),
h_exact: true,
x: 72.0,
y: 72.0,
h_anchor: "page".into(),
v_anchor: "page".into(),
wrap: wrap.into(),
..Default::default()
});
d.insert_block(StoryRef::Body, &Path::top(0), (*wordcraft_doc::para_block(framed)).clone()).unwrap();
let mut body = wordcraft_doc::Paragraph::with_text("Body line", Default::default());
body.props.page_break_before = Some(true);
d.insert_block(StoryRef::Body, &Path::top(1), (*wordcraft_doc::para_block(body)).clone()).unwrap();
let l = lay(&d);
(l.caret(&Pos { story: StoryRef::Body, path: Path::top(1), off: 0 }).unwrap(), l.pages.len())
};
let (below, pages) = caret_after("notBeside");
assert_eq!(below.page, 0, "a page break before after a frame stays on the frame's page");
assert_eq!(pages, 1, "the frame's page is the only page: {pages}");
assert!(below.top >= 172.0 - 0.5, "the text is below the frame: {}", below.top);
let (beside, pages) = caret_after("around");
assert_eq!(beside.page, 0, "a page break before after a frame stays on the frame's page");
assert_eq!(pages, 1, "the frame's page is the only page: {pages}");
assert!(beside.x >= 222.0 - 0.5, "the text is beside the frame: {}", beside.x);
}
/// A page-anchored text frame outside the column still blocks a paragraph whose negative indent
/// takes its text over the frame: the text goes on to the next page. A right-to-left paragraph's
/// leading indent is on the right.
@@ -19085,3 +19719,78 @@ fn evict_unused_caps_stale_entries_across_repeated_edits() {
assert!(c.len() <= base + 1025, "stale cache entries must be bounded (got {}, base {base})", c.len());
}
}
/// #8613: a Top-and-Bottom object ending above a paragraph's applied space before cannot affect
/// it, so paragraphs below keep empty exclusions and hit the cache when shifted vertically, and
/// paragraphs below it in a box are not laid out twice.
#[test]
fn top_and_bottom_float_above_space_before_keeps_cache_hits_on_shift() {
crate::test_fonts();
use wordcraft_doc::para::{Anchor, Float, Wrap};
use wordcraft_doc::props::LineSpacing;
let mut d = Document::from_text(&"line\n".repeat(12));
for block in &mut d.body {
if let wordcraft_doc::Block::Para(p) = Arc::make_mut(block) {
p.props.line_spacing = Some(LineSpacing::Exactly(12.0));
p.props.space_before = Some(0.0);
p.props.space_after = Some(0.0);
}
}
if let Some(wordcraft_doc::Block::Para(p)) = d.body.get_mut(4).map(Arc::make_mut) {
p.props.space_before = Some(12.0);
}
let f = Float { wrap: Wrap::TopAndBottom, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, ..Default::default() };
d.insert_object(&Pos::body(0, 0), rect_shape(144.0, 10.0, f), &Default::default()).unwrap();
let mut c = LayoutCache::new();
let before = layout(&d, &mut c, &LayoutOptions::default());
let y_before = before.caret(&Pos::body(6, 0)).unwrap().top;
let misses = c.misses;
d.insert_text(&Pos::body(2, 0), &"word ".repeat(30), &Default::default()).unwrap();
let after = layout(&d, &mut c, &LayoutOptions::default());
let y_after = after.caret(&Pos::body(6, 0)).unwrap().top;
assert!(y_after > y_before + 10.0, "paragraphs below shifted down ({y_before} -> {y_after})");
assert_eq!(c.misses, misses + 1, "only the edited paragraph should miss the cache");
}
/// #8613: in table cells and other boxes, paragraphs below a Top-and-Bottom float (and clear of
/// its space-before band) get empty exclusions, so they are laid out once and hit the cache when
/// shifted vertically.
#[test]
fn top_and_bottom_float_in_cell_keeps_cache_hits_on_shift() {
crate::test_fonts();
use wordcraft_doc::para::{Anchor, Float, Wrap};
use wordcraft_doc::props::LineSpacing;
let mut d = Document::new();
let mut t = Table::new(1, 1, 468.0);
t.props.fixed = true;
t.rows[0].cells[0].blocks = (0..6)
.map(|i| {
let mut p = Paragraph::with_text(&format!("cell line {i}"), Default::default());
p.props.line_spacing = Some(LineSpacing::Exactly(12.0));
p.props.space_before = Some(0.0);
p.props.space_after = Some(0.0);
wordcraft_doc::para_block(p)
})
.collect();
d.body = vec![Arc::new(wordcraft_doc::Block::Table(t))];
let cell_pos = |para: usize| Pos { story: StoryRef::Body, path: Path(vec![0, 0, 0, para as u32]), off: 0 };
let f = Float { wrap: Wrap::TopAndBottom, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, ..Default::default() };
d.insert_object(&cell_pos(0), rect_shape(100.0, 10.0, f), &Default::default()).unwrap();
let mut c = LayoutCache::new();
let before = layout(&d, &mut c, &LayoutOptions::default());
let y_before = before.caret(&cell_pos(4)).unwrap().top;
// Paragraph 0 holds the float so it lays out twice; paragraphs 1..6 sit below it and lay out once each.
assert_eq!(c.misses, 7, "paragraphs below the float should be laid out only once");
let misses = c.misses;
d.insert_text(&cell_pos(1), &"word ".repeat(30), &Default::default()).unwrap();
let after = layout(&d, &mut c, &LayoutOptions::default());
let y_after = after.caret(&cell_pos(4)).unwrap().top;
assert!(y_after > y_before + 10.0, "cell paragraphs below shifted down ({y_before} -> {y_after})");
assert_eq!(c.misses, misses + 1, "only the edited cell paragraph should miss the cache");
}
+28
View File
@@ -133,6 +133,34 @@ fn spaces_punctuation_hangul_and_latin_alone_get_nothing() {
}
}
/// Word adds no automatic space, on either side, beside an ideograph whose run names an installed
/// East Asian font without ideographs, even though a substituted face draws it (#6591: 0.00 pt
/// with `w:eastAsia="Times New Roman"`). A font that isn't installed keeps the space.
#[test]
fn an_east_asian_font_without_ideographs_turns_it_off() {
crate::test_fonts();
let with = |latin: Option<&str>, asian: &str| {
let mut d = Document::from_text("法院94年A字");
let p = para0(&mut d);
let len = p.text.len();
p.format(0, len, &|c: &mut CharProps| {
c.font = latin.map(str::to_string);
c.font_ea = Some(asian.to_string());
})
.unwrap();
d
};
// Source Serif 4 is installed for the tests and has no ideographs.
for d in [with(None, "Source Serif 4"), with(Some("Source Serif 4"), "Source Serif 4")] {
assert!(gaps(&d).iter().all(|g| *g == 0.0), "{:?}", gaps(&d));
}
let d = with(None, "No Such East Asian Font 6591");
let q = quarter(&d);
// The room after each Latin character follows the face that draws it, as without a
// `w:eastAsia` font at all (#6583).
assert_eq!(gaps(&d), [0.0, q, 0.0, after(&d, 7), q, after(&d, 11), 0.0], "a font that isn't installed");
}
#[test]
fn a_field_result_is_classed_by_the_text_it_shows() {
crate::test_fonts();
+160
View File
@@ -0,0 +1,160 @@
//! A long word broken by letters: the letter ending the line is measured without its kerning
//! pair with the letter that goes on to the next line (Word, a line's width swept a twip at a
//! time: the letters before a broken kerning pair fit only where they fit on their own).
use super::*;
#[test]
fn a_word_broken_by_letters_ends_without_its_kerning_pair() {
let text = "AVAVAVAVAVAVAVAVAVAV";
let doc = |indent_right: f32| {
let mut d = Document::from_text(text);
Arc::make_mut(&mut d.styles).default_chr.kern = Some(1.0);
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| p.indent_right = Some(indent_right)).unwrap();
d
};
// The word on one line: the first five letters' width with the "AV" pair after the fifth
// and without it.
let l = lay(&doc(0.0));
let para = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para.clone()) } else { None }).unwrap();
let paired: f32 = para.clusters[..5].iter().map(|c| c.adv).sum();
let alone = paired - para.clusters[4].kern;
assert!(alone - paired > 0.1, "the test font kerns \"AV\": {paired} vs {alone}");
// A line between the two takes four letters, as in Word; with the pair it took five.
let got = body_lines(&lay(&doc(468.0 - (paired + alone) / 2.0)), text);
assert_eq!(got.first().map(String::as_str), Some("AVAV"), "{got:?}");
// A line as wide as the five letters alone takes them.
let got = body_lines(&lay(&doc(468.0 - alone - 0.004)), text);
assert_eq!(got.first().map(String::as_str), Some("AVAVA"), "{got:?}");
}
/// Inter under the family name "Kernx" with its `GPOS` hidden and an old-style `kern` table that
/// kerns "AV" by `units` (and nothing else): a shaper splits such a pair between the two letters,
/// half in the first one's advance and half in the second one's advance and offset.
fn legacy_kern_family(units: i16) -> &'static str {
const FAMILY: &str = "Kernx";
let inter = wordcraft_fonts::word::resolve("Inter", false, false).face;
let (a, v) = (inter.glyph_for('A') as u16, inter.glyph_for('V') as u16);
let src = inter.data().to_vec();
let u16_at = |d: &[u8], o: usize| u16::from_be_bytes([d[o], d[o + 1]]) as usize;
let u32_at = |d: &[u8], o: usize| u32::from_be_bytes([d[o], d[o + 1], d[o + 2], d[o + 3]]) as usize;
// The tables, `GPOS` renamed so no shaper reads it, and the new `kern` table.
let mut tables: Vec<([u8; 4], Vec<u8>)> = (0..u16_at(&src, 4))
.map(|i| {
let r = 12 + 16 * i;
let tag: [u8; 4] = src[r..r + 4].try_into().unwrap();
let tag = if &tag == b"GPOS" { *b"XPOS" } else { tag };
(tag, src[u32_at(&src, r + 8)..u32_at(&src, r + 8) + u32_at(&src, r + 12)].to_vec())
})
.collect();
let mut kern = Vec::new();
for x in [0u16, 1, 0, 20, 0x0001, 1, 6, 0, 0, a, v] {
kern.extend(x.to_be_bytes());
}
kern.extend(units.to_be_bytes());
tables.push((*b"kern", kern));
tables.sort_by_key(|t| t.0);
// The font file again: its header, the table records, then the tables (4-byte aligned).
let n = tables.len();
let mut data = src[..12].to_vec();
data[4..6].copy_from_slice(&(n as u16).to_be_bytes());
let mut at = 12 + 16 * n;
let mut body = Vec::new();
for (tag, t) in &tables {
data.extend(tag);
data.extend(0u32.to_be_bytes());
data.extend((at as u32).to_be_bytes());
data.extend((t.len() as u32).to_be_bytes());
body.extend(t);
while body.len() % 4 != 0 {
body.push(0);
}
at = 12 + 16 * n + body.len();
}
data.extend(body);
// The family name, in the name table's UTF-16 and single-byte records alike.
let name = tables.iter().take_while(|t| &t.0 != b"name").map(|t| t.1.len().div_ceil(4) * 4).sum::<usize>() + 12 + 16 * n;
let len = tables.iter().find(|t| &t.0 == b"name").map_or(0, |t| t.1.len());
let wide = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::<Vec<u8>>();
for (from, to) in [(wide("Inter"), wide(FAMILY)), (b"Inter".to_vec(), FAMILY.as_bytes().to_vec())] {
for i in name..name + len - from.len() {
if data[i..i + from.len()] == from[..] {
data[i..i + from.len()].copy_from_slice(&to);
}
}
}
wordcraft_fonts::FontDb::global().add_font(data);
FAMILY
}
/// A letter ending a line whose kerning pair with the letter before it the shaper split between
/// them keeps that pair: only its pair with the letter going on to the next line is dropped
/// (Word for Windows, a font with only an old-style `kern` table: "...3Vy" of a base64 token on
/// one line, where the "y" carrying half the "Vy" pair measured it wider and moved it on).
#[test]
fn a_letter_ending_a_line_keeps_its_pair_with_the_letter_before() {
crate::test_fonts();
let text = "AVAVAVAVAVAVAVAVAVAV";
let family = legacy_kern_family(-300);
let doc = |indent_right: f32| {
let mut d = Document::from_text(text);
let st = Arc::make_mut(&mut d.styles);
st.default_chr.kern = Some(1.0);
st.default_chr.font = Some(family.into());
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| p.indent_right = Some(indent_right)).unwrap();
d
};
let l = lay(&doc(0.0));
let para = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para.clone()) } else { None }).unwrap();
// "AVAVAV" on a line: the "AV" pairs in it kerned, the "VA" after it not kerned at all.
let six: f32 = para.clusters[..6].iter().map(|c| c.adv).sum();
assert!(para.clusters[0].kern < -0.5, "the test font kerns \"AV\": {}", para.clusters[0].kern);
let got = body_lines(&lay(&doc(468.0 - six - 0.004)), text);
assert_eq!(got.first().map(String::as_str), Some("AVAVAV"), "{got:?}");
}
/// A ligature's kerning pair with the letter after it belongs on the ligature's last cluster, not
/// on its head (#8618): a forced character wrap inside the ligature must not subtract the pair
/// after the whole ligature, and a line ending after the ligature drops that pair.
#[test]
fn a_ligatures_kerning_pair_sits_on_its_last_cluster() {
crate::test_fonts();
let text = "flYflYflYflY";
let doc = |indent_right: f32| {
let mut d = Document::from_text(text);
let st = Arc::make_mut(&mut d.styles);
st.default_chr.font = Some("Source Serif 4".into());
st.default_chr.size = Some(14.0);
st.default_chr.kern = Some(1.0);
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| p.indent_right = Some(indent_right)).unwrap();
d
};
let l = lay(&doc(0.0));
let para = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para.clone()) } else { None }).unwrap();
assert!(para.clusters[0].g1 > para.clusters[0].g0 && para.clusters[1].g1 == para.clusters[1].g0, "fixture forms an \"fl\" ligature");
assert_eq!(para.clusters[0].kern, 0.0, "the ligature's head cluster carries no kerning pair");
assert!(para.clusters[1].kern < -0.3, "the ligature's last cluster carries its pair with \"Y\": {}", para.clusters[1].kern);
assert_eq!(para.clusters[3].kern, 0.0);
let paired: f32 = para.clusters[..5].iter().map(|c| c.adv).sum();
let alone = paired - para.clusters[4].kern;
assert!(alone - paired > 0.3, "Source Serif 4 kerns \"fl\" + \"Y\": {paired} vs {alone}");
// Between paired and alone: "flYfl" fits only with its pair with "Y", so "fl" wraps whole.
let got = body_lines(&lay(&doc(468.0 - (paired + alone) / 2.0)), text);
assert_eq!(got.first().map(String::as_str), Some("flY"), "{got:?}");
// Wide enough for "flYfl" without the pair after it.
let got = body_lines(&lay(&doc(468.0 - alone - 0.004)), text);
assert_eq!(got.first().map(String::as_str), Some("flYfl"), "{got:?}");
// A three-letter ligature ("ffi") also puts its pair with "V" only on its last cluster.
let mut d3 = Document::from_text("ffiV");
let st3 = Arc::make_mut(&mut d3.styles);
st3.default_chr.font = Some("Source Serif 4".into());
st3.default_chr.size = Some(14.0);
st3.default_chr.kern = Some(1.0);
let l3 = lay(&d3);
let p3 = l3.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para.clone()) } else { None }).unwrap();
assert!(p3.clusters[0].g1 > p3.clusters[0].g0 && p3.clusters[1].g1 == p3.clusters[1].g0 && p3.clusters[2].g1 == p3.clusters[2].g0);
assert_eq!(p3.clusters[0].kern, 0.0);
assert_eq!(p3.clusters[1].kern, 0.0);
assert!(p3.clusters[2].kern < -0.2, "last cluster of \"ffi\" carries pair with \"V\": {}", p3.clusters[2].kern);
}
+10 -2
View File
@@ -107,6 +107,7 @@ fn write_attempt(doc: &Document, lay: &DocLayout, opts: &PdfOptions, pages: &[us
objects: crate::exporter::ObjectLookup::new(doc),
at: (0, 0),
links: Vec::new(),
last_link: None,
bookmarks: std::cell::OnceCell::new(),
};
if let Some(o) = ex.outline(pages) {
@@ -136,8 +137,15 @@ fn write_attempt(doc: &Document, lay: &DocLayout, opts: &PdfOptions, pages: &[us
}
}
surface.finish();
for annotation in annotations {
kp.add_annotation(annotation);
for (annotation, tag_slot) in annotations {
if opts.tagged
&& let Some((para_idx, child_idx)) = tag_slot
{
let annot_id = kp.add_tagged_annotation(annotation);
ex.attach_link_annotation(para_idx, child_idx, annot_id);
} else {
kp.add_annotation(annotation);
}
}
kp.finish();
}
+52 -2
View File
@@ -18,6 +18,16 @@ mod objects;
pub(crate) use objects::ObjectLookup;
mod text;
pub(crate) struct LinkRect {
pub(crate) x0: f32,
pub(crate) y0: f32,
pub(crate) x1: f32,
pub(crate) y1: f32,
pub(crate) target: String,
/// `(para_idx, child_idx)` in `Exporter::tags` for this link's `Tag::Link` group.
pub(crate) tag: Option<(usize, usize)>,
}
pub(crate) struct Exporter<'a> {
pub(crate) doc: &'a Document,
pub(crate) lay: &'a DocLayout,
@@ -42,8 +52,10 @@ pub(crate) struct Exporter<'a> {
pub(crate) objects: ObjectLookup<'a>,
/// Where the item being drawn is read ([`TagEntry::at`]).
pub(crate) at: (usize, usize),
/// Link rectangles on the current page: (x0, y0, x1, y1, target).
pub(crate) links: Vec<(f32, f32, f32, f32, String)>,
/// Link rectangles on the current page.
pub(crate) links: Vec<LinkRect>,
/// Index in `links` touched by the most recent `Draw::Glyphs` item, if any.
pub(crate) last_link: Option<usize>,
/// Bookmark positions by name (the first of a name wins), gathered once: looking each internal
/// link up by walking the whole document made a long document with a linked table of contents
/// take seconds to export.
@@ -194,10 +206,48 @@ impl Exporter<'_> {
}
}
/// Attach a paragraph's marked-content `id` to its `Tag::Link` group when `draw` recorded a
/// link rectangle, or directly to the paragraph entry otherwise.
fn attach_para_link(&mut self, idx: usize, id: Identifier) {
if let Some(li) = self.last_link.take()
&& let Some(link) = self.links.get_mut(li)
{
if let Some((p_idx, c_idx)) = link.tag
&& let Some(Node::Group(g)) = self.tags.get_mut(p_idx).and_then(|e| e.children.get_mut(c_idx))
{
g.push(Node::Leaf(id));
return;
}
if let Some(e) = self.tags.get_mut(idx) {
let c_idx = e.children.len();
e.children.push(Node::Group(TagGroup::with_children(Tag::Link, vec![Node::Leaf(id)])));
link.tag = Some((idx, c_idx));
return;
}
}
if let Some(e) = self.tags.get_mut(idx) {
e.children.push(Node::Leaf(id));
}
}
/// Insert a link annotation's `OBJR` identifier as the first child of its `Tag::Link` group.
pub(crate) fn attach_link_annotation(&mut self, para_idx: usize, child_idx: usize, annot_id: Identifier) {
if let Some(Node::Group(g)) = self.tags.get_mut(para_idx).and_then(|e| e.children.get_mut(child_idx)) {
g.children.insert(0, Node::Leaf(annot_id));
}
}
/// One draw of a paragraph's line, tagged for what it is: text as the paragraph's content
/// (structure entry `idx`), pictures and figures on their own, anything else an artifact.
fn line_item(&mut self, s: &mut Surface, d: &Draw, idx: usize, story: StoryRef, path: &DocPath) {
match d {
Draw::Glyphs { link: Some(_), .. } if self.opts.tagged && self.opts.links => {
self.last_link = None;
let id = s.start_tagged(ContentTag::Span(SpanTag::empty()));
self.draw(s, d);
s.end_tagged();
self.attach_para_link(idx, id);
}
Draw::Glyphs { .. } | Draw::Turned { .. } => self.tagged(s, Role::Para(idx), None, |me, s| me.draw(s, d)),
// A picture marked decorative: an artifact screen readers skip.
Draw::Image { decorative: true, .. } => self.tagged(s, Role::Artifact(ArtifactType::Other), None, |me, s| me.draw(s, d)),
+3 -1
View File
@@ -31,7 +31,9 @@ impl Exporter<'_> {
}
None => self.glyphs(s, face, *size, glyphs, paint, (text, ranges)),
}
if let Some(l) = link {
if self.opts.links
&& let Some(l) = link
{
self.link_rect(face, *size, glyphs, l);
}
}
+14 -16
View File
@@ -53,24 +53,22 @@ impl Exporter<'_> {
None
}
pub(crate) fn annotations(&self, fit: Fit) -> Vec<Annotation> {
pub(super) fn link_target(&self, target: &str) -> Option<Target> {
if let Some(name) = target.strip_prefix('#') {
self.bookmark(name).map(|(page, x, y)| Target::Destination(XyzDestination::new(page, Point::from_xy(x, y)).into()))
} else {
// Unsafe targets (javascript:, file:, shares, other schemes) get no link; the text stays.
write::uri_target(target)
}
}
pub(crate) fn annotations(&self, fit: Fit) -> Vec<(Annotation, Option<(usize, usize)>)> {
let mut v = Vec::new();
for (x0, y0, x1, y1, target) in &self.links {
let ((x0, y0), (x1, y1)) = (fit.point(*x0, *y0), fit.point(*x1, *y1));
for link in &self.links {
let ((x0, y0), (x1, y1)) = (fit.point(link.x0, link.y0), fit.point(link.x1, link.y1));
let Some(rect) = krilla::geom::Rect::from_ltrb(x0, y0, x1, y1) else { continue };
let t = if let Some(name) = target.strip_prefix('#') {
match self.bookmark(name) {
Some((page, x, y)) => Target::Destination(XyzDestination::new(page, Point::from_xy(x, y)).into()),
None => continue,
}
} else {
// Unsafe targets (javascript:, file:, shares, other schemes) get no link; the text stays.
match write::uri_target(target) {
Some(t) => t,
None => continue,
}
};
v.push(Annotation::new_link(LinkAnnotation::new(rect, t), Some(target.clone())));
let Some(t) = self.link_target(&link.target) else { continue };
v.push((Annotation::new_link(LinkAnnotation::new(rect, t), Some(link.target.clone())), link.tag));
}
v
}
+23 -7
View File
@@ -158,25 +158,41 @@ impl Exporter<'_> {
}
}
/// Whether a link's `Link` group is still the last content of its paragraph, so more linked text
/// can join it without being read ahead of unlinked text drawn since. Untagged links always continue.
fn link_run_continues(&self, tag: Option<(usize, usize)>) -> bool {
match tag {
None => true,
Some((p, c)) => self.tags.get(p).is_some_and(|e| e.children.len() == c + 1),
}
}
pub(super) fn link_rect(&mut self, face: &FaceRef, size: f32, glyphs: &[(u32, f32, f32)], link: &str) {
let (Some(first), Some(last)) = (glyphs.first(), glyphs.last()) else { return };
let adv = face.advance(last.0) as f32 * size / face.upem.max(1.0) as f32;
let (x0, x1) = (first.1.min(last.1), first.1.max(last.1) + adv);
let (y0, y1) = (first.2 - size * 0.85, first.2 + size * 0.25);
if ![x0, x1, y0, y1].iter().all(|v| ok(*v)) {
if ![x0, x1, y0, y1].iter().all(|v| ok(*v)) || x0 >= x1 || y0 >= y1 {
return;
}
if self.link_target(link).is_none() {
return;
}
let continues = self.links.last().is_some_and(|prev| self.link_run_continues(prev.tag));
if let Some(prev) = self.links.last_mut()
&& prev.4 == link
&& (prev.1 - y0).abs() < 0.5
&& x0 - prev.2 < size
&& prev.target == link
&& (prev.y0 - y0).abs() < 0.5
&& x0 - prev.x1 < size
&& continues
{
prev.0 = prev.0.min(x0);
prev.2 = prev.2.max(x1);
prev.x0 = prev.x0.min(x0);
prev.x1 = prev.x1.max(x1);
self.last_link = Some(self.links.len() - 1);
return;
}
if self.links.len() < 10_000 {
self.links.push((x0, y0, x1, y1, link.to_string()));
self.links.push(super::LinkRect { x0, y0, x1, y1, target: link.to_string(), tag: None });
self.last_link = Some(self.links.len() - 1);
}
}
+5 -1
View File
@@ -145,12 +145,16 @@ fn into_tag_group(doc: &Document, node: StructNode) -> TagGroup {
StructNode::Leaf(g) => g,
StructNode::Table(t) => {
let doc_table = doc.table(t.story, &t.path);
// Only the unbroken run of header rows at the top of the table are headers, as layout
// counts them (`take_while(|r| r.props.header)`); a row marked as a header further down
// is a body row, so its cells get TD and not TH.
let header_rows = doc_table.map(|dt| dt.rows.iter().take_while(|r| r.props.header).count()).unwrap_or(0);
let row_nodes = t
.rows
.into_iter()
.map(|r| {
let doc_row = doc_table.and_then(|dt| dt.rows.get(r.index));
let is_header = doc_row.is_some_and(|dr| dr.props.header);
let is_header = r.index < header_rows;
let cell_nodes = r
.cells
.into_iter()
+120
View File
@@ -1946,6 +1946,7 @@ fn bookmark_destination_is_the_page_of_its_start() {
objects: crate::exporter::ObjectLookup::new(&d),
at: (0, 0),
links: Vec::new(),
last_link: None,
bookmarks: std::cell::OnceCell::new(),
};
let (page, x, y) = ex.bookmark("target").unwrap();
@@ -3730,6 +3731,31 @@ fn tables_are_tagged_with_table_tr_th_and_td() {
assert!(raw.contains("/Scope/Column") || raw.contains("/Scope /Column"), "missing /Scope /Column on TH");
}
/// Only the run of header rows at the top of the table are headers, as layout counts them: a
/// header-flagged row further down is a body row, so its cells are TD and not TH.
#[test]
fn a_header_row_below_the_top_of_the_table_is_tagged_td() {
use wordcraft_doc::{Cell, Row, Table, props::RowProps};
let mut d = Document::from_text("A table.");
let header = Row {
props: RowProps { header: true, ..Default::default() },
cells: vec![Cell::with_text("Head"), Cell::with_text("Col2")],
..Default::default()
};
let body = Row { cells: vec![Cell::with_text("Cell10"), Cell::with_text("Cell11")], ..Default::default() };
let later_header = Row {
props: RowProps { header: true, ..Default::default() },
cells: vec![Cell::with_text("Mid"), Cell::with_text("Mid2")],
..Default::default()
};
let t = Table { grid: vec![120.0, 120.0], rows: vec![header, body, later_header], ..Default::default() };
d.body.push(Arc::new(wordcraft_doc::Block::Table(t)));
let raw = String::from_utf8_lossy(&export(&d, &PdfOptions { tagged: true, compress: false, ..Default::default() }).unwrap()).into_owned();
let count = |tag: &str| raw.matches(&format!("/S/{tag}")).count() + raw.matches(&format!("/S /{tag}")).count();
assert_eq!(count("TH"), 2, "only the top header row's cells are TH");
assert_eq!(count("TD"), 4, "the body row and the later header row are TD");
}
/// A blank cell still gets its TD or TH, so a filled cell after it keeps its column.
#[test]
fn blank_table_cells_keep_their_td_and_th() {
@@ -3763,3 +3789,97 @@ fn an_all_blank_row_keeps_its_cells() {
assert_eq!(count("TR"), 2, "both rows, including the all-blank one");
assert_eq!(count("TD"), 4, "every body cell");
}
#[test]
fn link_annotations_are_tagged_with_link_and_objr() {
use hayro_syntax::object::{Array, Dict, Name, Object};
let mut p = Paragraph::with_text("Visit ", CharProps::default());
let link_props = CharProps { link: Some("https://example.com".into()), ..Default::default() };
p.insert_text(p.len(), "Example", &link_props).unwrap();
p.insert_text(p.len(), " now", &CharProps::default()).unwrap();
let mut d = Document::new();
d.core.title = "Link test".into();
d.body = vec![para_block(p)];
let bytes = export(&d, &PdfOptions { compress: false, tagged: true, ..Default::default() }).unwrap();
let pdf = hayro_syntax::Pdf::new(bytes).unwrap();
let page = &pdf.pages()[0];
let annots = page.raw().get::<Array>(b"Annots").expect("page Annots");
let annot = annots.iter::<Dict>().next().expect("link annotation");
assert!(annot.get::<i32>(b"StructParent").is_some(), "link annotation missing /StructParent");
let annot_id = format!("{:?}", annot.obj_id().expect("indirect annotation"));
let root = pdf.xref().get::<Dict>(pdf.xref().root_id()).unwrap();
let struct_tree = root.get::<Dict>(b"StructTreeRoot").expect("StructTreeRoot");
fn find_links(dict: &Dict, out: &mut Vec<(bool, Option<String>)>) {
if dict.get::<Name>(b"S").is_some_and(|s| s.as_ref() == b"Link") {
let mut has_mcid = false;
let mut objr = None;
if let Some(k) = dict.get::<Array>(b"K") {
for item in k.iter::<Object>() {
match item {
Object::Number(_) => has_mcid = true,
Object::Dict(d) if d.get::<Name>(b"Type").is_some_and(|t| t.as_ref() == b"OBJR") => {
objr = d.get::<Dict>(b"Obj").and_then(|o| o.obj_id()).map(|id| format!("{id:?}"));
}
_ => {}
}
}
}
out.push((has_mcid, objr));
}
if let Some(k) = dict.get::<Array>(b"K") {
for item in k.iter::<Object>() {
if let Object::Dict(child) = item {
find_links(&child, out);
}
}
} else if let Some(child) = dict.get::<Dict>(b"K") {
find_links(&child, out);
}
}
let mut links = Vec::new();
find_links(&struct_tree, &mut links);
assert!(!links.is_empty(), "StructTreeRoot has no /Link structure element (annot {annot_id})");
assert!(
links.iter().any(|(mcid, objr)| *mcid && objr.as_deref() == Some(&annot_id)),
"Link element missing MCID or OBJR for {annot_id}: {links:?}"
);
}
/// Linked text split by unlinked text keeps reading order: two Link elements, not one that
/// swallows the later run ahead of the text between.
#[test]
fn separated_link_runs_are_separate_link_elements() {
use hayro_syntax::object::{Array, Dict, Name, Object};
let link_props = CharProps { link: Some("https://example.com".into()), ..Default::default() };
let mut p = Paragraph::with_text("A", link_props.clone());
p.insert_text(p.len(), ".", &CharProps::default()).unwrap();
p.insert_text(p.len(), "B", &link_props).unwrap();
let mut d = Document::new();
d.body = vec![para_block(p)];
let bytes = export(&d, &PdfOptions { compress: false, tagged: true, ..Default::default() }).unwrap();
let pdf = hayro_syntax::Pdf::new(bytes).unwrap();
let root = pdf.xref().get::<Dict>(pdf.xref().root_id()).unwrap();
let tree = root.get::<Dict>(b"StructTreeRoot").expect("StructTreeRoot");
fn count(dict: &Dict) -> usize {
let mut n = usize::from(dict.get::<Name>(b"S").is_some_and(|s| s.as_ref() == b"Link"));
if let Some(k) = dict.get::<Array>(b"K") {
for item in k.iter::<Object>() {
if let Object::Dict(c) = item {
n += count(&c);
}
}
} else if let Some(c) = dict.get::<Dict>(b"K") {
n += count(&c);
}
n
}
assert_eq!(count(&tree), 2, "each separated link run needs its own Link element");
}
+3 -3
View File
@@ -1,5 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" height="20">
<rect x="7.5" y="2.5" width="5" height="9.5" rx="1" fill="none" stroke="currentColor" stroke-width="1.25"/>
<path d="M5 9.5 L5 11 L10 15 L15 11 L15 9.5" fill="none" stroke="currentColor" stroke-width="1.25"/>
<path d="M10 15 L10 18" fill="none" stroke="currentColor" stroke-width="1.25"/>
<rect x="7.5" y="2.5" width="5" height="9.5" rx="2.5" fill="none" stroke="currentColor" stroke-width="1.25"/>
<path d="M5 9.5 L5 11 L10 15 L15 11 L15 9.5" fill="none" stroke="currentColor" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M10 15 L10 18" fill="none" stroke="currentColor" stroke-width="1.25" stroke-linecap="round"/>
</svg>

Before

Width:  |  Height:  |  Size: 386 B

After

Width:  |  Height:  |  Size: 458 B

+1
View File
@@ -133,6 +133,7 @@ impl WordApp {
user_origin: false,
read_aloud_error: None,
autosave_path: None,
read_from: None,
saves_in_flight: Vec::new(),
fallback_chooser: false,
font_generation: wordcraft_fonts::FontDb::global().generation(),
+29 -8
View File
@@ -176,7 +176,11 @@ impl WordApp {
return Err(e.into());
}
if id == "file.autosave" {
return self.set_autosave(&params);
let r = self.set_autosave(&params);
if let Err(e) = &r {
self.status(e.clone());
}
return r;
}
if let Some(r) = table_pen::toggle(self, id, &params) {
return r;
@@ -326,13 +330,8 @@ impl WordApp {
self.recovery_seen = true;
self.sync_document();
}
// An explicit save to the document's own file lets AutoSave keep writing there.
if let Ok(v) = &r
&& matches!(id, "file.save" | "file.saveAs")
&& v.get("saved").and_then(Value::as_bool) == Some(true)
&& v.get("path").and_then(Value::as_str).map(std::path::Path::new) == self.session.path.as_deref()
{
self.autosave_path = self.session.path.clone();
if let Ok(v) = &r {
self.note_file_on_disk(id, &params, v);
}
// A Markdown file edited in the formatted view was written out again, not kept as it was.
if let Ok(v) = &r
@@ -349,6 +348,9 @@ impl WordApp {
if self.autosave_path.as_ref() == Some(&old) {
self.autosave_path = self.session.path.clone();
}
if self.read_from.as_ref() == Some(&old) {
self.read_from = self.session.path.clone();
}
let old = old.to_string_lossy();
self.ui.recent.retain(|r| *r != old);
}
@@ -434,6 +436,25 @@ impl WordApp {
r
}
/// Which file on disk the document is in, after `file.save`, `file.saveAs` or `file.open`.
fn note_file_on_disk(&mut self, id: &str, params: &Value, v: &Value) {
// An explicit save to the document's own file lets AutoSave keep writing there.
if matches!(id, "file.save" | "file.saveAs")
&& v.get("saved").and_then(Value::as_bool) == Some(true)
&& v.get("path").and_then(Value::as_str).map(std::path::Path::new) == self.session.path.as_deref()
{
self.autosave_path = self.session.path.clone();
self.read_from = self.session.path.clone();
}
// A file read from disk may have AutoSave turned on for it; one opened from bytes only
// names a file it never read.
// `file.open` without a path only asks for the picker, and `data` that isn't a string is
// ignored (the file is read from disk).
if id == "file.open" && params.get("path").and_then(Value::as_str).is_some() && v.get("alreadyOpen").and_then(Value::as_bool) == Some(false) {
self.read_from = if params.get("data").and_then(Value::as_str).is_some() { None } else { self.session.path.clone() };
}
}
fn after_command(&mut self, id: &str) {
self.canvas.glide.restart(craft::platform::clock::monotonic_ms());
if id == "view.outline" {
+21 -3
View File
@@ -684,13 +684,31 @@ impl WordApp {
self.autosave && self.autosave_block().is_none()
}
/// What the AutoSave switch can't lift: [`Self::autosave_block`], less a file read from disk
/// here, which the switch turns on (#3307). A document opened from bytes stays blocked.
pub fn autosave_switch_block(&self) -> Option<AutoSaveBlock> {
self.autosave_block().filter(|b| *b != AutoSaveBlock::NotSavedHere || self.read_from != self.session.path)
}
/// `file.autosave` (the AutoSave switch, and scripts): `value` turns AutoSave on or off;
/// without it, it toggles what the switch shows. Turning it on for a document AutoSave can't
/// cover is an error that says why, instead of a switch that is on but saves nothing (#196).
/// Turning it on for a file only opened here is the go-ahead a save gives (#3307), when the
/// document was read from that file; turning it off withdraws the go-ahead for this document.
pub(super) fn set_autosave(&mut self, params: &Value) -> Result<Value, String> {
let on = params.get("value").and_then(Value::as_bool).unwrap_or(!self.autosaves());
if on && let Some(block) = self.autosave_block() {
return Err(block.reason());
let on = match params.get("value") {
None => !self.autosaves(),
Some(Value::Bool(on)) => *on,
Some(_) => return Err("`value` must be true or false".into()),
};
if on && self.autosave_block().is_some() {
if let Some(block) = self.autosave_switch_block() {
return Err(block.reason());
}
self.autosave_path = self.session.path.clone();
}
if !on {
self.autosave_path = None;
}
self.autosave = on;
self.session.autosave = on;
+18
View File
@@ -941,3 +941,21 @@ fn clicking_beside_the_back_arrow_does_not_close_the_file_page() {
h.run_steps(4);
assert!(h.state().ui.backstage, "clicking beside the arrow leaves the File page open");
}
/// #7171: in a window too short for the settings column its scroll bar shows, and the buttons stop where the bar's lane
/// starts instead of running under it. The column also ends short of the preview.
#[test]
fn print_settings_buttons_stay_clear_of_the_bar_and_the_preview() {
let mut a = new_app();
a.run("text.insert", json!({"text": "Some text"})).unwrap();
a.run("ui.backstage", json!({"value": true, "page": "print"})).unwrap();
let mut h = harness(a, egui::vec2(700.0, 500.0));
h.run_steps(6);
let column = h.query_all_by_label("Print").map(|n| n.rect()).max_by(|a, b| a.height().total_cmp(&b.height())).expect("the settings column");
let pane = h.query_all_by_label("Sheet 1 of 1").map(|n| n.rect()).max_by(|a, b| a.height().total_cmp(&b.height())).expect("the preview");
assert!(pane.min.x >= column.max.x + 8.0, "a gap between the column and the preview: {column:?} {pane:?}");
for name in ["Save these pages as PDF…", "PDF document (*.pdf)"] {
let button = h.get_by_label(name).rect();
assert!(button.min.x >= column.min.x && button.max.x <= column.max.x - 4.0, "{name} leaves the bar's lane: {button:?} {column:?}");
}
}
+20 -1
View File
@@ -7,10 +7,29 @@ use super::{Pos2, WordApp};
/// coordinates) while any of it is inside the window (`top` .. `top + height`, `top` the layout's y at the window's
/// top edge), else the page at the window's top: the first whose shown band ends below it (with Hide White Space the
/// rects overlap in the hidden margins, and the next page's text already shows there), the last page past the end.
/// A page whose shown part at the top is no more than the gap to the page below it (the next row down) does not count: Go To leaves the
/// pages' margin above a page, which is more than that gap, so a sliver of the page above still shows (#7149).
pub(super) fn viewed_page(caret: Option<(usize, f64, f64)>, top: f64, layout: &PagedLayout, height: f64) -> usize {
match caret {
Some((page, from, to)) if to >= top && from <= top + height => page,
_ => layout.rects.iter().zip(&layout.bands).position(|(r, band)| r.y0 + band.1 > top).unwrap_or(layout.rects.len().saturating_sub(1)),
_ => (0..layout.rects.len())
.position(|i| {
let end = layout.rects[i].y0 + layout.bands.get(i).map_or(0.0, |band| band.1);
// The gap to the first later page whose shown part starts at or below this one's end: the page below,
// whatever the column (an incomplete last row, a Two Up cover) and with Hide White Space (a seam).
let below = |j: &usize| layout.rects.get(*j).is_some_and(|r| r.y0 + layout.bands.get(*j).map_or(0.0, |b| b.0) >= end);
// Measured from the bottom of the row (the tallest page between this one and that page): pages of different
// heights share a row, and the next row starts below the tallest.
let gap = ((i + 1)..layout.rects.len()).find(below).and_then(|j| layout.rects.get(j).map(|next| (j, next))).map_or(0.0, |(j, _)| {
let row_end = (i..j).map(|k| layout.rects[k].y0 + layout.bands.get(k).map_or(0.0, |b| b.1)).fold(end, f64::max);
// The next row's real top: its shorter pages are centred lower, so not `next`'s own top.
let shown = |k: usize| layout.rects[k].y0 + layout.bands.get(k).map_or(0.0, |b| b.0);
let next_top = (j..(j + layout.columns.max(1)).min(layout.rects.len())).map(shown).fold(shown(j), f64::min);
(next_top - row_end).max(0.0)
});
end > top + gap
})
.unwrap_or(layout.rects.len().saturating_sub(1)),
}
}
+84
View File
@@ -518,6 +518,24 @@ fn the_page_in_view_follows_the_caret_while_it_is_on_screen() {
assert_eq!(viewed_page(caret(2, 90.0), scrolled(330.0), &layout, 100.0), 3, "a caret just above the window is not in view");
}
/// Two Up centres the shorter page of a spread: the next spread's shorter first page starts lower than its row, and
/// the gap to the page above is measured to the row's top, so a visible sliver of page 0 still counts (#7149).
#[test]
fn the_page_in_view_measures_to_the_next_spreads_top() {
use craft::behavior::kurbo::Size;
use craft::pages::layout::{LayoutOptions, PageDisplay, PageSpacing, place_pages};
// Heights 100,100 | 100,200: the taller page of the second spread sits higher than its shorter neighbour.
let sizes = [Size::new(80.0, 100.0), Size::new(80.0, 100.0), Size::new(80.0, 100.0), Size::new(80.0, 200.0)];
let spacing = PageSpacing { gap: 10.0, margin: 0.0, side: 0.0, white_space_pad: 0.0, seam: 1.0 };
let options = LayoutOptions { display: PageDisplay::TwoUp, cover: false, ..LayoutOptions::WORD };
let layout = place_pages(&sizes, 1.0, Size::new(400.0, 400.0), &options, &spacing);
assert!(layout.rects[2].y0 > layout.rects[3].y0, "the shorter page is centred below the row's top");
let row_end = layout.rects[0].y1;
let at = |shown: f64| row_end - shown;
assert_eq!(viewed_page(None, at(spacing.gap * 2.0), &layout, 100.0), 0, "more than the gap of the first spread shows");
assert_eq!(viewed_page(None, at(spacing.gap / 2.0), &layout, 100.0), 2, "less than the gap is a sliver");
}
/// #856: the left margin beside body text is Word's selection bar. A click selects the line,
/// a double-click the paragraph, a triple-click (or Ctrl/⌘+click) the document; dragging
/// selects whole lines and Shift+click extends by lines.
@@ -2604,6 +2622,72 @@ fn hostile_numbers_are_ignored() {
assert!(h.state().canvas.view.offset.0.is_finite() && h.state().canvas.view.offset.1.is_finite());
}
/// `viewed_page` with the sliver of the page above that Go To leaves at the top of the window: it is not the page in view.
#[test]
fn a_sliver_of_the_page_above_is_not_the_page_in_view() {
let rects: Vec<craft::behavior::kurbo::Rect> =
(0..4).map(|i| craft::behavior::kurbo::Rect::new(0.0, f64::from(i) * 110.0, 80.0, f64::from(i) * 110.0 + 100.0)).collect();
let layout = craft::pages::layout::PagedLayout { rects, size: Default::default(), columns: 1, bands: vec![(0.0, 100.0); 4] };
// The gap between pages is 10; page 2 ends at 320. A window top 4 above its end shows 4 of it: a sliver.
assert_eq!(viewed_page(None, 316.0, &layout, 100.0), 3, "4 points of page 2 is a sliver");
assert_eq!(viewed_page(None, 310.0, &layout, 100.0), 3, "as much as the gap is still a sliver");
assert_eq!(viewed_page(None, 300.0, &layout, 100.0), 2, "20 points of page 2 is the page in view");
}
/// In Columns and Two Up the pages are stored row by row: the gap to measure is the one to the page below, not to the
/// page beside.
#[test]
fn a_sliver_of_a_row_above_is_not_the_page_in_view_with_columns() {
let rects: Vec<craft::behavior::kurbo::Rect> = [(0.0, 0.0), (90.0, 0.0), (0.0, 110.0), (90.0, 110.0)]
.iter()
.map(|&(x, y)| craft::behavior::kurbo::Rect::new(x, y, x + 80.0, y + 100.0))
.collect();
let layout = craft::pages::layout::PagedLayout { rects, size: Default::default(), columns: 2, bands: vec![(0.0, 100.0); 4] };
// The first row ends at 100 and the next starts at 110: a window top at 96 shows 4 points of it, a sliver.
assert_eq!(viewed_page(None, 96.0, &layout, 100.0), 2, "4 points of the row above is a sliver");
assert_eq!(viewed_page(None, 80.0, &layout, 100.0), 0, "20 points of the first row is the page in view");
}
/// A last row that is not full has no page below the one above it: the gap is still the one to the next row.
#[test]
fn a_sliver_of_a_row_above_is_not_the_page_in_view_with_an_incomplete_last_row() {
let rects: Vec<craft::behavior::kurbo::Rect> =
[(0.0, 0.0), (90.0, 0.0), (0.0, 110.0)].iter().map(|&(x, y)| craft::behavior::kurbo::Rect::new(x, y, x + 80.0, y + 100.0)).collect();
let layout = craft::pages::layout::PagedLayout { rects, size: Default::default(), columns: 2, bands: vec![(0.0, 100.0); 3] };
assert_eq!(viewed_page(None, 96.0, &layout, 100.0), 2, "4 points of the row above is a sliver");
assert_eq!(viewed_page(None, 80.0, &layout, 100.0), 0, "20 points of the first row is the page in view");
}
/// Pages of different heights share a row and the next row starts below the tallest: the gap is measured from the row's bottom.
#[test]
fn a_shorter_page_in_a_taller_row_is_still_the_page_in_view() {
let rects: Vec<craft::behavior::kurbo::Rect> = [(0.0, 0.0, 100.0), (90.0, 0.0, 200.0), (0.0, 210.0, 100.0), (90.0, 210.0, 100.0)]
.iter()
.map(|&(x, y, h)| craft::behavior::kurbo::Rect::new(x, y, x + 80.0, y + h))
.collect();
let layout = craft::pages::layout::PagedLayout {
rects,
size: Default::default(),
columns: 2,
bands: vec![(0.0, 100.0), (0.0, 200.0), (0.0, 100.0), (0.0, 100.0)],
};
assert_eq!(viewed_page(None, 50.0, &layout, 100.0), 0, "the short page is fully visible, the row gap is 10 not 110");
assert_eq!(viewed_page(None, 196.0, &layout, 100.0), 2, "4 points of the tall page's row is a sliver");
}
/// Two Up with a cover: page 0 is a row of its own, so there is no page `columns` after it.
#[test]
fn a_sliver_of_the_cover_is_not_the_page_in_view() {
let rects: Vec<craft::behavior::kurbo::Rect> = [(90.0, 0.0), (0.0, 110.0), (90.0, 110.0), (0.0, 220.0)]
.iter()
.map(|&(x, y)| craft::behavior::kurbo::Rect::new(x, y, x + 80.0, y + 100.0))
.collect();
let layout = craft::pages::layout::PagedLayout { rects, size: Default::default(), columns: 2, bands: vec![(0.0, 100.0); 4] };
assert_eq!(viewed_page(None, 96.0, &layout, 100.0), 1, "4 points of the cover is a sliver");
assert_eq!(viewed_page(None, 80.0, &layout, 100.0), 0, "20 points of the cover is the page in view");
assert_eq!(viewed_page(None, 206.0, &layout, 100.0), 3, "4 points of the spread is a sliver");
}
/// A window in the background shows no caret and asks for no frames to blink one (#7674). The page keeps the keyboard
/// focus, so the caret blinks again once the window is active again.
#[test]
+66 -6
View File
@@ -76,16 +76,43 @@ fn new_app() -> WordApp {
WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), crate::Services::default())
}
/// A saved .docx (so AutoSave can cover it) in the harness.
fn autosave_harness() -> (egui_kittest::Harness<'static, WordApp>, std::path::PathBuf) {
let dir = std::env::temp_dir().join(format!("wordcraft-ui-autosave-label-{}", std::process::id()));
/// How [`autosave_harness`] has the saved file in its window.
#[derive(Debug, PartialEq)]
enum Reopen {
/// The window that saved it.
No,
/// Opened in a fresh window, read from disk.
FromDisk,
/// Opened in a fresh window from its bytes, which only names the file.
FromBytes,
}
/// A saved .docx (so AutoSave can cover it), or the same file opened in a fresh window as
/// `reopen` says, with the title bar drawn over it. `files` answers a later Save As pick.
fn autosave_harness(
reopen: Reopen,
files: &std::sync::Arc<craft::host::ScriptedFiles>,
) -> (egui_kittest::Harness<'static, WordApp>, std::path::PathBuf) {
let dir = std::env::temp_dir().join(format!("wordcraft-ui-autosave-label-{}-{reopen:?}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("draft.docx");
let mut a = new_app();
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), crate::Services::default())
.with_host(std::sync::Arc::new(craft::host::Host::builder(crate::APP).files(files.clone()).build()));
a.run("text.insert", json!({"text": "Hello"})).unwrap();
a.run("file.save", json!({"path": path.to_string_lossy()})).unwrap();
assert!(a.autosaves(), "a saved .docx is covered by AutoSave");
if reopen != Reopen::No {
a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), crate::Services::default())
.with_host(std::sync::Arc::new(craft::host::Host::builder(crate::APP).files(files.clone()).build()));
if reopen == Reopen::FromBytes {
let data = wordcraft_engine::cmd::insert::base64_encode(&std::fs::read(&path).unwrap());
a.execute("file.open", json!({"path": path.to_string_lossy(), "data": data})).unwrap();
} else {
a.run("file.open", json!({"path": path.to_string_lossy()})).unwrap();
}
assert!(!a.autosaves(), "an opened file waits for the user's go-ahead");
}
let h = harness(a);
(h, dir)
}
@@ -93,7 +120,8 @@ fn autosave_harness() -> (egui_kittest::Harness<'static, WordApp>, std::path::Pa
/// #3370: clicking the AutoSave switch label toggles AutoSave on and off.
#[test]
fn clicking_the_autosave_label_toggles_autosave() {
let (mut h, dir) = autosave_harness();
let files = std::sync::Arc::new(craft::host::ScriptedFiles::new());
let (mut h, dir) = autosave_harness(Reopen::No, &files);
assert!(h.state().autosaves());
h.get_by_label("AutoSave").click();
crate::test_harness::frames(&mut h, 2);
@@ -104,6 +132,35 @@ fn clicking_the_autosave_label_toggles_autosave() {
let _ = std::fs::remove_dir_all(&dir);
}
/// #3307: a file opened, not saved, in this window had the switch greyed out, and clicking it
/// asked for Save As. Clicking it now turns AutoSave on for that file.
#[test]
fn clicking_autosave_on_an_opened_file_turns_it_on() {
let files = std::sync::Arc::new(craft::host::ScriptedFiles::new());
let (mut h, dir) = autosave_harness(Reopen::FromDisk, &files);
h.get_by_label("AutoSave").click();
crate::test_harness::frames(&mut h, 2);
assert!(h.state().autosaves(), "the switch turned AutoSave on");
assert!(h.state().dialog_host.is_empty() && h.state().file_dialog.is_none(), "without Save As");
let _ = std::fs::remove_dir_all(&dir);
}
/// A document opened from bytes only names its file, so the switch can't hand that file to
/// AutoSave: it shows the block and clicking it asks for Save As, after which AutoSave is on.
#[test]
fn clicking_autosave_on_a_document_opened_from_bytes_asks_for_save_as() {
let files = std::sync::Arc::new(craft::host::ScriptedFiles::new());
let (mut h, dir) = autosave_harness(Reopen::FromBytes, &files);
assert_eq!(h.state().autosave_switch_block(), Some(crate::AutoSaveBlock::NotSavedHere));
let copy = dir.join("copy.docx");
files.queue(craft::host::Picked::Paths(vec![copy.clone()]));
h.get_by_label("AutoSave").click();
crate::test_harness::frames(&mut h, 2);
assert!(copy.is_file(), "Save As saved a copy");
assert!(h.state().autosaves(), "AutoSave covers the copy");
let _ = std::fs::remove_dir_all(&dir);
}
/// #701: the arrow beside Undo lists the session's undo steps, newest first; clicking the third
/// row undoes three steps at once.
#[test]
@@ -744,8 +801,11 @@ fn the_autosave_knob_sits_right_when_on_and_mirrors_right_to_left() {
a.ui.language = "en".into();
// Mark the document as saved here without touching disk (`session.dirty` stays false).
let path = std::path::PathBuf::from("draft.docx");
// A save to the document's own file records both (`note_file_on_disk`): the file is read
// from disk, so the switch can be turned on again after it has been turned off.
a.session.path = Some(path.clone());
a.autosave_path = Some(path);
a.autosave_path = Some(path.clone());
a.read_from = Some(path);
let mut h = harness(a);
// Arabic UI labels draw even when built without `CRAFT_FONTS_DIR` (embedded Arabic faces).
+2 -1
View File
@@ -104,7 +104,8 @@ fn leading(app: &mut WordApp, ui: &mut Ui) -> Option<egui::Rect> {
/// The AutoSave switch: off and with the reason as its tooltip when AutoSave can't cover the document (#196,
/// #176); a click then offers Save As where that helps. Returns the rect it took.
fn autosave(app: &mut WordApp, ui: &mut Ui) -> egui::Rect {
let block = app.autosave_block();
// A file read from disk here is off, not blocked: the switch turns it on (#3307).
let block = app.autosave_switch_block();
let on = app.autosaves() && block.is_none();
let tip = block.as_ref().map_or_else(|| tl!("AutoSave saves every change to the file (needs a saved document)").to_string(), |b| b.reason());
// The small switch, as the old title bar drew it.
+6 -3
View File
@@ -2364,9 +2364,12 @@ fn modal_dialog_with_open_popup_does_not_shake_on_inside_click_but_shakes_on_out
#[test]
fn bare_fields_and_groups_draw_their_captions() {
use egui::accesskit::Role;
for (dialog, captions) in
[("envelopes", &["Delivery address", "Return address", "Envelope size"][..]), ("dropCap", &["Position", "Lines to drop"][..])]
{
for (dialog, captions) in [
("envelopes", &["Delivery address", "Return address", "Envelope size"][..]),
("dropCap", &["Position", "Lines to drop"][..]),
("mergeRecords", &["To:"][..]),
("printRecords", &["To:"][..]),
] {
let mut h = app_harness(app_with("Lanterns"));
h.state_mut().run("ui.dialog", json!({"name": dialog})).unwrap();
h.run_steps(6);
+8 -1
View File
@@ -20,6 +20,8 @@ use crate::{WordApp, panes};
pub(crate) struct Parked {
/// [`WordApp`]'s `autosave_path`: the file AutoSave writes this document to.
autosave_path: Option<std::path::PathBuf>,
/// [`WordApp`]'s `read_from`: the file on disk this document was read from or saved to.
read_from: Option<std::path::PathBuf>,
/// The comment panel's selection and the comment and reply text typed in this document and not
/// yet written to it.
comments: craft::review::ui::CommentsPanelState,
@@ -102,7 +104,11 @@ impl WordApp {
if from == to {
return false;
}
let leaving = Parked { autosave_path: self.autosave_path.take(), comments: std::mem::take(&mut self.canvas.comments) };
let leaving = Parked {
autosave_path: self.autosave_path.take(),
read_from: self.read_from.take(),
comments: std::mem::take(&mut self.canvas.comments),
};
if self.session.is_open(from) {
self.parked.insert(from, leaving);
}
@@ -110,6 +116,7 @@ impl WordApp {
let seen = back.is_some();
let back = back.unwrap_or_default();
self.autosave_path = back.autosave_path;
self.read_from = back.read_from;
self.canvas.comments = back.comments;
let session = &self.session;
self.parked.retain(|d, _| session.is_open(*d));
+86
View File
@@ -636,4 +636,90 @@ mod tests {
});
assert!(!shapes.is_empty(), "{KEY} icon must paint");
}
/// #7450: the Dictate microphone icon parses cleanly on a `0 0 20 20` viewBox, keeps a
/// rounded capsule (`rx >= width / 2`) clear of the U-stand cradle, and renders at 16–22 pt.
#[test]
fn dictate_icon_geometry_and_rendering() {
use craft::theme::{Contrast, Mode};
use craft::ui::testing::{Frames, style};
let (_, bytes) = WORDCRAFT_ICONS.icons.iter().find(|(name, _)| *name == "dictate").expect("dictate is registered");
let svg = std::str::from_utf8(bytes).expect("an SVG document is text");
let tree = craft::ui::primitives::svg_tree::parse(bytes).expect("dictate.svg must parse as a valid SVG document");
let size = tree.size();
assert_eq!(size.width(), 20.0, "icon viewBox width must be 20");
assert_eq!(size.height(), 20.0, "icon viewBox height must be 20");
fn attr_str<'a>(tag: &'a str, name: &str) -> &'a str {
let elem = tag.split('>').next().unwrap_or(tag);
let needle = format!("{name}=\"");
let start = elem
.match_indices(&needle)
.find(|&(idx, _)| idx == 0 || elem.as_bytes()[idx - 1].is_ascii_whitespace())
.map(|(idx, _)| idx + needle.len())
.unwrap_or_else(|| panic!("missing {name} on {elem}"));
&elem[start..elem[start..].find('"').map_or(elem.len(), |i| start + i)]
}
let attr = |tag: &str, name: &str| -> f32 {
let val = attr_str(tag, name);
val.parse::<f32>().unwrap_or_else(|_| panic!("non-numeric {name}: {val}"))
};
let root = svg.split("<svg").nth(1).expect("dictate.svg must contain a root <svg> element");
assert_eq!(attr_str(root, "viewBox"), "0 0 20 20", "root SVG viewBox must be 0 0 20 20");
let rect = svg.split("<rect").nth(1).expect("dictate.svg must contain a <rect> capsule");
let cap_x = attr(rect, "x");
let cap_y = attr(rect, "y");
let width = attr(rect, "width");
let height = attr(rect, "height");
let rx = attr(rect, "rx");
let cap_stroke = attr(rect, "stroke-width");
let cradle = svg.split("<path").nth(1).expect("dictate.svg must contain a cradle <path>");
let cradle_stroke = attr(cradle, "stroke-width");
let half_strokes = (cap_stroke + cradle_stroke) / 2.0;
assert!(rx >= width / 2.0, "capsule corner radius ({rx}) must be at least half the width ({width})");
assert!(cap_y + height < 15.0, "capsule bottom ({}) must stay clear of the cradle bottom (15.0)", cap_y + height);
assert!(cap_x > 5.0 && cap_x + width < 15.0, "capsule x-span ({}..{}) must stay inside the cradle arms (5..15)", cap_x, cap_x + width);
fn dist_point_to_seg(p: (f32, f32), a: (f32, f32), b: (f32, f32)) -> f32 {
let (vx, vy) = (b.0 - a.0, b.1 - a.1);
let len_sq = vx * vx + vy * vy;
let t = if len_sq > 0.0 { (((p.0 - a.0) * vx + (p.1 - a.1) * vy) / len_sq).clamp(0.0, 1.0) } else { 0.0 };
let (dx, dy) = (p.0 - (a.0 + t * vx), p.1 - (a.1 + t * vy));
(dx * dx + dy * dy).sqrt()
}
let cradle_segs = [((5.0_f32, 9.5_f32), (5.0, 11.0)), ((5.0, 11.0), (10.0, 15.0)), ((10.0, 15.0), (15.0, 11.0)), ((15.0, 11.0), (15.0, 9.5))];
let mut cap_points = vec![(cap_x, 9.5_f32), (cap_x + width, 9.5_f32), (cap_x + width / 2.0, cap_y + height)];
let (arc_cx, arc_cy, arc_r) = (cap_x + width / 2.0, cap_y + height - rx, rx);
for step in 0..=8 {
let angle = std::f32::consts::PI * (step as f32) / 8.0;
cap_points.push((arc_cx - arc_r * angle.cos(), arc_cy + arc_r * angle.sin()));
}
let min_clearance =
cap_points.iter().flat_map(|&p| cradle_segs.iter().map(move |&(a, b)| dist_point_to_seg(p, a, b))).fold(f32::INFINITY, f32::min);
assert!(min_clearance > half_strokes, "capsule outline clearance ({min_clearance:.2}) must exceed combined half-strokes ({half_strokes:.2})");
register();
let tokens = style::tokens(Mode::Light, Contrast::Standard);
let mut frames = Frames::new();
for pt in [16.0_f32, 19.0, 20.0, 22.0] {
let target = Rect::from_min_size(Pos2::ZERO, egui::vec2(pt, pt));
let icon = IconSpec::svg(IconId::new("dictate"));
let (shapes, _) = style::paint_frame(&mut frames, &tokens, craft::i18n::Direction::Ltr, craft::ui::style::Ink::OnPanel, |draw| {
draw.icon(target, &icon)
});
assert!(!shapes.is_empty(), "dictate icon must paint at {pt} pt");
let bounds = shapes.iter().map(|s| s.visual_bounding_rect()).fold(Rect::NOTHING, |acc, r| acc.union(r));
assert!(bounds.is_positive(), "dictate icon must have positive rendered bounds at {pt} pt, got {bounds:?}");
assert!(target.expand(1.0).contains_rect(bounds), "dictate icon at {pt} pt overflowed target {target:?}: {bounds:?}");
assert!(
bounds.width() >= pt * 0.5 && bounds.height() >= pt * 0.5 && bounds.width() <= 22.5 && bounds.height() <= 22.5,
"dictate icon rendered size at {pt} pt out of 16-22 pt bounds: {bounds:?}"
);
}
}
}
+3
View File
@@ -509,6 +509,9 @@ pub struct WordApp {
/// there. A file that was merely opened isn't rewritten until the user saves it: saving drops
/// whatever WordCraft can't represent (content controls, charts, macros…).
autosave_path: Option<std::path::PathBuf>,
/// The file on disk the document was read from or saved to. A document opened from bytes
/// (`file.open` with `data`) only names a file, so the AutoSave switch can't cover it.
read_from: Option<std::path::PathBuf>,
/// Web: saves the browser's picker hasn't finished yet (#1315).
saves_in_flight: Vec<SaveInFlight>,
/// The Save Changes prompt this window is running and the command it holds back.
+38
View File
@@ -1150,6 +1150,44 @@ fn unimplemented_stub_ribbon_buttons_are_disabled() {
.find(|n| n.accesskit_node().label().is_some_and(|l| l.split_whitespace().collect::<Vec<_>>().join(" ") == expected_label))
.unwrap_or_else(|| panic!("{tab}: ribbon button '{expected_label}' should exist"));
assert!(button.accesskit_node().is_disabled(), "{tab}: stub button {:?} ({id}) must be disabled", button.accesskit_node().label());
if expected_label == "Dictate" {
fn push_icon_rects(shape: &egui::Shape, clip: egui::Rect, btn_rect: egui::Rect, out: &mut Vec<egui::Rect>) {
match shape {
egui::Shape::Vec(items) => {
for item in items {
push_icon_rects(item, clip, btn_rect, out);
}
}
egui::Shape::Text(_) | egui::Shape::Noop => {}
other => {
let r = other.visual_bounding_rect().intersect(clip);
if r.is_positive()
&& btn_rect.expand(1.0).contains_rect(r)
&& r.width() < btn_rect.width() * 0.9
&& r.height() < btn_rect.height() * 0.9
{
out.push(r);
}
}
}
}
let btn_rect = button.rect();
let mut icon_rects = Vec::new();
for c in &h.output().shapes {
push_icon_rects(&c.shape, c.clip_rect, btn_rect, &mut icon_rects);
}
let icon_rect = icon_rects
.into_iter()
.reduce(|a, b| a.union(b))
.unwrap_or_else(|| panic!("Dictate button ({btn_rect:?}) must paint a bounded icon shape"));
assert!(
icon_rect.width() >= 16.0 && icon_rect.height() >= 16.0,
"Dictate ribbon icon must render at >= 16 pt, got {}x{} ({icon_rect:?})",
icon_rect.width(),
icon_rect.height()
);
assert!((icon_rect.width() - icon_rect.height()).abs() <= 2.0, "Dictate icon should be square: {icon_rect:?}");
}
}
}
+1 -1
View File
@@ -20,7 +20,7 @@ pub enum AutoSaveBlock {
Unsaved,
/// A file in a format that can't keep everything (Markdown, plain text, HTML…), by file name.
Format { name: String },
/// A file that was opened but not yet saved in this session.
/// A file that was opened but not yet saved in this session; the switch shows off and lifts it.
NotSavedHere,
}
+93
View File
@@ -3247,6 +3247,99 @@ fn autosave_is_unavailable_in_the_browser() {
assert!(err.contains("browser"), "{err}");
}
/// #3307: an opened file isn't rewritten until the user says so, but the switch says so
/// without Save As: turning it on lets AutoSave write the file.
#[test]
fn turning_autosave_on_covers_a_file_only_opened_here() {
let dir = scratch("autosave-opened");
let path = dir.join("report.docx");
let mut a = typed();
a.run("file.save", json!({"path": path.to_string_lossy()})).unwrap();
let mut b = app();
b.run("file.open", json!({"path": path.to_string_lossy()})).unwrap();
assert_eq!(b.autosave_block(), Some(AutoSaveBlock::NotSavedHere));
assert_eq!(b.autosave_switch_block(), None, "the switch lifts it itself");
b.run("text.insert", json!({"text": "Opened "})).unwrap();
b.autosave_tick(monotonic_ms() + 10_000.0);
assert!(b.session.dirty, "opening alone never rewrites the file");
assert!(b.run("file.autosave", json!({"value": "false"})).is_err());
assert!(!b.autosaves(), "a value that isn't a bool grants nothing");
assert_eq!(b.run("file.autosave", json!({})).unwrap(), json!({"value": true}));
assert!(b.autosaves());
b.autosave_tick(monotonic_ms() + 20_000.0);
assert!(!b.session.dirty, "AutoSave wrote the opened file");
assert!(b.run("file.autosave", json!({"value": false})).is_ok());
assert!(!b.autosaves());
let _ = std::fs::remove_dir_all(&dir);
}
/// `file.open` with `data` only names the file: the switch mustn't let AutoSave write a file of
/// that name, which may hold something else entirely.
#[test]
fn the_autosave_switch_refuses_a_document_opened_from_bytes() {
let dir = scratch("autosave-bytes");
let path = dir.join("other.docx");
let mut a = typed();
a.run("file.save", json!({"path": path.to_string_lossy()})).unwrap();
let on_disk = std::fs::read(&path).unwrap();
let files = Arc::new(ScriptedFiles::new());
let mut b = app_with_files(files.clone());
let data = wordcraft_engine::cmd::insert::base64_encode(&on_disk);
b.execute("file.open", json!({"path": path.to_string_lossy(), "data": data})).unwrap();
assert_eq!(b.autosave_block(), Some(AutoSaveBlock::NotSavedHere));
assert_eq!(b.autosave_switch_block(), Some(AutoSaveBlock::NotSavedHere), "the switch shows the block");
assert!(b.run("file.autosave", json!({"value": true})).is_err());
b.status = None;
let err = b.run("file.autosave", json!({})).unwrap_err();
assert_eq!(status_text(&b), Some(err.as_str()), "the status bar says why");
b.run("text.insert", json!({"text": "Bytes "})).unwrap();
b.autosave_tick(monotonic_ms() + 10_000.0);
assert!(b.session.dirty);
assert_eq!(std::fs::read(&path).unwrap(), on_disk, "the named file is untouched");
// Open without a path only asks for the picker: it isn't a read of the shown file.
script_pick(&files, None);
b.run("file.open", json!({"path": null})).unwrap();
assert!(b.run("file.autosave", json!({"value": true})).is_err(), "the picker request grants nothing");
// A `data` that isn't a string is ignored and the file is read from disk.
let mut c = app();
c.run("file.open", json!({"path": path.to_string_lossy(), "data": null})).unwrap();
assert!(c.run("file.autosave", json!({"value": true})).is_ok(), "read from disk");
// Saving is still the way: then AutoSave covers the file.
b.run("file.save", json!({})).unwrap();
assert!(b.autosaves());
let _ = std::fs::remove_dir_all(&dir);
}
/// AutoSave turned off in one document stays off there when another document turns it on: the
/// preference is shared, but each document's go-ahead is its own.
#[test]
fn autosave_turned_off_stays_off_when_another_document_turns_it_on() {
let dir = scratch("autosave-two");
let (first_path, second_path) = (dir.join("first.docx"), dir.join("second.docx"));
let mut c = typed();
c.run("file.save", json!({"path": second_path.to_string_lossy()})).unwrap();
let mut a = typed();
a.run("file.save", json!({"path": first_path.to_string_lossy()})).unwrap();
let first = a.session.document_id();
let saved = std::fs::read(&first_path).unwrap();
assert!(a.autosaves());
a.run("file.autosave", json!({"value": false})).unwrap();
a.run("file.open", json!({"path": second_path.to_string_lossy()})).unwrap();
assert_ne!(a.session.document_id(), first, "the second file opens beside the first");
a.run("file.autosave", json!({"value": true})).unwrap();
assert!(a.autosaves());
a.show_document(first).unwrap();
assert!(!a.autosaves(), "the first document's switch is still off");
a.run("text.insert", json!({"text": "Later "})).unwrap();
a.autosave_tick(monotonic_ms() + 10_000.0);
assert!(a.session.dirty);
assert_eq!(std::fs::read(&first_path).unwrap(), saved, "the first file is untouched");
// Turned back on, it covers the file it was saved to without another save.
a.run("file.autosave", json!({"value": true})).unwrap();
assert!(a.autosaves());
let _ = std::fs::remove_dir_all(&dir);
}
/// Cancelling the Open picker (Mod+O) left the document as it was but turned AutoSave off.
#[test]
fn cancelling_open_keeps_autosave() {
+1
View File
@@ -186,6 +186,7 @@ impl WordApp {
clipboard_published: _,
// Per document: the shown document's, swapped with `parked` on a document switch.
autosave_path: _,
read_from: _,
parked: _,
// Per window.
ui,
+89
View File
@@ -500,3 +500,92 @@ checker verifies the pairing (CT-MISMATCH, Error, observed — this row).
The corpus was regenerated; MANIFEST.md carries the fixed hashes.
The remaining nine stress files have not yet been shown to this consumer.
## Corpus probes — DrawingML geometry coordinate typing (#8231)
A real-world corpus document (`d60c276dc845`) containing a `wps` custom-geometry
shape (`a:custGeom`) inside `mc:AlternateContent` whose four `a:arcTo` elements
carried decimal `wR`/`hR` values was refused by Word for Windows (census) and
fell into the open-failure class on Word for Mac. Rounding only those eight
values to integers caused the full original document to open cleanly.
Follow-up probes derived from `d60c276dc845` (whose only decimals are the eight
`a:arcTo` radii) were measured in fresh instances of **Word for Mac 16.114.4
(2026-12-02)** (modal open-error alert / 0 documents opened on refusal):
| Form | Example | Word for Mac 16.114.4 |
|---|---|---|
| Plain decimal fraction | `407.666666666667` | REFUSES (original finding) |
| Integer | `407` | OPENS |
| Sign-prefixed fraction | `-407.666666666667` | REFUSES |
| Space-padded fraction | `" 407.666666666667 "` | REFUSES |
| Zero fraction | `407.0` | REFUSES |
| Strict-namespace `arcTo` (`http://purl.oclc.org/ooxml/drawingml/main`) in a Transitional package | — | REFUSES |
Context probes derived from `d60c276dc845` (one variable per probe; controls: original refuses, integer opens) were measured in **Word for Mac 16.114.4**:
| Context | Fractional radii in `custGeom` |
|---|---|
| Selected `mc:Choice` (first Supported, `Requires="wps"`; corpus document context) | REFUSES |
| Selected `mc:Choice` with no `Requires` attribute (`r1`) | REFUSES |
| Second, unselected `mc:Choice` (after Supported `mc:Choice`) | OPENS |
| `mc:Fallback` while a Supported `mc:Choice` precedes it | OPENS |
| `mc:Fallback` behind a foreign-namespace `mc:Choice` (`q1b`) | CONFOUNDED (Word refuses the MCE construction; geometry attribution unmeasurable) |
| Strict package (`http://purl.oclc.org/ooxml/...` namespaces, `conformance="strict"`) | OPENS |
| Outside any `mc:AlternateContent` (bare `w:drawing`, Transitional; `r2`) | REFUSES |
`DML-COORDINATE` is graded `Error` with `Observed` evidence only when ALL three
conditions hold:
1. **Transitional part profile**: the part's root element namespace resolves to
a non-Strict URI (not under `http://purl.oclc.org/ooxml/`). Strict parts and
parts whose root namespace cannot be resolved by the scanner (for example,
entity-obscured `xmlns`, undeclared prefix, or no namespace binding) never
emit `Error`.
2. **Supported-selected branch**: outside every `mc:AlternateContent`, or inside
the Supported-selected branch of every enclosing `mc:AlternateContent`. Each
`mc:Choice` evaluates to one of three states:
- **Supported**: `Requires` is absent (measured `r1`), or every
whitespace-delimited prefix resolves by exact URI equality to the closed
allowlist of Word MCE capability URIs (`w`, anchored on `wps`, plus Word's
shipped 2010/2012 WordprocessingML and DrawingML capability URIs).
- **Unresolved**: any `Requires` prefix resolves to an unlisted URI, fails to
resolve (undeclared, malformed, or entity-obscured), or `Requires` is empty
or entity-obscured. An Unresolved `Choice` makes the whole enclosing
`mc:AlternateContent`'s selection uncertain; no branch in it (that Choice,
later Choices, or `mc:Fallback`) may be treated as selected.
- **Unsupported**: reserved for capabilities a Word measurement proves Word
rejects without confounding MCE rejection; currently unpopulated (no
capability is populated by inference).
`mc:Fallback` is treated as selected only when `mc:AlternateContent` contains
no `Choice` at all; a `mc:Fallback` behind any `Choice` (`Supported`,
`Unresolved`, or `Unsupported`) is never treated as selected.
3. **Measured fractional geometry**: raw (undecoded, unnormalized) XML attribute
values matching `[ ]*-?[0-9]+\.[0-9]+[ ]*` with an `i64`-representable signed
whole part in `wR`/`hR` on `a:arcTo` in either the Transitional
(`http://schemas.openxmlformats.org/drawingml/2006/main`) or Strict
(`http://purl.oclc.org/ooxml/drawingml/main`) DrawingML namespace.
Every other invalid geometry finding is graded `Warning` and does not fail a
package. **Warning grade precedence** for measured fractional radii:
1. **Strict parts and definitively unselected enclosing `mc:AlternateContent`
branches** (for example, a second `mc:Choice` or `mc:Fallback` after a
Supported `mc:Choice`) report `Warning` with `Observed` evidence (Word
toleration is measured).
2. **Unresolved part profiles and unresolved `AlternateContent` selections**
report `Warning` with `MsDocumented` evidence only in a non-Strict part with
no definitively unselected enclosing branch.
Unmeasured schema-typed sibling attributes
(`ST_AdjCoordinate`, `ST_AdjAngle`, `ST_PositiveCoordinate`) and all unmeasured
invalid numeric lexical classes (`+`-prefixed fractions, non-space whitespace
padding such as `\t`/`\r`/`\n`, character-reference or entity-encoded
spellings, empty or whitespace-only values, lone signs, lone dots,
leading/trailing dots, scientific/exponent notation, integers outside their
schema type's bounds (`ST_PositiveCoordinate`: `0..=27273042316900`,
`ST_CoordinateUnqualified`: `-27273042329600..=27273042316900`, `ST_Angle`:
`-2147483648..=2147483647`), out-of-`i64`-range whole parts, and non-integer
path dimensions) are graded `Warning`
with `MsDocumented` evidence and do not fail a package. In-range integers, guide names,
and unit-qualified coordinate measures are preserved.
+12 -3
View File
@@ -48,6 +48,8 @@ Recorded reader pairs (exact shapes in the policy):
| Helper | Rules/conclusion | Collections/accessors | Intentional scope | Incompleteness causes | Fallback | Unknown package identity |
|---|---|---|---|---|---|---|
| lib.rs::ran | - | field.checks*1 | report accumulator and emission budgets; no input definition collection | per-rule findings, total findings, or coverage-note budget | preserve emitted evidence and record truncation/Incomplete; never supplies definition absence | independent |
| lib.rs::ran_dml_coordinate | DML-COORDINATE | - | report applicability for custom geometry | custom geometry may be absent from the scanned XML prefix | record the rule once when the scanner reaches custom geometry | independent |
| lib.rs::add_dml_coordinate_error | DML-COORDINATE | - | document-wide measured DML-COORDINATE error count and capped emission | per-rule finding cap | count every measured error across all XML parts and emit at most cap + 1 times so truncation is noted once | independent |
| lib.rs::allow | - | field.coverage*2,field.incomplete*1,field.rule_counts*1 | report accumulator and emission budgets; no input definition collection | per-rule findings, total findings, or coverage-note budget | preserve emitted evidence and record truncation/Incomplete; never supplies definition absence | independent |
| lib.rs::add | - | field.findings*1 | report accumulator and emission budgets; no input definition collection | per-rule findings, total findings, or coverage-note budget | preserve emitted evidence and record truncation/Incomplete; never supplies definition absence | independent |
| lib.rs::add_graded | - | field.findings*1 | report accumulator and emission budgets; no input definition collection | per-rule findings, total findings, or coverage-note budget | preserve emitted evidence and record truncation/Incomplete; never supplies definition absence | independent |
@@ -74,7 +76,9 @@ Recorded reader pairs (exact shapes in the policy):
| lib.rs::listing_complete | - | access.is_complete*2,field.listings*2,field.parts*1,field.special_notes*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| lib.rs::category_complete | - | access.is_complete*1,field.parts*1,type.Observed*1,type.Vec*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| lib.rs::xml_source_complete | - | field.parts*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| lib.rs::check_xml | HEADERSOURCE-PRESENT,MATH-PLACEMENT,PROTECTION-PASSWORD,STRUCT-END-P,XML-INVALID-CHAR,XML-MALFORMED,XML-UNDECLARED-PREFIX | access.prefix*1,access.retain_budget*1,field.comment_para_ids*1,field.content_part_exemptions*2,field.content_parts*2,field.entries*1,field.ink_content_parts*2,field.note_listings*1,field.refs*5,field.special_notes*1,field.unknown_prefixes*1,type.BTreeMap*1,type.HashMap*2,type.HashSet*2,type.Vec*13 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| lib.rs::check_xml | DML-COORDINATE,HEADERSOURCE-PRESENT,MATH-PLACEMENT,PROTECTION-PASSWORD,STRUCT-END-P,XML-INVALID-CHAR,XML-MALFORMED,XML-UNDECLARED-PREFIX | access.prefix*1,access.retain_budget*1,field.comment_para_ids*1,field.content_part_exemptions*2,field.content_parts*2,field.dml_coordinate_warnings*1,field.entries*1,field.ink_content_parts*2,field.note_listings*1,field.refs*5,field.special_notes*1,field.unknown_prefixes*1,type.BTreeMap*1,type.HashMap*2,type.HashSet*2,type.Vec*15 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| lib.rs::append_dml_coordinate_warnings | - | type.Vec*2 | bounded deferred DML-COORDINATE warnings across XML parts | per-rule finding cap | retain up to one warning past the cap to exercise truncation after measured errors | independent |
| lib.rs::flush_dml_coordinate_warnings | DML-COORDINATE | type.Observed*1,type.Vec*1 | deferred DML-COORDINATE warnings emitted after all XML parts | per-rule finding cap | emit measured errors ahead of warnings and trigger truncation at most once | independent |
| lib.rs::store_relationship_observations | - | access.invalidate*2,access.project*3,field.content*3,field.exemptions*3,field.references*2,type.BTreeMap*1,type.HashSet*1,type.Vec*6 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| lib.rs::store_note_observations | - | access.invalidate*3,access.push_bounded*3,field.listings*4,field.special_notes*2,type.BTreeMap*1,type.HashMap*1,type.Vec*3 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| lib.rs::append_note_items | - | type.Vec*6 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
@@ -193,7 +197,7 @@ Recorded reader pairs (exact shapes in the policy):
| scan.rs::close | - | field.frames*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| scan.rs::declared_encoding | - | field.bytes*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| scan.rs::decode_utf16_strict | - | type.Vec*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| scan.rs::scan_part | STRUCT-TC-NO-P | access.into_complete_set*2,access.invalidate*2,field.alt_stack*2,field.content_part_exemptions*2,field.content_parts*2,field.declared*8,field.frames*10,field.note_listings*1,field.note_listings_e*1,field.note_listings_f*1,field.para_ids*1,field.special_notes*2,field.unknown_prefixes*2,parser.parse_doctype_entities*1,type.BTreeMap*1,type.HashMap*1,type.HashSet*1,type.Observed*1,type.Vec*9 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| scan.rs::scan_part | STRUCT-TC-NO-P | access.into_complete_set*2,access.invalidate*2,field.alt_stack*2,field.content_part_exemptions*2,field.content_parts*2,field.declared*8,field.frames*10,field.note_listings*1,field.note_listings_e*1,field.note_listings_f*1,field.para_ids*1,field.special_notes*2,field.unknown_prefixes*2,parser.parse_doctype_entities*1,type.BTreeMap*1,type.HashMap*1,type.HashSet*1,type.Observed*1,type.Vec*10 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| scan.rs::own_declarations | - | type.Vec*2 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| scan.rs::open_attributes | - | type.Vec*2 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| scan.rs::enter_alt | - | field.alt_stack*1,field.frames*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
@@ -206,9 +210,14 @@ Recorded reader pairs (exact shapes in the policy):
| scan.rs::check_protection | PROTECTION-PASSWORD | type.Vec*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| scan.rs::record_note_pr | - | field.frames*2,field.note_listings_e*1,field.note_listings_f*1,field.special_notes*2 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| scan.rs::check_header_source | HEADERSOURCE-PRESENT | field.frames*2,field.withheld*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| scan.rs::in_custom_geometry | - | field.frames*1 | custom geometry ancestry of the current XML event | XML event/depth budget | use ancestry of events already scanned | independent |
| scan.rs::prefix_requires_state | - | type.Vec*1 | namespace scope for one mc:Choice Requires prefix | XML event/depth budget; entity-obscured xmlns declaration | treat unlisted, undeclared, malformed, or entity-obscured prefix bindings as unresolved rather than supported or unsupported | independent |
| scan.rs::choice_requires_state | - | type.Vec*1 | mc:Choice Requires attribute evaluation in current namespace scope | XML event/depth budget; entity-obscured Requires or xmlns declaration | withhold Error by returning Unresolved when Requires or any prefix binding is unlisted, empty, undeclared, or unreadable | independent |
| scan.rs::dml_branch_selection | - | field.alt_stack*1 | enclosing mc:AlternateContent branch selection for the current XML event | XML event/depth budget | evaluate enclosing AlternateContent frames already scanned | independent |
| scan.rs::check_dml_coordinates | DML-COORDINATE | field.dml_coordinate_warnings*2,field.frames*1 | source-local custom geometry attribute values | source unavailable or malformed; XML event/depth budget | measured decimal-fraction spellings ([ ]*-?[0-9]+\\.[0-9]+[ ]* raw XML source) in a:arcTo wR/hR (Transitional or Strict DrawingML namespace) receive Error with Observed evidence only when the part profile is Transitional and every enclosing AlternateContent is Supported-selected (bare drawing, Supported Choice, or choice-less Fallback); Warning grade precedence: Strict parts and definitively unselected enclosing AlternateContent branches report Warning with Observed evidence, while unresolved part profiles and unresolved AlternateContent selections report Warning with MsDocumented evidence only in a non-Strict part with no definitively unselected enclosing branch; other invalid schema-typed custom geometry attributes and unmeasured or unresolvable lexical classes receive Warning with MsDocumented evidence; measured Errors are emitted ahead of Warnings; report invalid values in the scanned prefix | independent |
| scan.rs::record | - | field.reps*3 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| scan.rs::check_para_ids | PARAID-VALUE | field.alt_stack*1,field.para_ids*3 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| scan.rs::assign_alt_branch | - | field.alt_stack*1,field.frames*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| scan.rs::assign_alt_branch | - | field.alt_stack*1,field.declared*1,field.frames*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| scan.rs::restore_branch | - | field.alt_stack*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| scan.rs::on_empty | STRUCT-TC-NO-P | - | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| scan.rs::record_ids | - | field.docpr*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
+340 -2
View File
@@ -434,6 +434,48 @@ pub(crate) const PROTECTION_PASSWORD: RuleSpec =
/// Batch b6 (Word for the web, 2026-11-07): corruption banner, view-only
/// — observed.
pub(crate) const HEADERSOURCE_PRESENT: RuleSpec = RuleSpec { id: "HEADERSOURCE-PRESENT", severity: Severity::Error, evidence: Evidence::Observed };
/// `DML-COORDINATE`: an invalid numeric literal in an integer-typed DrawingML
/// custom geometry coordinate or angle attribute (`ST_PositiveCoordinate`,
/// `ST_AdjCoordinate`, `ST_AdjAngle`).
/// Observed (#8231): Word for Windows (census) and Word for Mac 16.114.4
/// (2026-12-02, fresh instances) on probes derived from `d60c276dc845`
/// refused decimal-fraction `wR`/`hR` values on `a:arcTo` across all five
/// refusal forms — plain (`407.666666666667`), minus-sign-prefixed
/// (`-407.666666666667`), ASCII-space-padded (`" 407.666666666667 "`),
/// zero-fraction (`407.0`), and Strict-namespace `arcTo`
/// (`http://purl.oclc.org/ooxml/drawingml/main`) in a Transitional package —
/// while opening the integer twin (`407`) cleanly.
/// Follow-up context probes (Word for Mac 16.114.4) narrowed refusal further:
/// Word refuses fractional radii in the selected `mc:Choice` (first Supported
/// Choice, including a Choice with no `Requires` attribute — probe `r1`) or
/// outside any `mc:AlternateContent` (bare `w:drawing` — probe `r2`), while
/// opening fractional radii in an unselected second `mc:Choice`, in
/// `mc:Fallback` when a Supported Choice precedes it, or in a Strict part
/// (`http://purl.oclc.org/ooxml/...` root namespace). The foreign-namespace
/// `mc:Fallback` probe is confounded (Word refuses that file for its MCE
/// construction rather than measurably for the geometry), so `mc:Fallback` is
/// treated as selected only when `mc:AlternateContent` contains no `Choice` at
/// all.
/// Error requires ALL of: Transitional part profile (root namespace resolved to
/// a non-Strict URI) + Supported-selected branch at every enclosing level (bare
/// drawing, Supported `mc:Choice`, or choice-less `mc:Fallback`, with `Requires`
/// evaluated against a closed exact-URI allowlist of Word MCE capabilities
/// including `w` and `wps`) + measured fractional geometry (raw XML attribute
/// values matching `[ ]*-?[0-9]+\.[0-9]+[ ]*` with an `i64`-representable whole
/// part in `a:arcTo` `wR`/`hR` in Transitional or Strict DrawingML namespace).
/// Every other invalid geometry finding is graded Warning via
/// [`Acc::add_graded`]. Warning grade precedence for measured fractional radii:
/// Strict parts and definitively unselected enclosing `mc:AlternateContent`
/// branches report `Warning` / `Observed`; unresolved part profiles and
/// unresolved `AlternateContent` selections (including any `Choice` with an
/// unlisted, undeclared, empty, or entity-obscured `Requires`, or a `Fallback`
/// behind any `Choice`) report `Warning` / `MsDocumented` only in a non-Strict
/// part with no definitively unselected enclosing branch. Unmeasured sibling
/// attributes and unmeasured invalid lexical classes (`+`-prefixed fractions,
/// non-space padding, entity/character-reference encodings, exponent forms,
/// leading/trailing dots, empty/whitespace-only, out-of-schema-range integers,
/// or out-of-`i64`-range whole parts) emit `Warning` / `MsDocumented`.
pub(crate) const DML_COORDINATE: RuleSpec = RuleSpec { id: "DML-COORDINATE", severity: Severity::Error, evidence: Evidence::Observed };
/// `CONTENTPART-TYPE`: a `w:contentPart` element whose relationship target's
/// effective content type is not `text/xml`. MS-OI29500 Part 1 §17.3.3.2
/// note (a): "Word will fail to load the document if the content part's
@@ -522,6 +564,7 @@ pub(crate) const RULES: &[RuleSpec] = &[
NOTE_PR_DANGLING,
PROTECTION_PASSWORD,
HEADERSOURCE_PRESENT,
DML_COORDINATE,
CONTENTPART_TYPE,
REL_DUP_ID,
REL_DANGLING,
@@ -569,6 +612,9 @@ pub(crate) struct Acc {
findings: Vec<Finding>,
coverage: Vec<String>,
checks: Vec<&'static str>,
dml_coordinate_checked: bool,
/// Document-wide count of measured `DML-COORDINATE` Error findings seen across all XML parts.
dml_coordinate_errors: usize,
incomplete: bool,
limits: Limits,
rule_counts: HashMap<&'static str, usize>,
@@ -597,6 +643,40 @@ impl Acc {
self.checks.push(rule);
}
/// Record that a custom geometry scope was reached, once per package.
fn ran_dml_coordinate(&mut self) {
observation_contract! {
rules: "DML-COORDINATE";
collections: "-";
scope: "report applicability for custom geometry";
loss: "custom geometry may be absent from the scanned XML prefix";
fallback: "record the rule once when the scanner reaches custom geometry";
package_loss: "independent";
}
if !self.dml_coordinate_checked {
self.ran(DML_COORDINATE.id);
self.dml_coordinate_checked = true;
}
}
/// Count a measured `DML-COORDINATE` Error across the whole document and emit it via
/// [`Acc::add`] at most `findings_per_rule + 1` times so repeated overflow Errors cannot
/// append duplicate truncation coverage notes.
pub(crate) fn add_dml_coordinate_error(&mut self, part: String, message: String) {
observation_contract! {
rules: "DML-COORDINATE";
collections: "-";
scope: "document-wide measured DML-COORDINATE error count and capped emission";
loss: "per-rule finding cap";
fallback: "count every measured error across all XML parts and emit at most cap + 1 times so truncation is noted once";
package_loss: "independent";
}
self.dml_coordinate_errors = self.dml_coordinate_errors.saturating_add(1);
if self.dml_coordinate_errors <= self.limits.findings_per_rule.saturating_add(1) {
self.add(DML_COORDINATE.id, Some(part), message);
}
}
/// Record that the archive holds an entry whose identity could not be recovered. Absence
/// conclusions are suppressed from here on (see [`contracts_generated::PACKAGE_ABSENCE_RULES`]).
pub(crate) fn set_unknown_unreadable(&mut self) {
@@ -1467,8 +1547,8 @@ fn xml_source_complete(xml: &XmlScan, entry: &package::Entry) -> bool {
/// Scan all XML parts for well-formedness, undeclared prefixes, illegal characters, and extract story facts.
fn check_xml(pkg: &Package, acc: &mut Acc) -> XmlScan {
observation_contract! {
rules: "HEADERSOURCE-PRESENT,MATH-PLACEMENT,PROTECTION-PASSWORD,STRUCT-END-P,XML-INVALID-CHAR,XML-MALFORMED,XML-UNDECLARED-PREFIX";
collections: "access.prefix*1,access.retain_budget*1,field.comment_para_ids*1,field.content_part_exemptions*2,field.content_parts*2,field.entries*1,field.ink_content_parts*2,field.note_listings*1,field.refs*5,field.special_notes*1,field.unknown_prefixes*1,type.BTreeMap*1,type.HashMap*2,type.HashSet*2,type.Vec*13";
rules: "DML-COORDINATE,HEADERSOURCE-PRESENT,MATH-PLACEMENT,PROTECTION-PASSWORD,STRUCT-END-P,XML-INVALID-CHAR,XML-MALFORMED,XML-UNDECLARED-PREFIX";
collections: "access.prefix*1,access.retain_budget*1,field.comment_para_ids*1,field.content_part_exemptions*2,field.content_parts*2,field.dml_coordinate_warnings*1,field.entries*1,field.ink_content_parts*2,field.note_listings*1,field.refs*5,field.special_notes*1,field.unknown_prefixes*1,type.BTreeMap*1,type.HashMap*2,type.HashSet*2,type.Vec*15";
scope: "source-local bounded extraction; no implicit document owner";
loss: "source unavailable or malformed; XML event/depth budget; category allocation cap";
fallback: "retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set";
@@ -1510,6 +1590,7 @@ fn check_xml(pkg: &Package, acc: &mut Acc) -> XmlScan {
let mut pooled_refs = 0usize;
let mut refs_pooled_capped = false;
let mut refs_pooled_part: Option<String> = None;
let mut dml_coordinate_warnings: Vec<DeferredDmlWarning> = Vec::new();
for e in pkg.entries.iter().filter(|e| !e.is_dir) {
if !package::is_xml_part(pkg, &e.name) {
continue;
@@ -1542,6 +1623,8 @@ fn check_xml(pkg: &Package, acc: &mut Acc) -> XmlScan {
let Some(text) = &e.decoded else { continue };
let mut scanned = scan::scan_part(&e.name, text, role, acc);
append_dml_coordinate_warnings(&mut dml_coordinate_warnings, &e.name, scanned.dml_coordinate_warnings, acc.limits.findings_per_rule);
*note_incomplete_parts.entry(l.clone()).or_default() |= scanned.note_loss;
if append_note_items(&mut note_listings, &mut special_notes, &e.name, scanned.note_listings, scanned.special_notes, acc.limits.facts) {
*note_incomplete_parts.entry(l.clone()).or_default() |= scan::NOTE_ALL;
@@ -1634,6 +1717,7 @@ fn check_xml(pkg: &Package, acc: &mut Acc) -> XmlScan {
acc.add("XML-INVALID-CHAR", Some(e.name.clone()), format!("{} contains {desc}, which is illegal in XML 1.0", e.name));
}
}
flush_dml_coordinate_warnings(dml_coordinate_warnings, acc);
if pooled_capped {
let part = facts_pooled_part.as_deref().unwrap_or("an unknown part");
acc.note(format!("the pooled story facts exceeded {} entries at {part}; later facts were not recorded", acc.limits.facts));
@@ -1666,6 +1750,47 @@ fn check_xml(pkg: &Package, acc: &mut Acc) -> XmlScan {
XmlScan { graph, parts, compat }
}
type DeferredDmlWarning = (String, scan::DmlWarnEvidence, String);
/// Buffer deferred `DML-COORDINATE` Warnings across XML parts up to one past the finding cap
/// so Warnings can be emitted after all parts have been scanned without crowding out Errors.
fn append_dml_coordinate_warnings(out: &mut Vec<DeferredDmlWarning>, part: &str, part_warnings: Vec<(scan::DmlWarnEvidence, String)>, cap: usize) {
observation_contract! {
rules: "-";
collections: "type.Vec*2";
scope: "bounded deferred DML-COORDINATE warnings across XML parts";
loss: "per-rule finding cap";
fallback: "retain up to one warning past the cap to exercise truncation after measured errors";
package_loss: "independent";
}
let budget = cap.saturating_add(1).saturating_sub(out.len());
out.extend(part_warnings.into_iter().take(budget).map(|(evidence, message)| (part.to_string(), evidence, message)));
}
/// Emit deferred `DML-COORDINATE` Warnings after all XML parts have been scanned, keeping at
/// most one overflow Warning when measured Errors have not already exceeded the cap.
fn flush_dml_coordinate_warnings(deferred: Vec<DeferredDmlWarning>, acc: &mut Acc) {
observation_contract! {
rules: "DML-COORDINATE";
collections: "type.Observed*1,type.Vec*1";
scope: "deferred DML-COORDINATE warnings emitted after all XML parts";
loss: "per-rule finding cap";
fallback: "emit measured errors ahead of warnings and trigger truncation at most once";
package_loss: "independent";
}
let errors_seen = acc.dml_coordinate_errors;
let remaining = if errors_seen > acc.limits.findings_per_rule { 0 } else { (acc.limits.findings_per_rule - errors_seen).saturating_add(1) };
for (part, evidence, message) in deferred.into_iter().take(remaining) {
let evidence = match evidence {
scan::DmlWarnEvidence::ObservedContext => Evidence::Observed,
scan::DmlWarnEvidence::Unmeasured => Evidence::MsDocumented,
};
acc.add_graded(DML_COORDINATE.id, Severity::Warning, evidence, Some(part), message);
}
}
/// Attach each relationship fact collection's loss to its contributing source.
fn store_relationship_observations(
parts: &mut std::collections::BTreeMap<PartId, PartFacts>,
@@ -6974,6 +7099,219 @@ mod budget_tests {
assert!(mixed.findings.iter().any(|f| f.rule == "MEDIA-MAGIC" && f.severity == Severity::Warning));
}
#[test]
fn dml_coordinate_budget_keeps_errors_ahead_of_warnings_across_orderings_and_parts() {
let wrap_doc = |arcs: &str| {
format!(
r#"<?xml version="1.0"?><w:document xmlns:w="{NS_W}" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><w:body><w:p><w:r><a:custGeom><a:pathLst><a:path w="100" h="100">{arcs}</a:path></a:pathLst></a:custGeom></w:r></w:p></w:body></w:document>"#
)
.into_bytes()
};
let wrap_hdr = |arcs: &str| {
format!(
r#"<?xml version="1.0"?><w:hdr xmlns:w="{NS_W}" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><w:p><w:r><a:custGeom><a:pathLst><a:path w="100" h="100">{arcs}</a:path></a:pathLst></a:custGeom></w:r></w:p></w:hdr>"#
)
.into_bytes()
};
let zip_doc = |arcs: &str| {
tiny_zip(&[
("[Content_Types].xml", content_types()),
("_rels/.rels", package_rels()),
("word/document.xml", wrap_doc(arcs)),
("word/_rels/document.xml.rels", doc_rels()),
])
};
let warn_arc = r#"<a:arcTo wR="+12.5" hR="+12.5" stAng="0" swAng="cd4"/>"#;
let err_arc = r#"<a:arcTo wR="12.5" hR="12.5" stAng="0" swAng="cd4"/>"#;
let limits = Limits { findings_per_rule: 4, ..Limits::default() };
// Warnings-first, Errors-first, and interleaved orderings all keep both measured Errors
// ahead of Warnings and bound total DML-COORDINATE findings to the cap.
for (label, arcs) in [
("warnings then error", format!("{warn_arc}{warn_arc}{warn_arc}{err_arc}")),
("error then warnings", format!("{err_arc}{warn_arc}{warn_arc}{warn_arc}")),
("interleaved", format!("{warn_arc}{err_arc}{warn_arc}{warn_arc}")),
] {
let report = validate_bytes_limited(&zip_doc(&arcs), limits);
assert_eq!(report.verdict, Verdict::Fail, "{label}: {report:?}");
let dml: Vec<_> = report.findings.iter().filter(|f| f.rule == "DML-COORDINATE").collect();
assert_eq!(dml.len(), 4, "{label}: {dml:?}");
assert_eq!(dml.iter().filter(|f| f.severity == Severity::Error && f.evidence == Evidence::Observed).count(), 2, "{label}: {dml:?}");
assert_eq!(dml.iter().filter(|f| f.severity == Severity::Warning && f.evidence == Evidence::MsDocumented).count(), 2, "{label}: {dml:?}");
assert_eq!(
report.coverage_notes.iter().filter(|n| n.starts_with("more than 4 DML-COORDINATE")).count(),
1,
"{label}: {:?}",
report.coverage_notes
);
}
// Cross-part: Warnings in word/document.xml exceed the cap before a measured Error in word/header1.xml.
let cross_part = tiny_zip(&[
("[Content_Types].xml", content_types()),
("_rels/.rels", package_rels()),
("word/document.xml", wrap_doc(&format!("{warn_arc}{warn_arc}{warn_arc}"))),
("word/_rels/document.xml.rels", doc_rels()),
("word/header1.xml", wrap_hdr(err_arc)),
]);
let cross_report = validate_bytes_limited(&cross_part, limits);
assert_eq!(cross_report.verdict, Verdict::Fail, "{cross_report:?}");
let cross_dml: Vec<_> = cross_report.findings.iter().filter(|f| f.rule == "DML-COORDINATE").collect();
assert_eq!(cross_dml.len(), 4, "{cross_dml:?}");
assert_eq!(
cross_dml
.iter()
.filter(|f| f.part.as_deref() == Some("word/header1.xml") && f.severity == Severity::Error && f.evidence == Evidence::Observed)
.count(),
2,
"{cross_dml:?}"
);
assert_eq!(cross_report.coverage_notes.iter().filter(|n| n.starts_with("more than 4 DML-COORDINATE")).count(), 1);
// Warnings-only overflow still yields Incomplete with bounded Warnings and one truncation note.
let warn_only = validate_bytes_limited(&zip_doc(&format!("{warn_arc}{warn_arc}{warn_arc}")), limits);
assert_eq!(warn_only.verdict, Verdict::Incomplete, "{warn_only:?}");
let warn_dml: Vec<_> = warn_only.findings.iter().filter(|f| f.rule == "DML-COORDINATE").collect();
assert_eq!(warn_dml.len(), 4, "{warn_dml:?}");
assert!(warn_dml.iter().all(|f| f.severity == Severity::Warning));
assert_eq!(warn_only.coverage_notes.iter().filter(|n| n.starts_with("more than 4 DML-COORDINATE")).count(), 1);
// Errors-only overflow with extra Warnings retains only Errors up to the cap and emits
// exactly one truncation coverage note.
let err_overflow = validate_bytes_limited(&zip_doc(&format!("{warn_arc}{err_arc}{warn_arc}{err_arc}{err_arc}")), limits);
assert_eq!(err_overflow.verdict, Verdict::Fail, "{err_overflow:?}");
let err_dml: Vec<_> = err_overflow.findings.iter().filter(|f| f.rule == "DML-COORDINATE").collect();
assert_eq!(err_dml.len(), 4, "{err_dml:?}");
assert!(err_dml.iter().all(|f| f.severity == Severity::Error && f.evidence == Evidence::Observed));
assert_eq!(
err_overflow.coverage_notes.iter().filter(|n| n.starts_with("more than 4 DML-COORDINATE")).count(),
1,
"single-part overflow errors must not duplicate truncation notes: {:?}",
err_overflow.coverage_notes
);
// Cross-part error overflow: cap 4, six measured Errors across two parts (2+4, 4+2, and
// 6+2 with extra Warnings) must retain four Errors, emit exactly one DML-COORDINATE
// truncation coverage note, and Fail.
for (label, doc_arcs, hdr_arcs) in [
("2+4 errors across two parts", err_arc.to_string(), format!("{err_arc}{err_arc}")),
("4+2 errors across two parts", format!("{err_arc}{err_arc}"), err_arc.to_string()),
("6+2 errors plus warnings across two parts", format!("{warn_arc}{err_arc}{err_arc}{err_arc}"), format!("{err_arc}{warn_arc}")),
] {
let two_part = tiny_zip(&[
("[Content_Types].xml", content_types()),
("_rels/.rels", package_rels()),
("word/document.xml", wrap_doc(&doc_arcs)),
("word/_rels/document.xml.rels", doc_rels()),
("word/header1.xml", wrap_hdr(&hdr_arcs)),
]);
let report = validate_bytes_limited(&two_part, limits);
assert_eq!(report.verdict, Verdict::Fail, "{label}: {report:?}");
let dml: Vec<_> = report.findings.iter().filter(|f| f.rule == "DML-COORDINATE").collect();
assert_eq!(dml.len(), 4, "{label}: {dml:?}");
assert!(dml.iter().all(|f| f.severity == Severity::Error && f.evidence == Evidence::Observed), "{label}: {dml:?}");
assert_eq!(
report.coverage_notes.iter().filter(|n| n.starts_with("more than 4 DML-COORDINATE")).count(),
1,
"{label}: duplicate truncation notes: {:?}",
report.coverage_notes
);
}
// Exact cap (2 Warnings + 2 Errors == 4) records all 4 with no truncation note.
let exact = validate_bytes_limited(&zip_doc(&format!("{warn_arc}{err_arc}")), limits);
assert_eq!(exact.verdict, Verdict::Fail, "{exact:?}");
let exact_dml: Vec<_> = exact.findings.iter().filter(|f| f.rule == "DML-COORDINATE").collect();
assert_eq!(exact_dml.len(), 4, "{exact_dml:?}");
assert!(exact.coverage_notes.is_empty(), "{:?}", exact.coverage_notes);
}
#[test]
fn dml_coordinate_deferred_unselected_branch_warnings_preserve_observed_evidence_and_error_priority() {
let wrap_doc = |body: &str| {
format!(
r#"<?xml version="1.0"?><w:document xmlns:w="{NS_W}" xmlns:mc="{NS_MC}" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"><w:body><w:p><w:r>{body}</w:r></w:p></w:body></w:document>"#
)
.into_bytes()
};
let wrap_hdr = |body: &str| {
format!(
r#"<?xml version="1.0"?><w:hdr xmlns:w="{NS_W}" xmlns:mc="{NS_MC}" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"><w:p><w:r>{body}</w:r></w:p></w:hdr>"#
)
.into_bytes()
};
let geom = |arcs: &str| format!(r#"<a:custGeom><a:pathLst><a:path w="100" h="100">{arcs}</a:path></a:pathLst></a:custGeom>"#);
let frac_arc = r#"<a:arcTo wR="12.5" hR="12.5" stAng="0" swAng="cd4"/>"#;
let plus_arc = r#"<a:arcTo wR="+12.5" hR="+12.5" stAng="0" swAng="cd4"/>"#;
let ok_arc = r#"<a:arcTo wR="12" hR="12" stAng="0" swAng="cd4"/>"#;
let limits = Limits { findings_per_rule: 4, ..Limits::default() };
// Unselected-branch Warnings (Fallback after satisfiable Choice) exceed cap in document.xml,
// while a selected-branch Error sits later in header1.xml. Measured Errors must survive
// ahead of unselected-branch Warnings, and retained unselected-branch Warnings must keep
// Evidence::Observed while emitting a single truncation note.
let unselected_six = format!(
r#"<mc:AlternateContent><mc:Choice Requires="wps">{}</mc:Choice><mc:Fallback>{}</mc:Fallback></mc:AlternateContent>"#,
geom(ok_arc),
geom(&format!("{frac_arc}{frac_arc}{frac_arc}"))
);
let selected_two =
format!(r#"<mc:AlternateContent><mc:Choice Requires="wps">{}</mc:Choice><mc:Fallback/></mc:AlternateContent>"#, geom(frac_arc));
let cross_part = tiny_zip(&[
("[Content_Types].xml", content_types()),
("_rels/.rels", package_rels()),
("word/document.xml", wrap_doc(&unselected_six)),
("word/_rels/document.xml.rels", doc_rels()),
("word/header1.xml", wrap_hdr(&selected_two)),
]);
let report = validate_bytes_limited(&cross_part, limits);
assert_eq!(report.verdict, Verdict::Fail, "{report:?}");
let dml: Vec<_> = report.findings.iter().filter(|f| f.rule == "DML-COORDINATE").collect();
assert_eq!(dml.len(), 4, "{dml:?}");
assert_eq!(
dml.iter()
.filter(|f| f.part.as_deref() == Some("word/header1.xml") && f.severity == Severity::Error && f.evidence == Evidence::Observed)
.count(),
2,
"{dml:?}"
);
assert_eq!(
dml.iter()
.filter(|f| f.part.as_deref() == Some("word/document.xml") && f.severity == Severity::Warning && f.evidence == Evidence::Observed)
.count(),
2,
"{dml:?}"
);
assert_eq!(report.coverage_notes.iter().filter(|n| n.starts_with("more than 4 DML-COORDINATE")).count(), 1, "{:?}", report.coverage_notes);
// Mixed deferred Warning evidences in one part preserve each finding's own evidence class
// (Observed for unselected-branch measured fraction, MsDocumented for unmeasured "+12.5").
let mixed_warns = format!(
r#"<mc:AlternateContent><mc:Choice Requires="wps">{}</mc:Choice><mc:Fallback>{}</mc:Fallback></mc:AlternateContent>"#,
geom(ok_arc),
geom(&format!("{frac_arc}{plus_arc}"))
);
let mixed_zip = tiny_zip(&[
("[Content_Types].xml", content_types()),
("_rels/.rels", package_rels()),
("word/document.xml", wrap_doc(&mixed_warns)),
("word/_rels/document.xml.rels", doc_rels()),
]);
let mixed = validate_bytes_limited(&mixed_zip, limits);
assert_eq!(mixed.verdict, Verdict::Pass, "{mixed:?}");
let mixed_dml: Vec<_> = mixed.findings.iter().filter(|f| f.rule == "DML-COORDINATE").collect();
assert_eq!(mixed_dml.len(), 4, "{mixed_dml:?}");
for (raw, want_evidence) in [("\"12.5\"", Evidence::Observed), ("\"+12.5\"", Evidence::MsDocumented)] {
for attr in ["wR", "hR"] {
let finding = mixed_dml
.iter()
.find(|f| f.message.contains(attr) && f.message.contains(raw))
.unwrap_or_else(|| panic!("missing {attr}/{raw}: {mixed_dml:?}"));
assert_eq!((finding.severity, finding.evidence), (Severity::Warning, want_evidence), "{attr}/{raw}: {finding:?}");
}
}
}
#[test]
fn media_magic_webp_preflight_respects_and_charges_decode_budget() {
let malformed = b"RIFF\x04\0\0\0WEBP";
+519 -17
View File
@@ -386,6 +386,16 @@ impl StoryFacts {
}
}
/// Evidence basis for a deferred `DML-COORDINATE` Warning.
#[derive(Clone, Copy)]
pub(crate) enum DmlWarnEvidence {
/// Word-measured toleration (Strict part or definitively unselected `mc:AlternateContent` branch).
ObservedContext,
/// Unresolved part profile, unresolved `AlternateContent` selection, unmeasured attribute,
/// lexical class, entity encoding, or out-of-schema-range integer.
Unmeasured,
}
/// The result of scanning one XML or `.rels` part.
pub(crate) struct PartScan {
pub malformed: Option<String>,
@@ -426,6 +436,10 @@ pub(crate) struct PartScan {
pub fact_capped: bool,
/// The per-part reference budget dropped at least one `r:id`/`r:embed`/`r:link`.
pub refs_capped: bool,
/// Deferred `DML-COORDINATE` warning `(evidence, message)` pairs collected during this part
/// scan, bounded so Warnings can be flushed after all XML parts without crowding out measured
/// Errors.
pub dml_coordinate_warnings: Vec<(DmlWarnEvidence, String)>,
/// All XML events and story facts were examined; absence joins may use this part.
pub facts_complete: bool,
/// XML events completed independently of individual fact/reference allocation caps.
@@ -451,6 +465,10 @@ impl ElemId<'_> {
fn wp(&self) -> bool {
self.local_w(NS_WP)
}
/// Whether this element belongs to the DrawingML main namespace (`a:`).
fn a(&self) -> bool {
matches!(self.ns, Some(ns) if ns == NS_A.as_bytes() || ns == b"http://purl.oclc.org/ooxml/drawingml/main")
}
/// Whether this element belongs to the Office Math namespace (`m:`).
fn m(&self) -> bool {
self.local_w(NS_M)
@@ -679,6 +697,10 @@ struct Frame {
/// A `w:customXml` frame: likewise a prohibited direct parent only at block,
/// cell, or row level — a run-level `customXml` inside a paragraph is not.
is_custom_xml: bool,
/// This element is within an `a:custGeom` subtree.
in_custom_geometry: bool,
/// Distinguishes `a:CT_Path2D` from the gradient-fill `a:path` variant.
is_path_lst: bool,
tc_has_block: bool,
/// A block of known kind (or a skipped `AlternateContent`) was seen directly in this cell.
tc_known_block: bool,
@@ -691,9 +713,9 @@ struct Frame {
/// This frame is an `mc:AlternateContent` element.
alt: bool,
/// For an `mc:Choice` / `mc:Fallback` frame that assigned the
/// enclosing block's current branch: the branch value to restore
/// when this frame closes.
alt_branch_prev: Option<u32>,
/// enclosing block's current branch: the `(branch, in_selected_branch)`
/// pair to restore when this frame closes.
alt_branch_prev: Option<(u32, bool)>,
/// The element was opened inside a skipped `mc:AlternateContent` subtree, so its closing event
/// must not touch the frame counters or report structural findings.
suppressed: bool,
@@ -768,6 +790,8 @@ struct State {
alt_depth: usize,
/// One coverage note per part that contains `mc:AlternateContent`.
alt_noted: bool,
/// Profile of this part's root element namespace (Transitional, Strict, or Unresolved).
part_profile: PartProfile,
/// The per-category fact budget, copied from [`crate::Limits`].
fact_cap: usize,
/// A fact budget was exhausted; no further facts are collected.
@@ -1055,7 +1079,7 @@ fn decode_utf16_strict(bytes: &[u8], little_endian: bool) -> Result<String, Deco
pub(crate) fn scan_part(part: &str, text: &str, role: PartRole, acc: &mut Acc) -> PartScan {
observation_contract! {
rules: "STRUCT-TC-NO-P";
collections: "access.into_complete_set*2,access.invalidate*2,field.alt_stack*2,field.content_part_exemptions*2,field.content_parts*2,field.declared*8,field.frames*10,field.note_listings*1,field.note_listings_e*1,field.note_listings_f*1,field.para_ids*1,field.special_notes*2,field.unknown_prefixes*2,parser.parse_doctype_entities*1,type.BTreeMap*1,type.HashMap*1,type.HashSet*1,type.Observed*1,type.Vec*9";
collections: "access.into_complete_set*2,access.invalidate*2,field.alt_stack*2,field.content_part_exemptions*2,field.content_parts*2,field.declared*8,field.frames*10,field.note_listings*1,field.note_listings_e*1,field.note_listings_f*1,field.para_ids*1,field.special_notes*2,field.unknown_prefixes*2,parser.parse_doctype_entities*1,type.BTreeMap*1,type.HashMap*1,type.HashSet*1,type.Observed*1,type.Vec*10";
scope: "source-local bounded extraction; no implicit document owner";
loss: "source unavailable or malformed; XML event/depth budget; category allocation cap";
fallback: "retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set";
@@ -1086,6 +1110,7 @@ pub(crate) fn scan_part(part: &str, text: &str, role: PartRole, acc: &mut Acc) -
note_loss: 0,
fact_capped: false,
refs_capped: false,
dml_coordinate_warnings: Vec::new(),
facts_complete: false,
syntax_complete: false,
};
@@ -1116,7 +1141,8 @@ pub(crate) fn scan_part(part: &str, text: &str, role: PartRole, acc: &mut Acc) -
}
Ok(Event::Eof) => break,
Ok(Event::Start(e)) => {
if state.frames.is_empty() {
let is_root = state.frames.is_empty();
if is_root {
if root_count >= 1 {
out.malformed = Some("more than one document element".to_string());
break;
@@ -1139,11 +1165,13 @@ pub(crate) fn scan_part(part: &str, text: &str, role: PartRole, acc: &mut Acc) -
let decls = declarations(&attrs);
state.declared.push(decls);
note_unresolved_element(&mut state, &mut id, &[]);
record_root_profile(&mut state, is_root, &id);
let is_alt = enter_alt(&mut state, &id, part, acc);
let branch_prev = assign_alt_branch(&mut state, &id);
let branch_prev = assign_alt_branch(&mut state, &id, &attrs, reader.resolver(), &[]);
push_unknown_prefix(&mut out, &state.declared, &[], id.unknown.as_deref());
check_prefixes(&state.declared, &attrs, reader.resolver(), (&[], complete_entities.as_ref().map(|_| &entity_decls)), &mut out);
collect_ink_content_part(&id, &attrs, reader.resolver(), &mut out, acc.limits.facts);
check_dml_coordinates(&state, &id, &attrs, part, &mut out, acc);
if !was_suppressed {
collect_refs(&id, &attrs, reader.resolver(), &mut out, acc.limits.facts, &mut state.refs_capped);
collect_content_part(&id, &attrs, reader.resolver(), &mut out.content_parts, acc.limits.facts, &mut out.content_part_capped);
@@ -1161,11 +1189,18 @@ pub(crate) fn scan_part(part: &str, text: &str, role: PartRole, acc: &mut Acc) -
);
check_para_ids(&mut state, &id, &attrs, reader.resolver(), role, part, acc);
}
let frame = Frame { alt: is_alt, suppressed: was_suppressed, alt_branch_prev: branch_prev, ..frame_for(&id) };
let frame = Frame {
alt: is_alt,
suppressed: was_suppressed,
alt_branch_prev: branch_prev,
in_custom_geometry: in_custom_geometry(&state, &id),
..frame_for(&id)
};
state.frames.push(frame);
}
Ok(Event::Empty(e)) => {
if state.frames.is_empty() {
let is_root = state.frames.is_empty();
if is_root {
if root_count >= 1 {
out.malformed = Some("more than one document element".to_string());
break;
@@ -1181,11 +1216,13 @@ pub(crate) fn scan_part(part: &str, text: &str, role: PartRole, acc: &mut Acc) -
let was_suppressed = state.alt_depth > 0;
let decls = declarations(&attrs);
note_unresolved_element(&mut state, &mut id, &decls);
record_root_profile(&mut state, is_root, &id);
let is_alt = enter_alt(&mut state, &id, part, acc);
let branch_prev = assign_alt_branch(&mut state, &id);
let branch_prev = assign_alt_branch(&mut state, &id, &attrs, reader.resolver(), &decls);
push_unknown_prefix(&mut out, &state.declared, &decls, id.unknown.as_deref());
check_prefixes(&state.declared, &attrs, reader.resolver(), (&decls, complete_entities.as_ref().map(|_| &entity_decls)), &mut out);
collect_ink_content_part(&id, &attrs, reader.resolver(), &mut out, acc.limits.facts);
check_dml_coordinates(&state, &id, &attrs, part, &mut out, acc);
if !was_suppressed {
collect_refs(&id, &attrs, reader.resolver(), &mut out, acc.limits.facts, &mut state.refs_capped);
collect_content_part(&id, &attrs, reader.resolver(), &mut out.content_parts, acc.limits.facts, &mut out.content_part_capped);
@@ -1448,11 +1485,20 @@ fn enter_alt(state: &mut State, id: &ElemId, part: &str, acc: &mut Acc) -> bool
// An `AlternateContent` of unresolved namespace may be the markup-compatibility one: it is treated as that,
// so its branches are skipped exactly as the literal spelling's are (nothing in them is established).
let is_alt = id.local == "AlternateContent" && (id.ns == Some(NS_MC.as_bytes()) || id.unresolved);
let is_mc = id.ns == Some(NS_MC.as_bytes());
let is_alt = id.local == "AlternateContent" && (is_mc || id.unresolved);
if is_alt {
state.alt_depth += 1;
state.alt_seq += 1;
state.alt_stack.push(AltCtx { seq: state.alt_seq, branch: 0 });
state.alt_stack.push(AltCtx {
seq: state.alt_seq,
branch: 0,
is_mc,
choice_seen: false,
selected_seen: false,
selection_unresolved: !is_mc,
in_selected_branch: false,
});
if !state.alt_noted {
acc.note(format!("{part} contains mc:AlternateContent; its contents were skipped"));
state.alt_noted = true;
@@ -1505,6 +1551,8 @@ fn frame_for(id: &ElemId) -> Frame {
},
is_sdt_content: w && local == "sdtContent",
is_custom_xml: w && local == "customXml",
in_custom_geometry: false,
is_path_lst: id.a() && local == "pathLst",
tc_has_block: false,
tc_known_block: false,
tc_unresolved_candidate: false,
@@ -1946,6 +1994,405 @@ fn check_header_source(state: &mut State, id: &ElemId, role: PartRole, part: &st
}
}
/// Schema-defined integer bounds for DrawingML custom geometry types (`dml-main.xsd`).
/// `ST_CoordinateUnqualified` (§20.1.10.19): `i32::MIN * 12_700 ..= i32::MAX * 12_700`.
const DML_COORD_MIN: i64 = -27_273_042_329_600;
const DML_COORD_MAX: i64 = 27_273_042_316_900;
/// `ST_Angle` (§20.1.10.3): `xsd:int`.
const DML_ANGLE_MIN: i64 = i32::MIN as i64;
const DML_ANGLE_MAX: i64 = i32::MAX as i64;
/// Schema lexical domains and integer bounds used by the custom geometry types in `dml-main.xsd`.
#[derive(Clone, Copy)]
enum CoordKind {
/// `ST_PositiveCoordinate` (§20.1.10.41, path dimensions): integer only, `0..=27273042316900`.
PositiveCoordinate,
/// `ST_AdjCoordinate` (§20.1.10.2, coordinates/radii): `ST_CoordinateUnqualified`
/// (`-27273042329600..=27273042316900`), `ST_UniversalMeasure`, or `ST_GeomGuideName`.
AdjCoordinate,
/// `ST_AdjAngle` (§20.1.10.1, angles): `ST_Angle` (`xsd:int`, `-2147483648..=2147483647`)
/// or `ST_GeomGuideName`.
AdjAngle,
}
impl CoordKind {
fn allows_guide_name(self) -> bool {
matches!(self, Self::AdjCoordinate | Self::AdjAngle)
}
fn int_in_range(self, value: i64) -> bool {
match self {
Self::PositiveCoordinate => (0..=DML_COORD_MAX).contains(&value),
Self::AdjCoordinate => (DML_COORD_MIN..=DML_COORD_MAX).contains(&value),
Self::AdjAngle => (DML_ANGLE_MIN..=DML_ANGLE_MAX).contains(&value),
}
}
}
/// Classification of a custom geometry attribute value against its lexical domain.
#[derive(Clone, Copy, PartialEq, Eq)]
enum CoordLiteral {
/// Valid in-range integer, or (for adjustable attributes) a non-numeric guide name or
/// universal measure.
Valid,
/// Measured-refused decimal-fraction spelling (#8231, Word for Mac 16.114.4, 2026-12-02):
/// raw XML attribute source matching `[ ]*-?[0-9]+\.[0-9]+[ ]*` with an `i64`-representable
/// whole part.
MeasuredDecimalFraction,
/// Any other invalid numeric literal (unmeasured signs such as `+`, non-space whitespace
/// padding, entity/character-reference-encoded spellings, empty/whitespace-only, lone sign,
/// lone dot, leading/trailing dot, scientific notation, integer outside its schema type's
/// bounds or whole part outside `i64` range, or non-integer on an integer-only type).
OtherInvalid,
}
/// Return `(raw_source, normalized)` for an unprefixed attribute by exact name.
///
/// `raw_source` is the undecoded UTF-8 attribute slice from the XML source (preserving character
/// references, entity references, and literal `\t`/`\r`/`\n` before XML 1.0 attribute-value
/// normalization), while `normalized` is `Some` when XML 1.0 normalization succeeds and `None`
/// when normalization fails (for example, on a DOCTYPE-declared or unresolvable entity reference).
fn dml_attr_values<'a>(attrs: &'a [Attribute<'a>], name: &[u8]) -> Option<(&'a str, Option<String>)> {
let attr = attrs.iter().find(|a| a.key.as_ref() == name)?;
let raw_source = std::str::from_utf8(attr.value.as_ref()).ok()?;
let normalized = attr.normalized_value(quick_xml::XmlVersion::Implicit1_0).ok().map(std::borrow::Cow::into_owned);
Some((raw_source, normalized))
}
/// Whether `raw_source` (undecoded, unnormalized XML attribute value) belongs to the
/// measured-refused decimal-fraction lexical set (#8231, Word for Mac 16.114.4, 2026-12-02):
/// optional surrounding ASCII spaces (`' '`), optional leading `-`, one or more ASCII digits,
/// `.`, one or more ASCII digits, with an `i64`-representable signed whole part.
///
/// Unmeasured spellings — `+`-prefixed fractions, non-space whitespace (`\t`, `\r`, `\n`,
/// non-ASCII spaces), character-reference or entity encodings, exponent forms, leading/trailing
/// dot forms, empty/whitespace-only values, and out-of-`i64`-range whole parts — return `false`
/// and never take the `Error` / `Observed` path.
fn is_measured_decimal_fraction(raw_source: &str) -> bool {
let trimmed = raw_source.trim_matches(' ');
let Some((signed_whole, frac)) = trimmed.split_once('.') else { return false };
let whole = signed_whole.strip_prefix('-').unwrap_or(signed_whole);
!whole.is_empty()
&& !frac.is_empty()
&& whole.chars().all(|c| c.is_ascii_digit())
&& frac.chars().all(|c| c.is_ascii_digit())
&& signed_whole.parse::<i64>().is_ok()
}
/// Classify unqualified numeric literals using both the raw XML attribute source and its
/// XML 1.0 normalized value. Other tokens in adjustable attributes may be guide names
/// (including `3cd4`), or a unit-qualified `ST_UniversalMeasure` for coordinates.
/// Values whose XML 1.0 normalization failed (such as DOCTYPE-declared or unresolvable entity
/// references) classify as [`CoordLiteral::OtherInvalid`] so they reach the Warning path using
/// their raw text and never enter the `Error` / `Observed` path.
fn classify_dml_coord(raw_source: &str, normalized: Option<&str>, kind: CoordKind) -> CoordLiteral {
let Some(normalized) = normalized else {
return CoordLiteral::OtherInvalid;
};
let value = normalized.trim_matches([' ', '\t', '\r', '\n']);
if let Ok(int_value) = value.parse::<i64>() {
return if kind.int_in_range(int_value) { CoordLiteral::Valid } else { CoordLiteral::OtherInvalid };
}
if is_measured_decimal_fraction(raw_source) {
return CoordLiteral::MeasuredDecimalFraction;
}
let unsigned = value.strip_prefix(['+', '-']).unwrap_or(value);
let numeric =
unsigned.is_empty() || unsigned == "." || (unsigned.starts_with(|c: char| c.is_ascii_digit() || c == '.') && value.parse::<f64>().is_ok());
if kind.allows_guide_name() && !numeric { CoordLiteral::Valid } else { CoordLiteral::OtherInvalid }
}
/// The parser keeps each custom geometry scope even inside AlternateContent.
fn in_custom_geometry(state: &State, id: &ElemId) -> bool {
observation_contract! {
rules: "-";
collections: "field.frames*1";
scope: "custom geometry ancestry of the current XML event";
loss: "XML event/depth budget";
fallback: "use ancestry of events already scanned";
package_loss: "independent";
}
(id.a() && id.local == "custGeom") || state.frames.last().is_some_and(|frame| frame.in_custom_geometry)
}
/// Observed-Error custom geometry attributes (#8231): only measured decimal-fraction spellings in
/// `wR`/`hR` on `a:arcTo` (Transitional or Strict DrawingML namespace) have desktop consumer
/// refusal measurements (Word for Mac 16.114.4, 2026-12-02).
fn is_observed_decimal_attr(local: &str, attr: &str) -> bool {
local == "arcTo" && matches!(attr, "wR" | "hR")
}
/// Schema-typed custom geometry attributes of CT_Path2D, CT_Path2DArcTo, CT_AdjPoint2D,
/// CT_GeomRect, CT_XYAdjustHandle, CT_PolarAdjustHandle and CT_ConnectionSite in the model.
/// Entries outside [`is_observed_decimal_attr`] (and unmeasured invalid literals on any entry)
/// are unmeasured and graded Warning / MsDocumented.
fn dml_coord_spec(local: &str, is_path: bool) -> &'static [(&'static str, CoordKind)] {
use CoordKind::{AdjAngle, AdjCoordinate, PositiveCoordinate};
match local {
"arcTo" => &[("wR", AdjCoordinate), ("hR", AdjCoordinate), ("stAng", AdjAngle), ("swAng", AdjAngle)],
"pt" | "pos" => &[("x", AdjCoordinate), ("y", AdjCoordinate)],
"rect" => &[("l", AdjCoordinate), ("t", AdjCoordinate), ("r", AdjCoordinate), ("b", AdjCoordinate)],
"ahXY" => &[("minX", AdjCoordinate), ("maxX", AdjCoordinate), ("minY", AdjCoordinate), ("maxY", AdjCoordinate)],
"ahPolar" => &[("minR", AdjCoordinate), ("maxR", AdjCoordinate), ("minAng", AdjAngle), ("maxAng", AdjAngle)],
"cxn" => &[("ang", AdjAngle)],
"path" if is_path => &[("w", PositiveCoordinate), ("h", PositiveCoordinate)],
_ => &[],
}
}
/// Root namespace profile of the part currently being scanned.
#[derive(Clone, Copy, Default, PartialEq, Eq)]
enum PartProfile {
/// Root element namespace resolved to a Transitional (non-Strict) URI.
Transitional,
/// Root element namespace resolved to a Strict OOXML URI (`http://purl.oclc.org/ooxml/...`).
Strict,
/// Root element namespace could not be resolved by the scanner (for example, entity-obscured
/// `xmlns`, undeclared prefix, or no namespace binding).
#[default]
Unresolved,
}
/// Record the namespace profile of this part's root element.
fn record_root_profile(state: &mut State, is_root: bool, id: &ElemId) {
if is_root {
state.part_profile = match id.ns {
Some(ns) if !id.unresolved && is_strict_ooxml_ns(ns) => PartProfile::Strict,
Some(ns) if !id.unresolved && !ns.is_empty() => PartProfile::Transitional,
_ => PartProfile::Unresolved,
};
}
}
/// Whether a namespace URI belongs to the Strict OOXML family (`http://purl.oclc.org/ooxml/...`).
fn is_strict_ooxml_ns(ns: &[u8]) -> bool {
ns.starts_with(b"http://purl.oclc.org/ooxml/")
}
/// Whether `ns` is an exact full namespace URI proven by a Word measurement to be rejected as an
/// `mc:Choice/@Requires` capability without confounding MCE rejection.
///
/// Currently always returns `false`: no capability is populated by inference.
fn is_unsupported_word_mce_capability(ns: &[u8]) -> bool {
let _ = ns;
false
}
/// Whether `ns` is an exact full namespace URI known to be supported by Word as an
/// `mc:Choice/@Requires` capability.
///
/// The measured anchor is `http://schemas.microsoft.com/office/word/2010/wordprocessingShape`
/// (`wps`, corpus document `d60c276dc845` and Word for Mac 16.114.4 context probes).
/// The remaining entries are Word's own main WordprocessingML namespace (`w`) and the complete
/// URIs of Word's shipped MCE capability namespaces (`wordprocessingGroup`,
/// `wordprocessingCanvas`, `wordprocessingInk`, `wordprocessingDrawing`, 2010/2012
/// WordprocessingML, and 2010/2012 DrawingML extensions) that Word resolves as `Requires`
/// capabilities.
///
/// Match by exact URI equality only — closed list, never prefix or namespace-family matching.
/// Additions require a Word measurement or a Word-produced document showing the `Requires` value.
fn is_word_mce_capability(ns: &[u8]) -> bool {
matches!(
ns,
// WordprocessingML main namespace (w).
b"http://schemas.openxmlformats.org/wordprocessingml/2006/main"
// Word 2010 shapes (wps — measured anchor).
| b"http://schemas.microsoft.com/office/word/2010/wordprocessingShape"
// Word 2010 shape groups, drawing canvas, ink, and drawing extensions (wpg, wpc, wpi, wp14).
| b"http://schemas.microsoft.com/office/word/2010/wordprocessingGroup"
| b"http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas"
| b"http://schemas.microsoft.com/office/word/2010/wordprocessingInk"
| b"http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing"
// Word 2010 and 2012 WordprocessingML extensions (w14, w15).
| b"http://schemas.microsoft.com/office/word/2010/wordml"
| b"http://schemas.microsoft.com/office/word/2012/wordml"
// Office 2010 and 2012 DrawingML extensions (a14, pic14, dgm14, cdr14, a15, c15, cs).
| b"http://schemas.microsoft.com/office/drawing/2010/main"
| b"http://schemas.microsoft.com/office/drawing/2010/picture"
| b"http://schemas.microsoft.com/office/drawing/2010/diagram"
| b"http://schemas.microsoft.com/office/drawing/2010/chartDrawing"
| b"http://schemas.microsoft.com/office/drawing/2012/main"
| b"http://schemas.microsoft.com/office/drawing/2012/chart"
| b"http://schemas.microsoft.com/office/drawing/2012/chartStyle"
)
}
/// Three-state evaluation outcome of an `mc:Choice/@Requires` attribute.
#[derive(Clone, Copy, PartialEq, Eq)]
enum ChoiceState {
/// Every required prefix resolved to an exact URI in [`is_word_mce_capability`] (or `Requires`
/// was absent — measured in Word for Mac probe `r1`).
Supported,
/// At least one required prefix resolved to a URI not on the allowlist, could not be resolved
/// (undeclared, malformed, or entity-obscured), or `Requires` itself was empty or unreadable.
/// Makes the whole enclosing `mc:AlternateContent`'s selection uncertain.
Unresolved,
/// Reserved for capabilities a Word measurement proves Word rejects without confounding MCE
/// rejection. Never populated by inference; [`is_unsupported_word_mce_capability`] always
/// returns `false` today.
Unsupported,
}
/// Evaluate a single prefix token from `mc:Choice/@Requires` against [`is_word_mce_capability`].
fn prefix_requires_state(prefix: &str, res: &NamespaceResolver, declared: &[Vec<String>], own_decls: &[String]) -> ChoiceState {
observation_contract! {
rules: "-";
collections: "type.Vec*1";
scope: "namespace scope for one mc:Choice Requires prefix";
loss: "XML event/depth budget; entity-obscured xmlns declaration";
fallback: "treat unlisted, undeclared, malformed, or entity-obscured prefix bindings as unresolved rather than supported or unsupported";
package_loss: "independent";
}
if prefix.is_empty() || prefix.as_bytes().contains(&b':') {
return ChoiceState::Unresolved;
}
if nearest_binding(declared, own_decls, prefix) == Binding::Unresolved {
return ChoiceState::Unresolved;
}
let qname = format!("{prefix}:_");
match res.resolve_attribute(QName(qname.as_bytes())).0 {
ResolveResult::Bound(Namespace(ns)) if is_word_mce_capability(ns) => ChoiceState::Supported,
ResolveResult::Bound(Namespace(ns)) if is_unsupported_word_mce_capability(ns) => ChoiceState::Unsupported,
_ => ChoiceState::Unresolved,
}
}
/// Evaluate an `mc:Choice` element's `Requires` attribute into [`ChoiceState`]:
/// - Missing `Requires` is [`ChoiceState::Supported`] (measured in Word for Mac probe `r1`:
/// fractional radii inside an `mc:Choice` with no `Requires` attribute are refused).
/// - If every whitespace-delimited prefix resolves to an exact URI in [`is_word_mce_capability`],
/// returns [`ChoiceState::Supported`].
/// - If any prefix resolves to a URI in [`is_unsupported_word_mce_capability`] (currently none),
/// returns [`ChoiceState::Unsupported`].
/// - Otherwise (any unlisted URI, undeclared/malformed prefix, empty `Requires`, or
/// entity-obscured `Requires` / `xmlns`), returns [`ChoiceState::Unresolved`].
fn choice_requires_state(attrs: &[Attribute], res: &NamespaceResolver, declared: &[Vec<String>], own_decls: &[String]) -> ChoiceState {
observation_contract! {
rules: "-";
collections: "type.Vec*1";
scope: "mc:Choice Requires attribute evaluation in current namespace scope";
loss: "XML event/depth budget; entity-obscured Requires or xmlns declaration";
fallback: "withhold Error by returning Unresolved when Requires or any prefix binding is unlisted, empty, undeclared, or unreadable";
package_loss: "independent";
}
let Some(attr) = attrs.iter().find(|a| a.key.as_ref() == b"Requires") else {
return ChoiceState::Supported;
};
let Ok(value) = attr.normalized_value(quick_xml::XmlVersion::Implicit1_0) else {
return ChoiceState::Unresolved;
};
let mut saw_prefix = false;
let mut unresolved = false;
for prefix in value.split([' ', '\t', '\r', '\n']).filter(|prefix| !prefix.is_empty()) {
saw_prefix = true;
match prefix_requires_state(prefix, res, declared, own_decls) {
ChoiceState::Supported => {}
ChoiceState::Unsupported => return ChoiceState::Unsupported,
ChoiceState::Unresolved => unresolved = true,
}
}
if !saw_prefix || unresolved { ChoiceState::Unresolved } else { ChoiceState::Supported }
}
/// Enclosing `mc:AlternateContent` selection status for custom geometry checks.
#[derive(Clone, Copy, PartialEq, Eq)]
enum DmlBranchSelection {
/// Outside every `mc:AlternateContent`, or inside the Supported-selected branch of every
/// enclosing `mc:AlternateContent` (including a choice-less `mc:Fallback`).
Selected,
/// Inside a definitively unselected branch of at least one enclosing `mc:AlternateContent`.
Unselected,
/// At least one enclosing `AlternateContent` has unresolved selection (for example, an
/// unlisted `Requires` capability, a `Fallback` behind a Choice, or an entity-obscured
/// `xmlns` / `Requires`) and none is definitively unselected.
Unresolved,
}
/// Determine whether the current XML event sits in an established Supported-selected branch, a
/// definitively unselected branch, or an unresolved `AlternateContent` context.
fn dml_branch_selection(state: &State) -> DmlBranchSelection {
observation_contract! {
rules: "-";
collections: "field.alt_stack*1";
scope: "enclosing mc:AlternateContent branch selection for the current XML event";
loss: "XML event/depth budget";
fallback: "evaluate enclosing AlternateContent frames already scanned";
package_loss: "independent";
}
let mut unresolved = false;
for ctx in &state.alt_stack {
if ctx.is_mc && !ctx.selection_unresolved {
if !ctx.in_selected_branch {
return DmlBranchSelection::Unselected;
}
} else {
unresolved = true;
}
}
if unresolved { DmlBranchSelection::Unresolved } else { DmlBranchSelection::Selected }
}
/// Report invalid custom geometry literals from the XML events in every branch.
/// Measured Errors require ALL of: Transitional part profile + Supported-selected branch (bare
/// drawing, Supported `mc:Choice`, or choice-less `mc:Fallback` at every enclosing level) +
/// measured fractional geometry (`a:arcTo` `wR`/`hR`). Everything else is Warning, buffered in
/// `out` (bounded to one entry past the per-rule finding cap) and flushed after all XML parts
/// have been scanned so Warnings cannot crowd out measured Errors at the cap.
///
/// Warning grade precedence for measured fractional geometry:
/// 1. Strict part profile OR definitively unselected enclosing `mc:AlternateContent` branch
/// -> `Warning` / `Observed` (`DmlWarnEvidence::ObservedContext`).
/// 2. Unresolved part profile OR unresolved `AlternateContent` selection (only in a non-Strict
/// part with no definitively unselected enclosing branch)
/// -> `Warning` / `MsDocumented` (`DmlWarnEvidence::Unmeasured`).
fn check_dml_coordinates(state: &State, id: &ElemId, attrs: &[Attribute], part: &str, out: &mut PartScan, acc: &mut Acc) {
observation_contract! {
rules: "DML-COORDINATE";
collections: "field.dml_coordinate_warnings*2,field.frames*1";
scope: "source-local custom geometry attribute values";
loss: "source unavailable or malformed; XML event/depth budget";
fallback: "measured decimal-fraction spellings ([ ]*-?[0-9]+\\.[0-9]+[ ]* raw XML source) in a:arcTo wR/hR (Transitional or Strict DrawingML namespace) receive Error with Observed evidence only when the part profile is Transitional and every enclosing AlternateContent is Supported-selected (bare drawing, Supported Choice, or choice-less Fallback); Warning grade precedence: Strict parts and definitively unselected enclosing AlternateContent branches report Warning with Observed evidence, while unresolved part profiles and unresolved AlternateContent selections report Warning with MsDocumented evidence only in a non-Strict part with no definitively unselected enclosing branch; other invalid schema-typed custom geometry attributes and unmeasured or unresolvable lexical classes receive Warning with MsDocumented evidence; measured Errors are emitted ahead of Warnings; report invalid values in the scanned prefix";
package_loss: "independent";
}
if !id.a() || !in_custom_geometry(state, id) {
return;
}
if id.local == "custGeom" {
acc.ran_dml_coordinate();
}
let is_path = id.local == "path"
&& state.frames.iter().rev().find(|frame| !frame.alt && frame.alt_branch_prev.is_none()).is_some_and(|frame| frame.is_path_lst);
for &(attr_name, kind) in dml_coord_spec(&id.local, is_path) {
let Some((raw_source, normalized)) = dml_attr_values(attrs, attr_name.as_bytes()) else { continue };
let warning_evidence = match classify_dml_coord(raw_source, normalized.as_deref(), kind) {
CoordLiteral::Valid => continue,
CoordLiteral::MeasuredDecimalFraction if is_observed_decimal_attr(&id.local, attr_name) => {
match (state.part_profile, dml_branch_selection(state)) {
(PartProfile::Transitional, DmlBranchSelection::Selected) => {
acc.add_dml_coordinate_error(
part.to_string(),
format!("a:{} attribute {attr_name} has invalid coordinate or angle value {raw_source:?} in {part}", id.local),
);
continue;
}
(PartProfile::Strict, _) | (_, DmlBranchSelection::Unselected) => DmlWarnEvidence::ObservedContext,
(PartProfile::Transitional, DmlBranchSelection::Unresolved)
| (PartProfile::Unresolved, DmlBranchSelection::Selected | DmlBranchSelection::Unresolved) => DmlWarnEvidence::Unmeasured,
}
}
CoordLiteral::MeasuredDecimalFraction | CoordLiteral::OtherInvalid => DmlWarnEvidence::Unmeasured,
};
// Save one extra Warning past the cap to exercise the accumulator's truncation path
// while emitting measured Errors first across all XML parts.
if out.dml_coordinate_warnings.len() <= acc.limits.findings_per_rule {
out.dml_coordinate_warnings.push((
warning_evidence,
format!("a:{} attribute {attr_name} has invalid coordinate or angle value {raw_source:?} in {part}", id.local),
));
}
}
}
/// The AlternateContent ancestry of one `w14:paraId` occurrence: one
/// `(block, branch instance)` pair per enclosing `mc:AlternateContent`
/// block, outermost first. Branch instance 0 means the occurrence is
@@ -2072,6 +2519,21 @@ struct AltCtx {
/// no branch element, otherwise the instance number assigned to
/// the enclosing `mc:Choice` / `mc:Fallback` element.
branch: u32,
/// Whether the opening element resolved to the actual Markup Compatibility namespace (`NS_MC`).
is_mc: bool,
/// Whether this block has already seen any direct `Choice` child (`mc:Choice` or unresolved).
/// `mc:Fallback` is selected only when no `Choice` precedes it.
choice_seen: bool,
/// Whether this `mc:AlternateContent` block has already seen its established selected branch
/// (the first `Supported` `mc:Choice`, or `mc:Fallback` when no `Choice` is present).
selected_seen: bool,
/// Whether branch selection for this block is uncertain (the `AlternateContent` element's
/// namespace could not be resolved, an earlier direct `Choice`/`Fallback` before selection
/// was unresolved, a `Choice` before selection evaluated to [`ChoiceState::Unresolved`], or
/// `mc:Fallback` appeared behind a non-selected `Choice`).
selection_unresolved: bool,
/// Whether the scanner is currently inside this block's established selected branch.
in_selected_branch: bool,
}
/// The `w14:paraId` / `w14:textId` family (MS-DOCX §2.6.2.3 and
@@ -2155,10 +2617,10 @@ fn check_para_ids(state: &mut State, id: &ElemId, attrs: &[Attribute], res: &Nam
/// are different alternatives — and returns the block's previous
/// branch value, which the caller restores when the branch element
/// closes (its frame carries it; an empty element restores at once).
fn assign_alt_branch(state: &mut State, id: &ElemId) -> Option<u32> {
fn assign_alt_branch(state: &mut State, id: &ElemId, attrs: &[Attribute], res: &NamespaceResolver, own_decls: &[String]) -> Option<(u32, bool)> {
observation_contract! {
rules: "-";
collections: "field.alt_stack*1,field.frames*1";
collections: "field.alt_stack*1,field.declared*1,field.frames*1";
scope: "source-local bounded extraction; no implicit document owner";
loss: "source unavailable or malformed; XML event/depth budget; category allocation cap";
fallback: "retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set";
@@ -2175,15 +2637,54 @@ fn assign_alt_branch(state: &mut State, id: &ElemId) -> Option<u32> {
return None;
}
let ctx = state.alt_stack.last_mut()?;
let prev = ctx.branch;
let prev = (ctx.branch, ctx.in_selected_branch);
state.alt_branch_seq += 1;
ctx.branch = state.alt_branch_seq | if unresolved { BRANCH_UNKNOWN } else { 0 };
if id.local == "Choice" {
ctx.choice_seen = true;
}
if ctx.selection_unresolved {
ctx.in_selected_branch = false;
} else if ctx.is_mc && id.ns == Some(NS_MC.as_bytes()) {
match id.local.as_str() {
"Choice" if !ctx.selected_seen => match choice_requires_state(attrs, res, &state.declared, own_decls) {
ChoiceState::Supported => {
ctx.selected_seen = true;
ctx.in_selected_branch = true;
}
ChoiceState::Unsupported => {
ctx.in_selected_branch = false;
}
ChoiceState::Unresolved => {
ctx.selection_unresolved = true;
ctx.in_selected_branch = false;
}
},
"Fallback" if !ctx.selected_seen => {
if !ctx.choice_seen {
ctx.selected_seen = true;
ctx.in_selected_branch = true;
} else {
ctx.selection_unresolved = true;
ctx.in_selected_branch = false;
}
}
_ => {
ctx.in_selected_branch = false;
}
}
} else if unresolved {
if !ctx.selected_seen {
ctx.selection_unresolved = true;
}
ctx.in_selected_branch = false;
}
Some(prev)
}
/// Restore the innermost block's branch value saved by
/// `assign_alt_branch` when its branch element closes.
fn restore_branch(state: &mut State, prev: Option<u32>) {
fn restore_branch(state: &mut State, prev: Option<(u32, bool)>) {
observation_contract! {
rules: "-";
collections: "field.alt_stack*1";
@@ -2193,10 +2694,11 @@ fn restore_branch(state: &mut State, prev: Option<u32>) {
package_loss: "independent";
}
if let Some(prev) = prev
if let Some((prev_branch, prev_selected)) = prev
&& let Some(ctx) = state.alt_stack.last_mut()
{
ctx.branch = prev;
ctx.branch = prev_branch;
ctx.in_selected_branch = prev_selected;
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -65,7 +65,7 @@ Document title opens Rename Document; the account badge opens Options › Genera
| Caret motion: keys and typing glide the caret to its new place (100 ms, `cubic-bezier(0, 0, 0, 1)`), the blink fades (530 ms on and off, 100 ms fades); clicks and scripted moves don't glide. File › Options › Advanced › Animation (`ui.caretAnimation`) turns it off. The caret is black or white by contrast with what lies under it (paper, page colour, dark page, shading, highlight), never by the UI theme (#299). On Windows, whose inverting I-beam pointer stays white over the page, the pointer there is drawn the same way: black on light paper, white on dark (#1746) | ✅ as measured from Word for Windows (`caret_glide.rs`); zoom levels other than 100%, modifier keys and off-screen moves not measured | ✅ on Windows; Word for Mac not measured | 90% | 1–2 |
| Interface themes (light, dark, system #249, follows OS changes live #311), dark page separate from the interface theme (#194, #312); on a dark page highlights and character shading are dimmed, keeping their hue, so the text on them stays readable; coloured text below 4.5:1 on them is drawn white, and underlines and strikethroughs follow the same rule (#1252); Interface Theme as a searchable View command (light/dark/system, toggle without a value, #1861) | ✅ | ✅ | 90% | — |
| Interface size (File › Options › General: Auto, which keeps the system display scale and shows the size it draws at, or an absolute 75–300 %, so "100%" is one screen pixel per point; `ui.interfaceSize`; Auto is capped so a window of at least 900x460 points fits the smallest screen of the open windows (no cap while a screen's size is unknown, and never below 100 %, so a screen under 900x460 pixels may not hold the window), and Ctrl+Shift+0 (⌘⇧0) returns to Auto when no dialog is open and the key isn't bound to a command in Customize Keyboard; where Shift+0 types another character (`=` on German, Swiss and Nordic layouts) the chord is Ctrl+Shift+= (Superscript), and on Windows Ctrl+Shift+0 is often the input-language hotkey; there File › Options › General › Interface size returns to Auto, #4030) (#475, #822). A size from before #822 (on top of the display scale) becomes the absolute size it drew at. On the web the browser's zoom is part of the display scale, so a chosen size cancels browser zoom (Ctrl+plus/minus no longer resize the interface); Auto follows it | ✅ | system display scaling only | 100% | — |
| Animation effects (File › Options › Accessibility: Use system setting, On, Off; `ui.animations`). Off: a wheel notch scrolls at once; Ctrl+wheel zooms in whole steps, each drawn finished in its own frame (a notch at once; touchpad pinches and high-resolution wheels in steps of about 10% rather than gliding); menus, buttons and the scroll to the caret neither fade nor glide | ✅ "Use system setting" reads Windows (Animation effects), macOS (Reduce motion), the Linux/BSD desktops (settings portal: the cross-desktop reduced-motion preference, GNOME's switch, KDE's animation speed; the GTK and KDE settings files where no portal answers) and browsers (`prefers-reduced-motion`), and follows a change while running. Run on Windows and against a stand-in portal on Linux; not yet tried on a Mac or a real GNOME or KDE session | not compared | 90% | 0.5–1 |
| Animation effects (File › Options › Accessibility: Use system setting, On, Off; `ui.animations`). Off: a wheel notch scrolls at once; Ctrl+wheel zooms in whole steps, each drawn finished in its own frame (a notch at once; touchpad pinches and high-resolution wheels in steps of about 10% rather than gliding); menus, buttons and the scroll to the caret neither fade nor glide | ✅ "Use system setting" reads Windows (Animation effects), macOS (Reduce motion), the Linux/BSD desktops (settings portal: the cross-desktop reduced-motion preference, GNOME's switch, KDE's animation speed; the GTK and KDE settings files where no portal answers) and browsers (`prefers-reduced-motion`), and follows a change while running. On desktop, detecting a CPU graphics adapter disables animations under Use system setting even when the OS allows them. On the web, Use system setting follows the browser's motion preference even with software rendering. Explicit On and Off still apply on both hosts. Run on Windows and against a stand-in portal on Linux; not yet tried on a Mac or a real GNOME or KDE session | not compared | 90% | 0.5–1 |
| Focus and Full Screen (#1678, #980) | View › Focus fills the screen with the document on black, with a slim bar whose "⋯" drops the ribbon over the page; Full Screen View (`view.fullScreenView`, any key in Customize Keyboard) shows the pages alone with Search at the top; the two turn each other off. View › Window › Full Screen (`view.fullScreen`, F11, ⌃⌘F on macOS) fills the screen with the whole window, ribbon and all. Esc leaves Focus or Full Screen View, then Full Screen, once nothing nearer takes it; leaving gives back the earlier window size; the window manager's or macOS's own full screen keeps them in step. Ctrl+F1 (⌘⌥R on macOS) collapses or expands the ribbon; a shortcut of your own on Ctrl+F1 wins. Web: Full Screen off (the browser's own F11); Focus and Full Screen View hide the chrome only | Focus, Toggle Full Screen View (Alt, V, U, #1697), Word for Mac's View › Enter Full Screen, ⌘⌥R to collapse or expand the ribbon (Ctrl+F1 on Windows) | 85% | 0.5 |
| File dialogs (Open, Save As, Export, Insert Picture) | system dialog, without blocking the window (#94), its Save As type list naming every format with the document's own first (#1399); Linux/BSD: the desktop portal's Save dialog reports the file type picked, updating the extension so saving as PDF writes a PDF (#6180); Linux/BSD without a file chooser portal or zenity: WordCraft's own browser, also Browse in WordCraft… on File › Open, Save As and Export (#576, #3535) | system dialog | 95% | — |
| Linux display server (File › Options › Advanced: Automatic, Wayland, X11 (XWayland); `ui.displayServer`, #2184), kept in `ui.json` and applied at the next launch. `WORDCRAFT_WAYLAND` overrides it (`0`, `false`, `no` or `off` for X11, any other value for Wayland), and a choice that isn't available falls back to the other instead of failing to start; the log's `display:` line says which ran and why | ✅ Linux and the BSDs only; the choice is unit-tested, not yet tried on a real GNOME or KDE session | no equivalent (no Word for Linux) | 100% | 0 |
+2 -3
View File
@@ -111,6 +111,8 @@ pub fn run(_root: &Path, exact: bool) -> Result<(), String> {
#[cfg(test)]
mod tests {
use super::count_tests;
#[cfg(unix)]
use super::{Counts, walk};
#[test]
fn counts_attributes_and_proptest_blocks() {
@@ -118,9 +120,6 @@ mod tests {
assert_eq!(count_tests(src), (2, 1));
}
#[cfg(unix)]
use super::{Counts, walk};
#[cfg(unix)]
#[test]
fn a_walk_does_not_follow_directory_links() {