Compare commits

...
Author SHA1 Message Date
Martin BallandClaude Sonnet 5.5 241bf8c94d #8853: interface size uses the document window's display scale, not the hidden root's
Cause: the zoom is context-wide and divided the display scale read from the root viewport; the windowless root (v0.20.0) has no window, so it reported none (1.0) and a chosen size drew at size x the window's real scale (too large on a scaled display, wrong on mixed DPI). Now read from the active document viewport.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCXNomWeGUu3duixKdm
2026-12-05 06:15:17 +00:00
batistalucasv 824d3c431e test(ui): skip Arabic ribbon tests without embedded Arab face unless CRAFT_FONTS_REQUIRED=1 (#8000) 2026-12-05 02:41:31 -03:00
autocraft-bot[bot] 789cabd832 Merge pull request #9097 2026-12-05 03:48:27 +00:00
batistalucasv 6545c44f0a Engine tests: serialize dictionary-mutating tests and layout cache test on DICT_TEST_LOCK (#8886) 2026-12-05 00:48:27 -03:00
autocraft-bot[bot] b22e901c45 Merge pull request #9095 2026-12-05 03:45:18 +00:00
Martin BallandClaude Sonnet 5.5 c60c82d960 #8915: formula editor shades the active argument translucently, so its text shows
Cause: the port painted the argument shading with the opaque accent.soft token over the text. Fix: accent.solid at alpha 40, as v0.19.1's translucent shade.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCXNomWeGUu3duixKdm
2026-12-05 03:45:18 +00:00
autocraft-bot[bot] 67bfa46a3d Merge pull request #9093 2026-12-05 03:38:03 +00:00
batistalucasv 513ff0541f Windows: add valid child control case to cascade skip test (#9075) 2026-12-05 00:38:03 -03:00
autocraft-bot[bot] 6f7b8156dc Merge pull request #6361
With AutoCraft's conflict resolution bb27a377.
2026-12-05 03:32:03 +00:00
autocraft-bot[bot] a21324bf78 Merge pull request #9090 2026-12-05 03:32:03 +00:00
batistalucasv a39f6adf9f docs(layout-parity): state tblGrid width mismatch condition in table row and summary (#9077) 2026-12-05 00:32:03 -03:00
autocraft-bot[bot] b2dd74729f Merge pull request #9089 2026-12-05 03:30:34 +00:00
batistalucasv 5ea160c706 Layout: test stale_grid_widths refusal for gridAfter (#9079) 2026-12-05 00:30:34 -03:00
autocraft-bot[bot] 8a7fef3ec6 Merge pull request #9061 2026-12-05 03:27:47 +00:00
autocraft-bot[bot] 84118adcf9 Merge pull request #9088 2026-12-05 03:27:47 +00:00
yoriswind 0ec775a9b9 Text: honor either BOM for the generic UTF-32 label 2026-12-04 19:27:47 -08:00
autocraft-bot[bot] caf9c8de8b Left/Right in rotated table cells no longer jump to another cell, and th
Left/Right in rotated table cells no longer jump to another cell, and they step along the text at the edge of a cell's lines. `turned_line` now only counts turned lines with the same parent path as the caret's paragraph (same story level or same table cell). The engine's `line_step` falls back to `lr_along` when there is no such line. I added a layout test for the cell case and updated the typing-parity row. fmt, clippy and the layout and engine caret and vertical tests pass.
2026-12-05 03:21:26 +00:00
aionggandautocraft-bot[bot] <354215646+autocraft-bot[bot]@users.noreply.github.com> c07b649e7b Merge pull request #8978
Co-authored-by: autocraft-bot[bot] <354215646+autocraft-bot[bot]@users.noreply.github.com>
2026-12-05 03:20:54 +00:00
autocraft-bot[bot] 135c1f72b1 Merge pull request #7560
With AutoCraft's conflict resolution e90d6670.
2026-12-05 03:20:54 +00:00
autocraft-bot[bot] c70ad1bab2 Merge pull request #9083 2026-12-05 03:20:54 +00:00
yoriswind 4358f546d8 Insert Field: use language defaults for dates and times 2026-12-04 19:20:54 -08:00
autocraft-bot[bot] 6b79b722d3 Part 1: quit() in crates/ui-egui/src/windows.rs now returns true right
Part 1: `quit()` in crates/ui-egui/src/windows.rs now returns true right away when a quit is already pending and no print job is busy. It no longer calls `close_requested()` in that case, so a second quit can't use up `quit_recheck` or clear `quit_requested`. If a print job is busy, a second quit still goes through `close_requested()` and refuses, as before. On a first quit that is allowed, `quit_recheck` is set to true. I added no new test. Checks: `cargo fmt --all --check` passes. `cargo clippy -p wordcraft-ui-egui --all-targets -- -D warnings` passes; its only warning is the existing unused `egui_extras` dependency. The 9 lib tests matching `quit` pass, including `quit_commits_the_focused_fields_draft_before_asking`. I did not run the rest of the lib suite.
2026-12-05 03:17:04 +00:00
autocraft-bot[bot] eba89475f6 Merge pull request #9067 2026-12-05 03:15:57 +00:00
autocraft-bot[bot] 64ef08c60a Merge pull request #9065 2026-12-05 03:15:57 +00:00
autocraft-bot[bot] bc71452511 Merge pull request #9062 2026-12-05 03:15:57 +00:00
autocraft-bot[bot] fb9276c4a6 Part 1: in enter_outdents_an_empty_list_item_and_drops_direct_indents
Part 1: in `enter_outdents_an_empty_list_item_and_drops_direct_indents` (crates/engine/src/tests/typing.rs), the style sheet edit is now `Arc::make_mut(&mut doc.styles).upsert(..)` instead of `doc.styles.upsert(..)`. The lib tests build again and the new test passes. `cargo fmt --check` and `cargo clippy --all-targets` on wordcraft-engine report nothing. All 213 `typing` tests pass. I did not run the rest of the crate's tests.
2026-12-05 03:15:57 +00:00
batistalucasv 1129aa51f2 Replace All: skip hidden stories via Document::shown_stories (#9064) 2026-12-05 00:08:38 -03:00
yoriswind 70e181a966 Lists: reset direct indents when Enter outdents an empty item 2026-12-04 18:58:48 -08:00
autocraft-bot[bot] 496d276873 Merge pull request #9039 2026-12-05 02:58:25 +00:00
Martin BallandClaude Opus 5.5 32ad05fe64 #8832: a failed multi-picture edit puts the picture originals and looks back too
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCXNomWeGUu3duixKdm
2026-12-05 02:58:25 +00:00
Martin BallandClaude Sonnet 5.5 b2dd18c916 #8986: test vertical arrow line stepping in layout with the fixed fonts
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCXNomWeGUu3duixKdm
2026-12-05 02:57:53 +00:00
autocraft-bot[bot] dc9327501c Merge pull request #9058 2026-12-05 02:56:29 +00:00
batistalucasv b2021313ab Fix flaky continuous-view and connector-reroute engine tests (#9056) 2026-12-04 23:56:29 -03:00
autocraft-bot[bot] 41b351d770 Merge pull request #9057 2026-12-05 02:50:04 +00:00
batistalucasv 3fbc536eba test(canvas): derive tooltip wait frames from harness step time (#9052) 2026-12-04 23:50:04 -03:00
Martin BallandClaude Sonnet 5.5 7342c32b1e #8986: arrow keys follow vertical text like Word
Cause: Up/Down looked for horizontal lines only (turned lines are skipped), found none and
jumped to the story start/end; Left/Right always stepped along the text.
Fix: in turned text Up/Down step along the line and Left/Right move to the next/previous line
(direction by the text direction), via new DocLayout::turn_at and turned_line.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCXNomWeGUu3duixKdm
2026-12-05 02:46:47 +00:00
autocraft-bot[bot] 0f0551351a Merge pull request #8998 2026-12-05 02:41:01 +00:00
batistalucasv c99d119543 fix(ui): restore 56 pt mouse-wheel notch distance and eased wheel acceleration (#8840) 2026-12-04 23:41:01 -03:00
autocraft-bot[bot] a60bd414ed Merge pull request #7538 2026-12-05 02:40:33 +00:00
autocraft-bot[bot] 53d83510d7 Merge pull request #9048 2026-12-05 02:40:33 +00:00
autocraft-bot[bot] 58b595835f Merge pull request #9046 2026-12-05 02:40:33 +00:00
autocraft-bot[bot] 438c12d54a Merge pull request #9032 2026-12-05 02:40:33 +00:00
Martin BallandClaude Opus 5.5 fb813b7988 #8915: hiding the rulers drops a border drag they started
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCXNomWeGUu3duixKdm
2026-12-05 02:40:33 +00:00
autocraft-bot[bot] 67aa8ca4b7 The narrow-viewport test now checks the whole floating bar, so its right
The narrow-viewport test now checks the whole floating bar, so its right edge is covered. The pull request's head already had two of the three requested changes. The harness check finds the bar with `member(&h, "Bold")`, which only counts a Bold inside the canvas, and the `visible_anchor` half is gone. The third wasn't fully done: the test checked only the Bold button's rect. I changed it so that, after finding Bold with `member`, it looks up the bar itself (the group labelled "Formatting" that contains that Bold). It then asserts the bar's left, top, right and bottom edges each sit inside both `canvas(&h)` and the 220x480 viewport. All 29 `mini_toolbar::tests` pass under `cargo test`; cargo-nextest isn't installed here, so I didn't use it. `cargo fmt --check` passes, and clippy with `-D warnings` passes for the crate. Clippy's one warning is in the crate's manifest, not in the code: it reports an unused `egui_extras` dependency, which this change doesn't touch.
2026-12-05 02:31:20 +00:00
batistalucasv b8ac6de3d0 xtask(wasm): test wasm_test_set and wasm_summary by relations 2026-12-04 23:30:40 -03:00
batistalucasv db92b5cf2e test(ribbon): derive tooltip wait frames from harness step time (#9038) 2026-12-04 23:28:22 -03:00
autocraft-bot[bot] 18a8326ff0 Merge pull request #9025
With AutoCraft's conflict resolution 7e16be80.
2026-12-05 02:28:17 +00:00
autocraft-bot[bot] b1de6f8556 Merge pull request #9049 2026-12-05 02:28:17 +00:00
autocraft-bot[bot] d2ed8a334b Merge pull request #9045 2026-12-05 02:28:17 +00:00
batistalucasv c583679407 docs(layout-parity): split 2026-12-04 turned-text clarification into its own history row (#9043) 2026-12-04 23:28:17 -03:00
Martin BallandClaude Sonnet 5.5 e6ff55e758 #8921: a size typed in the Font Size box now applies on Enter
The box was bound to a local string rebuilt from the engine each frame, so the
first typed digit was reset and the edit cancelled as a host change. Pass the
size with Bind::given so edits come out as events and Enter runs format.size.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCXNomWeGUu3duixKdm
2026-12-05 02:25:41 +00:00
Martin BallandClaude Opus 5.5 7d45de75f6 #8832: Crop and Alt Text stay one-picture commands, as in Word
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCXNomWeGUu3duixKdm
2026-12-05 02:23:01 +00:00
autocraft-bot[bot] 84e7aee82f Merge pull request #9036 2026-12-05 02:19:44 +00:00
batistalucasv dfb7e2647e test(ui): use fixed assets/fonts catalog in mini_toolbar tests (#8901) 2026-12-04 23:19:44 -03:00
kiwi4boy c070c2a258 Layout: objects ending at the same edge give the span beside them the larger minimum
A picture and a floating table both ending at 70pt left the span after them
needing the picture's 18pt instead of the table's 20, when the picture came
first: an object only touching a span's edge didn't raise that edge's minimum.
2026-12-04 21:16:51 -05:00
Martin BallandClaude Sonnet 5.5 ba7318322a #8832: picture formatting applies to every selected picture
Border, style, effects, colour, corrections, transparency, crop, reset and alt text read
only the first selected picture. each_picture runs the one-picture command on each target
in turn (one undo step) and restores the selection, which stays multi-selected.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCXNomWeGUu3duixKdm
2026-12-05 02:13:39 +00:00
autocraft-bot[bot] b7f52b6c78 Merge pull request #9027
With AutoCraft's conflict resolution 825b3b17.
2026-12-05 02:12:28 +00:00
autocraft-bot[bot] 4d7be007da Merge pull request #9026 2026-12-05 02:12:28 +00:00
autocraft-bot[bot] 14280d1c03 Merge pull request #2341
With AutoCraft's conflict resolution e1ebd40e.
2026-12-05 02:12:28 +00:00
autocraft-bot[bot] 2bf03bcfc6 Merge pull request #2297
With AutoCraft's conflict resolution 9ff6f7e5.
2026-12-05 02:12:28 +00:00
autocraft-bot[bot] ea2e2f2970 Merge pull request #9034 2026-12-05 02:12:28 +00:00
batistalucasv f5892400de Layout: test stale_grid_widths refusals for gridBefore and edge mismatches (#8907) 2026-12-04 23:12:28 -03:00
Martin BallandClaude Opus 5.5 874184f066 #8945: the last tab selected in a frame wins
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCXNomWeGUu3duixKdm
2026-12-05 02:11:14 +00:00
Martin BallandClaude Sonnet 5.5 501dddf7b5 #8915: turning the ruler off in View hides the rulers
The craft port called page_rulers on every pass, so the horizontal and vertical
rulers kept drawing (over the page's strips) after view.ruler was switched off,
and in Draft, Outline and Focus. Show them only when the page view reserves
the strips, as show_rulers already decides.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCXNomWeGUu3duixKdm
2026-12-05 02:10:01 +00:00
kiwi4boy 1f6eb8eceb Merge remote-tracking branch 'origin/main' into tight-gap-6316
Conflicts with main's right-to-left floating table offset (FloatPlace) in
boxes.rs, the line-end kerning helper in para/lines.rs and new rows in
docs/layout-parity.md; both sides kept. The hidden-mark joined-line areas
main added (#3986) are AreaKind::Object, as every non-table area was the
previous bool's false.
2026-12-04 21:07:21 -05:00
autocraft-bot[bot] 087bf2535b Merge pull request #9017 2026-12-05 02:05:47 +00:00
autocraft-bot[bot] 7a408c7eb3 Part 1: I added mod reproducible_pdf; to apps/wordcraft-cli/tests/it/m
Part 1: I added `mod reproducible_pdf;` to apps/wordcraft-cli/tests/it/main.rs, between `mod picture_then_typing;` and `mod strict;`. The moved tests are now compiled into the `it` test binary again. `cargo fmt --check` is clean. `cargo clippy --offline -p wordcraft-cli --all-targets -- -D warnings` finished with no errors. `TZ=UTC cargo test --offline -p wordcraft-cli --test it reproducible_pdf` now runs 5 tests and all pass.
2026-12-05 02:05:47 +00:00
batistalucasv a1ad0f4cbc docs(layout-parity): document autofit table row-width rule (#8923) 2026-12-04 22:59:52 -03:00
batistalucasv 9c54fc1446 test(docx): verify run style and resolved emphasis across saves (#8936) 2026-12-04 22:57:24 -03:00
Martin BallandClaude Sonnet 5.5 e3f9ed8134 #8945: regression test for Navigation pane tab clicks
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-05 01:55:48 +00:00
autocraft-bot[bot] 195f103ceb I put escape_reverts_a_comment_draft back on the balloon path. It now
I put `escape_reverts_a_comment_draft` back on the balloon path. It now uses the comment harness, `click_balloon`, types a draft, presses Escape (one frame), then calls `leave_field`, which really clicks on the page. The final check that nothing is written is back. I added one assertion before it: the page click must have left the balloon (no balloon selected), so `deselect_balloon`/`write_back` really ran.

To make the test faster, `comment_harness` now passes through a new `comment_harness_in(size, settle)`, and `window_dt` through a new `sized_window(a, size, dt, settle)`. The other tests still get exactly the window they had: 1440x900 with 6 settle frames. The Escape test uses a 1024x768 window and no settle frames of its own, because `click_balloon` settles before it clicks. That is 18 frames instead of the original 24.

`comment_field` was already private at this head (the author had reverted it), so item 4 needed no change.

Checks: `cargo fmt --check` is clean, clippy on wordcraft-ui-egui with all targets and `-D warnings` is clean, and all 20 tests in canvas::tests::markup pass. As a temporary check, I put a draft back just before `leave_field`. The final assertion then failed with "Discarded" written over "Original", so it can catch the regression the review describes. I then reverted that change.
2026-12-05 01:52:39 +00:00
batistalucasv b6777d494c test(wordcraft-cli): move reproducible_pdf integration tests into tests/it 2026-12-04 22:38:32 -03:00
Martin BallandClaude Sonnet 5.5 06d7d3e9a6 #8945: Navigation pane Headings, Pages and Results tabs switch views again
The pane read TabStrip's overflow-menu pick (out.picked) instead of the selection event a click or key raises, so tabs never switched and search results stuck. Read the selection event.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-05 00:41:46 +00:00
autocraft-bot[bot] 94aa34729c Ask about a focused field's typed text when quitting from the menu
Ask about a focused field's typed text when quitting from the menu

When the app menu's Quit (⌘Q) or the Dock's Quit found nothing unsaved, it set `quit_requested` right away. Text still typed in a focused field (for example a table title in the Alt Text pane) only reaches the document on the root close that follows. That close was then let through, so the text was lost without a prompt.

I followed AutoCraft's plan without changes. Upstream craft-libs has not fixed this: on its main branch, `commit_focused` and `draft_held` are still crate-private and the root-close path is unchanged, so the fix is in this app, not a repin.
- `WordApp` gets a `quit_recheck` flag. It is set up in `app.rs` and added to the full field list in `window_ui.rs`.
- `quit()` in `windows.rs` sets `quit_recheck` when it allows a quit that was not already set. Its doc comment now says a true answer can still turn into a prompt at the host's close.
- `close_requested()` in `app/files.rs` clears `quit_recheck` when `quit_requested` is set, and checks once more for unsaved documents. If the close has committed typed text, it clears `quit_requested` and asks Save Changes as usual. Quits that were already answered (Don't Save, prompts, `app.quit`, forced `ui.quit`) never set the flag, so they are not asked again.
- One new test in `control/tests.rs`, `quit_commits_the_focused_fields_draft_before_asking`. It checks that a root close with a title typed in the focused Alt Text field shows Save Changes. It checks that `ui.quit` followed by the host's close also shows Save Changes, keeps the title, and leaves `quit_requested` false. It also checks that Don't Save then quits and is not asked again on the next close.

Testing:
- The new test passes. I did not rerun it without the fix; AutoCraft's investigation showed the same core assertions failing on the default branch.
- The crate's 62 quit and close tests pass.
- `cargo fmt --all --check` passes.
- `cargo clippy -p wordcraft-ui-egui --all-targets -- -D warnings` passes; its only warnings are unused workspace dependencies in the manifest that were already there.
- The full `wordcraft-ui-egui` lib suite was started but did not finish before the session's shell time ran out, so I can't report it.
- Not run: `cargo xtask layers`, `cargo xtask wasm`, and the tests in `apps/wordcraft`, including its ⌘Q test.
2026-12-04 22:40:52 +00:00
autocraft-bot[bot] d0dbc425ee I made both changes FredApps asked for in crates/doc/src/numbering.rs. A
I made both changes FredApps asked for in crates/doc/src/numbering.rs. A start override of 0 now makes the first item 0, and the new test `start_override_of_zero_starts_at_zero` sets `start_overrides = vec![(0, 0)]` and gets the labels ["0.", "1.", "2."].

How the fix works: `Counters` has a new per-list field, `first`. When a start override is applied, the level's counter is cleared and the override value is kept in `first` as the value the next item takes. The first item at that level takes that value instead of the level's own start. Later items count up as before. When a higher level restarts a deeper one, any override still waiting on the deeper level is dropped too, as the old `start - 1` value was.

Overrides of 1 and above give the same first numbers as before, and a level whose own start is 0 still starts at 0. The existing tests for restarting lists, restart levels and start 0 still pass.

Test results: formatting and clippy are clean for wordcraft-doc, and its 148 tests pass. The wordcraft-docx tests pass. In wordcraft-layout, 325 tests pass and 6 fail (line justification, tabs, widow control, footnotes, a floating table, linear-time layout). None of those 6 builds a list, so the failures don't come from this change, but I did not run them without it to confirm.
2026-12-04 21:26:59 +00:00
autocraft-bot[bot] 6e67012f78 I made both changes FredApps asked for in crates/formats/src/txt.rs. Fir
I made both changes FredApps asked for in crates/formats/src/txt.rs. First, in the table branch of `blocks_text`, the two identical branches are now one: `if c.covered || depth > 8 { cells.push(String::new()); } else { ... }`. This fixes the clippy::if_same_then_else error. Second, the test `test_table_export_colspan_covered_and_newline_cleaning` now builds its cells as `let mut c1 = Cell { colspan: 2, ..Default::default() };` and `let c3 = Cell { covered: true, ..Default::default() };`. c1 stays `mut` because the test adds a paragraph to it afterwards, and c3 no longer needs `mut`. `cargo fmt --check` passes. `cargo clippy --offline -p wordcraft-formats --all-targets -- -D warnings` finished with no warnings, so neither lint fires now. I only ran the three txt tests, and all of them pass; the full wordcraft-formats test run timed out in the build pod, so it wasn't run. Nothing else changed.
2026-12-04 21:24:50 +00:00
batistalucasv 1342420920 test(comments): assert draft remains empty after clicking away 2026-11-30 01:50:11 -03:00
batistalucasv b917ca74c1 Address review feedback: drive balloon editor and leave_field in escape_reverts_a_comment_draft (#1348) 2026-11-27 01:11:56 -03:00
batistalucasv 03070810eb Address review feedback: verify mini toolbar stays inside narrow viewport and canvas (#7317) 2026-11-27 00:47:26 -03:00
batistalucasv 4b772c030c test(mini_toolbar): pass rtl arg and verify bar placement in narrow viewport (#7317) 2026-11-26 14:01:26 -03:00
batistalucasv 3794d9718e Merge remote-tracking branch 'upstream/main' into HEAD 2026-11-26 13:55:13 -03:00
kiwi4boy 97daa4b3ed Layout: main's balanced-column test marks its float as an object (AreaKind, #6316) 2026-11-25 19:36:46 -05:00
kiwi4boy 7b03696d8c Merge remote-tracking branch 'origin/main' into tight-gap-6316
# Conflicts:
#	docs/layout-parity.md
2026-11-25 19:32:35 -05:00
batistalucasv bbad606bc3 test(ui-egui): run escape_reverts_a_comment_draft directly against comment_field 2026-11-25 12:46:16 -03:00
batistalucasv 49f89569d0 test(ui-egui): restore escape_reverts_a_comment_draft regression test (#1348)
Restores the regression test from #7101 for comment draft cancellation:
- escape_reverts_a_comment_draft (#1348, data-loss): Verifies that pressing Escape in a comment balloon field cancels the uncommitted draft buffer without mutating the original comment text, and asserts that subsequently unfocusing/leaving the field does not trigger delayed writes.
2026-11-22 22:11:50 -03:00
batistalucasv 408dcc0367 test(mini_toolbar): restore test for tiny viewport anchor rect (#7317)
Restores the `a_viewport_narrower_than_the_bar_still_yields_a_rect` test (#7317, tag: keyboard) adapted to the post-#7101 `visible_anchor` implementation in `crates/ui-egui/src/mini_toolbar/tests.rs`.
2026-11-22 20:13:40 -03:00
kiwi4boy 0ee236e6a4 Merge remote-tracking branch 'origin/main' into tight-gap-6316
# Conflicts:
#	crates/layout/src/para/lines.rs
#	docs/layout-parity.md
2026-11-20 19:22:23 -05:00
kiwi4boy f94aecace7 Merge remote-tracking branch 'origin/main' into tight-gap-6316 2026-11-11 18:00:18 -05:00
kiwi4boy 366b89341d Layout: a span beside floats takes the minimum of its own two edges (#6316)
A table splitting a span first left its 20pt minimum on the far piece, so a
19pt gap bordered only by a picture was refused in that order alone. Each span
now keeps its left and right edge's minimum separately.
2026-11-11 17:04:09 -05:00
kiwi4boy 0c7f425e91 Layout: text goes beside a floating picture in an 18pt gap, as in Word (#6316)
A line goes beside a floating picture or shape when the gap from the column
edge to its wrap area is at least 18pt (was 20), and beside a tight or through
one at least 9pt before Word 2013 layout; floating tables keep 20pt. Each span
takes the largest minimum of the objects bordering it. WrapArea's table flag
becomes AreaKind (Object, Tight, Table) so tight objects without an outline
are known too.
2026-11-11 16:20:53 -05:00
Divyanshu Gupta 59e818424c fix(doc): handle start 0 list counters and preserve literal %0 placeholders 2026-10-16 07:31:55 +05:30
Divyanshu Gupta 02e7bbc640 fix(formats): support UTF-32 BOM decoding, preserve vertical tabs in text import, and handle colspan in table export 2026-10-16 05:28:22 +05:30
57 changed files with 1455 additions and 300 deletions
+1
View File
@@ -9,5 +9,6 @@ mod mcp_roots;
#[cfg(all(unix, not(target_os = "macos")))]
mod non_utf8_args;
mod picture_then_typing;
mod reproducible_pdf;
mod strict;
mod text_tracked;
+38
View File
@@ -519,6 +519,7 @@ fn render_label<'a>(level_def: impl Fn(usize) -> Option<&'a Level>, def: &Level,
while let Some(c) = chars.next() {
if c == '%'
&& let Some(d) = chars.peek().and_then(|d| d.to_digit(10))
&& (1..=9).contains(&d)
{
chars.next();
let k = (d as usize).saturating_sub(1).min(8);
@@ -842,6 +843,43 @@ mod tests {
assert_eq!(c.next_label(&n, r, 0).unwrap().0, "Part V");
}
#[test]
fn start_zero_counters_increment_properly() {
let mut n = Numbering::default();
let id = n.add_list(ListKind::Numbered);
if let Some(a) = n.abstracts.first_mut() {
a.levels[0].start = 0;
a.levels[0].text = "Item %1.".into();
}
let mut c = Counters::default();
assert_eq!(c.next_label(&n, id, 0).unwrap().0, "Item 0.");
assert_eq!(c.next_label(&n, id, 0).unwrap().0, "Item 1.");
assert_eq!(c.next_label(&n, id, 0).unwrap().0, "Item 2.");
}
#[test]
fn start_override_of_zero_starts_at_zero() {
let mut n = Numbering::default();
let id = n.add_list(ListKind::Numbered);
if let Some(num) = n.nums.iter_mut().find(|x| x.id == id) {
num.start_overrides = vec![(0, 0)];
}
let mut c = Counters::default();
let labels: Vec<String> = (0..3).map(|_| c.next_label(&n, id, 0).unwrap().0).collect();
assert_eq!(labels, ["0.", "1.", "2."]);
}
#[test]
fn placeholder_percent_zero_is_preserved_as_literal() {
let mut n = Numbering::default();
let id = n.add_list(ListKind::Numbered);
if let Some(a) = n.abstracts.first_mut() {
a.levels[0].text = "%0 %1.".into();
}
let mut c = Counters::default();
assert_eq!(c.next_label(&n, id, 0).unwrap().0, "%0 1.");
}
#[test]
fn definition_index_keeps_first_ids_overrides_and_missing_definitions() {
let override_level = Level { start: 0, text: "own %1".into(), ..Default::default() };
+27 -23
View File
@@ -122,7 +122,6 @@ fn run_and_style_emphasis_marks_survive_two_saves() {
</w:p>
"#;
let mut doc = wordcraft_docx::read(&docx(body, styles)).unwrap();
let p = doc.body.iter().find_map(|b| b.as_para()).unwrap();
let expected_styles = [
("Dot", Some(EmphasisMark::Dot)),
("Comma", Some(EmphasisMark::Comma)),
@@ -130,24 +129,33 @@ fn run_and_style_emphasis_marks_survive_two_saves() {
("UnderDot", Some(EmphasisMark::UnderDot)),
("NoMark", Some(EmphasisMark::None)),
];
for (id, mark) in expected_styles {
assert_eq!(doc.styles.get(id).and_then(|style| style.chr.emphasis), mark);
}
let expected_run_marks = [
None,
None,
None,
None,
Some(EmphasisMark::None),
None,
Some(EmphasisMark::Dot),
Some(EmphasisMark::Comma),
Some(EmphasisMark::Circle),
Some(EmphasisMark::UnderDot),
Some(EmphasisMark::None),
None,
let expected_runs = [
(Some("Dot"), None, EmphasisMark::Dot),
(Some("Comma"), None, EmphasisMark::Comma),
(Some("Circle"), None, EmphasisMark::Circle),
(Some("UnderDot"), None, EmphasisMark::UnderDot),
(Some("Dot"), Some(EmphasisMark::None), EmphasisMark::None),
(Some("NoMark"), None, EmphasisMark::None),
(None, Some(EmphasisMark::Dot), EmphasisMark::Dot),
(None, Some(EmphasisMark::Comma), EmphasisMark::Comma),
(None, Some(EmphasisMark::Circle), EmphasisMark::Circle),
(None, Some(EmphasisMark::UnderDot), EmphasisMark::UnderDot),
(None, Some(EmphasisMark::None), EmphasisMark::None),
(None, None, EmphasisMark::None),
];
assert_eq!(p.runs.iter().map(|run| run.props.emphasis).collect::<Vec<_>>(), expected_run_marks);
let assert_state = |doc: &wordcraft_doc::Document, stage: &str| {
for (id, mark) in expected_styles {
assert_eq!(doc.styles.get(id).and_then(|style| style.chr.emphasis), mark, "{stage}: style {id}");
}
let p = doc.body.iter().find_map(|b| b.as_para()).unwrap();
let actual: Vec<_> = p
.runs
.iter()
.map(|r| (r.props.style.as_deref(), r.props.emphasis, doc.styles.resolve_char(p.props.style.as_deref(), &r.props).emphasis))
.collect();
assert_eq!(actual, expected_runs, "{stage}");
};
assert_state(&doc, "initial read");
for pass in 0..2 {
let out = wordcraft_docx::write(&doc).unwrap();
@@ -159,11 +167,7 @@ fn run_and_style_emphasis_marks_survive_two_saves() {
assert!(document_xml.contains(r#"<w:em w:val="none"/>"#), "pass {pass}: {document_xml}");
assert!(document_xml.contains("default dot"));
doc = wordcraft_docx::read(&out).unwrap();
for (id, mark) in expected_styles {
assert_eq!(doc.styles.get(id).and_then(|style| style.chr.emphasis), mark, "pass {pass}");
}
let p = doc.body.iter().find_map(|b| b.as_para()).unwrap();
assert_eq!(p.runs.iter().map(|run| run.props.emphasis).collect::<Vec<_>>(), expected_run_marks, "pass {pass}");
assert_state(&doc, &format!("pass {pass}"));
}
}
+1
View File
@@ -513,6 +513,7 @@ fn split_para_as(s: &mut Session, at: &Pos, enter: bool) -> Result<Pos, CmdError
let para = s.doc.para_mut(at.story, &at.path)?;
if n.level > 0 {
para.props.numbering = Some(wordcraft_doc::props::NumRef { num: n.num, level: n.level - 1 });
para::drop_direct_indents(&mut para.props);
para.touch();
} else {
leave_list(para);
+46
View File
@@ -3,6 +3,7 @@
use serde_json::Value;
use wordcraft_doc::math_edit::MathPos;
use wordcraft_doc::para::{NBSP, OBJ};
use wordcraft_doc::props::TextDirection;
use wordcraft_doc::{InlineObject, Paragraph, Path, Pos, StoryRef};
use wordcraft_layout::ViewMode;
@@ -113,6 +114,47 @@ fn bidi_para(s: &Session) -> bool {
/// Left/Right: with a selection and no Shift, collapse to its edge.
fn lr(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
if let Some(t) = turn(s) {
// Vertical text (#8986): Left/Right change line; top-to-bottom lines stack leftwards.
return line_step(s, v, (t == TextDirection::Down) == is_left, is_left);
}
lr_along(s, v, is_left)
}
/// The text direction at the caret when it is in turned (vertical) text.
fn turn(s: &mut Session) -> Option<TextDirection> {
let l = s.layout();
l.turn_at(&s.sel.focus, s.page_hint)
}
/// Vertical text: to the next (`next`) or previous line, at the same distance along it. With no
/// such line in the caret's flow (a table cell's only line, the last column), Left/Right step along
/// the text as they did before (`is_left`: backwards).
fn line_step(s: &mut Session, v: &Value, next: bool, is_left: bool) -> CmdResult {
let ext = extend(v);
if !ext && !s.sel.is_collapsed() {
let (a, b) = s.sel.ordered();
s.sel = Selection::caret(if next { b } else { a });
s.goal_x = None;
return sel_result(s);
}
let l = s.layout();
let from = s.sel.focus.clone();
let to = match l.turned_line(&from, s.goal_x, next, s.page_hint) {
Some((p, g)) => {
s.goal_x = Some(g);
p
}
None => return lr_along(s, v, is_left),
};
let gx = s.goal_x;
apply(s, to, ext);
s.goal_x = gx;
sel_result(s)
}
/// Left/Right as a step along the text (`is_left`: backwards).
fn lr_along(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
let ext = extend(v);
if !ext && !s.sel.is_collapsed() {
let (a, b) = s.sel.ordered();
@@ -374,6 +416,10 @@ fn para_down(s: &mut Session, p: &Pos) -> Pos {
}
fn vert(s: &mut Session, v: &Value, dir: i32) -> CmdResult {
if let Some(t) = turn(s) {
// Vertical text (#8986): Up/Down step along the line (top-to-bottom text runs down).
return lr_along(s, v, (dir < 0) == (t == TextDirection::Down));
}
let ext = extend(v);
let l = s.layout();
let from = s.sel.focus.clone();
+57 -34
View File
@@ -335,43 +335,66 @@ mod tests {
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")]
fn rerouting_many_pages_does_not_rescan_all_objects_per_connector() {
use wordcraft_doc::{Document, Paragraph, para_block};
let mut doc = Document::new();
doc.body = (0..8000u32)
.map(|i| {
let mut p = Paragraph::default();
p.props.page_break_before = Some(i > 0);
let id = i * 2 + 1;
for (kind, x, extra) in [
(ShapeKind::Rectangle, 100.0, ShapeExtra { id, ..Default::default() }),
(ShapeKind::Ellipse, 300.0, ShapeExtra { id: id + 1, ..Default::default() }),
(
ShapeKind::ElbowConnector,
0.0,
ShapeExtra { start: Some(ConnEnd { id, site: 3 }), end: Some(ConnEnd { id: id + 1, site: 2 }), ..Default::default() },
),
] {
let float = Float { wrap: Wrap::InFrontOfText, h_rel: Anchor::Page, v_rel: Anchor::Page, x, y: 200.0, ..Default::default() };
p.insert_object(p.len(), shape(kind, extra, float), &Default::default()).unwrap();
}
para_block(p)
})
.collect();
let mut s = Session::new(doc);
s.view.proofing = false;
s.page_hint = 0;
assert_eq!(s.layout().pages.len(), 8000);
let started = std::time::Instant::now();
assert!(reroute(&mut s));
let elapsed = started.elapsed();
eprintln!("8000-page reroute: {elapsed:?}");
assert!(elapsed < std::time::Duration::from_secs(5), "reroute took {elapsed:?}");
for path in s.doc.para_paths(StoryRef::Body) {
let para = s.doc.para(StoryRef::Body, &path).unwrap();
fn glued_pages(n: u32) -> Session {
let mut doc = Document::new();
doc.body = (0..n)
.map(|i| {
let mut p = Paragraph::default();
p.props.page_break_before = Some(i > 0);
let id = i * 2 + 1;
for (kind, x, extra) in [
(ShapeKind::Rectangle, 100.0, ShapeExtra { id, ..Default::default() }),
(ShapeKind::Ellipse, 300.0, ShapeExtra { id: id + 1, ..Default::default() }),
(
ShapeKind::ElbowConnector,
0.0,
ShapeExtra { start: Some(ConnEnd { id, site: 3 }), end: Some(ConnEnd { id: id + 1, site: 2 }), ..Default::default() },
),
] {
let float = Float { wrap: Wrap::InFrontOfText, h_rel: Anchor::Page, v_rel: Anchor::Page, x, y: 200.0, ..Default::default() };
p.insert_object(p.len(), shape(kind, extra, float), &Default::default()).unwrap();
}
para_block(p)
})
.collect();
let mut s = Session::new(doc);
s.view.proofing = false;
s.page_hint = 0;
assert_eq!(s.layout().pages.len(), n as usize);
s
}
// Use the running thread's CPU time on Linux; scheduler pauses are not reroute work.
fn cpu_cost(mut f: impl FnMut()) -> f64 {
let ran = || std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse::<u64>().ok();
let (wall, before) = (std::time::Instant::now(), ran());
f();
match (before, ran()) {
(Some(a), Some(b)) if b > a => (b - a) as f64 * 1e-9,
_ => wall.elapsed().as_secs_f64(),
}
}
const SMALL: u32 = 500;
const SCALE: u32 = 8;
let (mut small_min, mut big_min) = (f64::INFINITY, f64::INFINITY);
let mut last_big = None;
for _ in 0..3 {
let mut small = glued_pages(SMALL);
small_min = small_min.min(cpu_cost(|| assert!(reroute(&mut small))));
let mut big = glued_pages(SMALL * SCALE);
big_min = big_min.min(cpu_cost(|| assert!(reroute(&mut big))));
last_big = Some(big);
}
let ratio = big_min / small_min.max(1e-9);
eprintln!("{SMALL} vs {} pages reroute: {small_min:.4}s vs {big_min:.4}s (ratio {ratio:.2}x)", SMALL * SCALE);
assert!(ratio < SCALE as f64 * 3.0, "reroute scaled superlinearly: {small_min:.4}s -> {big_min:.4}s ({ratio:.2}x for {SCALE}x pages)");
let mut big = last_big.unwrap();
for path in big.doc.para_paths(StoryRef::Body) {
let para = big.doc.para(StoryRef::Body, &path).unwrap();
let InlineObject::Shape { w, h, float, .. } = para.object_at(6).unwrap() else { panic!("connector") };
assert_eq!((*w, *h, float.x, float.y), (160.0, 0.0, 140.0, 210.0));
}
s.touch();
assert!(!reroute(&mut s), "rerouting must settle after refreshing the layout");
big.touch();
assert!(!reroute(&mut big), "rerouting must settle after refreshing the layout");
}
/// The per-case shape/geometry of one scaled-group reroute case.
+4 -5
View File
@@ -827,12 +827,11 @@ fn replace(s: &mut Session, v: &Value) -> CmdResult {
Ok(json!({"replaced": replaced, "remaining": search(s, story)?.len(), "selected": selected}))
}
/// The stories Replace All covers, as in Word: the main text, then headers, footers, footnotes,
/// endnotes and text boxes. Comments keep their words.
/// The stories Replace All covers, as in Word: the main text, then the headers, footers,
/// footnotes, endnotes and text boxes the document shows. Hidden stories (a removed header, a
/// deleted note's text) and comments keep their words.
fn replace_stories(s: &Session) -> Vec<StoryRef> {
use wordcraft_doc::PartKind;
let parts = s.doc.parts.iter().filter(|(_, p)| !matches!(p.kind, PartKind::Comment)).map(|(id, _)| StoryRef::Part(*id));
std::iter::once(StoryRef::Body).chain(parts).collect()
s.doc.shown_stories()
}
/// Every match in every story replaced (wherever the caret is), last first so earlier positions
+12
View File
@@ -668,6 +668,18 @@ fn recipient_lists_in_legacy_and_utf16_encodings() {
assert_eq!(s.merge.rows, [["José"]]);
}
#[test]
fn recipient_list_with_generic_utf32_uses_its_big_endian_bom() {
let mut data = vec![0x00, 0x00, 0xFE, 0xFF];
for c in "Name,City\nAda,A🌍\n".chars() {
data.extend_from_slice(&(c as u32).to_be_bytes());
}
let mut s = Session::new(Document::new());
s.run("mailings.recipients", &json!({"path": "list.csv", "data": b64(&data), "encoding": "utf-32"})).unwrap();
assert_eq!(s.merge.headers, ["Name", "City"]);
assert_eq!(s.merge.rows, [["Ada", "A🌍"]]);
}
/// #778: legacy Excel 97–2003 workbooks are recipient lists; a CSV named .xls reads as text.
#[test]
fn recipients_from_an_xls_workbook() {
+25 -1
View File
@@ -1,4 +1,4 @@
use super::select::{edit_obj, is_shape_or_canvas, obj_size, selected, target_objects, with_obj};
use super::select::{edit_obj, is_shape_or_canvas, obj_size, select_object, selected, target_objects, with_obj};
use super::{CmdError, CmdResult, InlineObject, Pos, Rgb, Session, Value, Wrap, json, p};
use wordcraft_doc::picfx::PicFx;
@@ -186,6 +186,30 @@ pub fn fit_size(w: f32, h: f32, keep: bool) -> (f32, f32) {
(side(w), side(h))
}
/// Runs a one-picture command on each selected picture in turn (several selected with Shift or
/// Ctrl+click, #8832), one undo step. The selection is as it was afterwards.
pub(super) fn each_picture(s: &mut Session, run: impl Fn(&mut Session) -> CmdResult) -> CmdResult {
let picks = target_objects(s, |o| matches!(o, InlineObject::Image { .. }));
if picks.len() < 2 {
return run(s);
}
let (sel, also) = (s.sel.clone(), s.also_selected.clone());
// The failed command's rollback restores the document but not these maps: put them back too.
let (originals, looks) = (s.originals.clone(), s.picture_looks.clone());
let mut out = Ok(Value::Null);
for (pos, _) in &picks {
select_object(s, pos);
s.also_selected.clear();
out = run(s);
if out.is_err() {
(s.originals, s.picture_looks) = (originals, looks);
break;
}
}
(s.sel, s.also_selected) = (sel, also);
out
}
/// Apply an image operation to the selected picture's bitmap (stored as a new PNG).
pub(super) fn adjust(s: &mut Session, f: impl Fn(image::DynamicImage) -> Result<image::DynamicImage, CmdError>) -> CmdResult {
let (_, o) = selected(s).ok_or_else(|| CmdError::Disabled("no picture".into()))?;
+92 -72
View File
@@ -1,6 +1,8 @@
use super::arrange::{MAX_OFFSET, bounds, copy_to, move_with_text, unalign};
use super::group::{add_object, group, ungroup};
use super::picture::{adjust, adjust_media, clear_lum, crop, original_media, recolor, relook, remove_background, reset, shape_size, size};
use super::picture::{
adjust, adjust_media, clear_lum, crop, each_picture, original_media, recolor, relook, remove_background, reset, shape_size, size,
};
use super::select::{
all_objects, alt_text, can_group, edit_obj, has_any_movable, has_any_shape, has_floating, has_group, has_movable, has_object, has_picture,
has_placeable, has_shape, has_shape_or_canvas, has_sizable, is_shape_or_canvas, obj_size, objects_list, selected_or_text_box, target_objects,
@@ -58,98 +60,112 @@ pub fn specs() -> Vec<CommandSpec> {
.params(r#"{"text"?: string, "title"?: string, "decorative"?: bool} (the selected picture, shape, text box, group or chart)"#)
.when(has_object),
CommandSpec::new("picture.corrections", "Corrections", "Picture Format › Adjust", |s, v| {
let b = p::f32(v, "brightness").unwrap_or(0.0).clamp(-100.0, 100.0);
let c = p::f32(v, "contrast").unwrap_or(0.0).clamp(-100.0, 100.0);
let sharpen = p::f32(v, "sharpen").unwrap_or(0.0).clamp(-100.0, 100.0);
// Absolute from the original (like transparency): re-setting all three to 0
// restores the original pixels instead of stacking on the last pass.
// The file's own brightness and contrast (`fx`) are replaced, not stacked on.
let base = original_media(s)?;
adjust_media(s, &base, clear_lum, move |img| {
let mut img = img;
if b != 0.0 {
img = image::DynamicImage::ImageRgba8(image::imageops::colorops::brighten(&img, (b * 2.55) as i32));
}
if c != 0.0 {
img = image::DynamicImage::ImageRgba8(image::imageops::colorops::contrast(&img, c));
}
if sharpen > 0.0 {
img = img.unsharpen(1.0 + sharpen / 50.0, 2);
} else if sharpen < 0.0 && (-sharpen / 25.0).is_normal() {
// `blur` asserts on a subnormal width.
img = img.blur(-sharpen / 25.0);
}
Ok(img)
each_picture(s, |s| {
let b = p::f32(v, "brightness").unwrap_or(0.0).clamp(-100.0, 100.0);
let c = p::f32(v, "contrast").unwrap_or(0.0).clamp(-100.0, 100.0);
let sharpen = p::f32(v, "sharpen").unwrap_or(0.0).clamp(-100.0, 100.0);
// Absolute from the original (like transparency): re-setting all three to 0
// restores the original pixels instead of stacking on the last pass.
// The file's own brightness and contrast (`fx`) are replaced, not stacked on.
let base = original_media(s)?;
adjust_media(s, &base, clear_lum, move |img| {
let mut img = img;
if b != 0.0 {
img = image::DynamicImage::ImageRgba8(image::imageops::colorops::brighten(&img, (b * 2.55) as i32));
}
if c != 0.0 {
img = image::DynamicImage::ImageRgba8(image::imageops::colorops::contrast(&img, c));
}
if sharpen > 0.0 {
img = img.unsharpen(1.0 + sharpen / 50.0, 2);
} else if sharpen < 0.0 && (-sharpen / 25.0).is_normal() {
// `blur` asserts on a subnormal width.
img = img.blur(-sharpen / 25.0);
}
Ok(img)
})
})
})
.params(r#"{"brightness"?: -100..100, "contrast"?: -100..100, "sharpen"?: -100..100}"#)
.when(has_picture),
CommandSpec::new("picture.color", "Color", "Picture Format › Adjust", |s, v| {
let mode = p::str(v, "mode").unwrap_or("grayscale").to_string();
let sat = p::f32(v, "saturation").unwrap_or(100.0);
// Absolute from the original (like transparency): saturation 100 restores it.
// Color and Corrections are independent, as in Word: only Washout, which Word stores
// as brightness and contrast (`a:lum`), replaces the file's own (`fx`).
let base = original_media(s)?;
let fx: fn(&mut PicFx) = if mode == "washout" { clear_lum } else { |_| {} };
adjust_media(s, &base, fx, move |img| Ok(recolor(img, &mode, sat)))
each_picture(s, |s| {
let mode = p::str(v, "mode").unwrap_or("grayscale").to_string();
let sat = p::f32(v, "saturation").unwrap_or(100.0);
// Absolute from the original (like transparency): saturation 100 restores it.
// Color and Corrections are independent, as in Word: only Washout, which Word stores
// as brightness and contrast (`a:lum`), replaces the file's own (`fx`).
let base = original_media(s)?;
let fx: fn(&mut PicFx) = if mode == "washout" { clear_lum } else { |_| {} };
adjust_media(s, &base, fx, move |img| Ok(recolor(img, &mode, sat)))
})
})
.params(r#"{"mode": "grayscale|sepia|washout|blackAndWhite|saturation|tint", "saturation"?: 0..400}"#)
.when(has_picture),
CommandSpec::new("picture.iconColor", "Icon Color", "Picture Format › Adjust", |s, v| {
let c = p::str(v, "color").and_then(Rgb::parse).ok_or_else(|| CmdError::Params("`color` (RRGGBB) is required".into()))?;
// One colour everywhere, transparency kept: recolours an inserted icon or other
// one-colour line art without redrawing it.
adjust(s, move |img| {
let mut rgba = img.to_rgba8();
for px in rgba.pixels_mut() {
px.0 = [c.0, c.1, c.2, px.0[3]];
}
Ok(image::DynamicImage::ImageRgba8(rgba))
each_picture(s, |s| {
let c = p::str(v, "color").and_then(Rgb::parse).ok_or_else(|| CmdError::Params("`color` (RRGGBB) is required".into()))?;
// One colour everywhere, transparency kept: recolours an inserted icon or other
// one-colour line art without redrawing it.
adjust(s, move |img| {
let mut rgba = img.to_rgba8();
for px in rgba.pixels_mut() {
px.0 = [c.0, c.1, c.2, px.0[3]];
}
Ok(image::DynamicImage::ImageRgba8(rgba))
})
})
})
.params(r#"{"color": "RRGGBB"}"#)
.when(has_picture),
CommandSpec::new("picture.effects", "Artistic Effects", "Picture Format › Adjust", |s, v| {
// One effect at a time, as in Word: a second one replaces the first (#2052).
let e = p::str(v, "effect").unwrap_or("blur").to_string();
relook(s, move |l| l.effect = (e != "none").then_some(e))
each_picture(s, |s| {
// One effect at a time, as in Word: a second one replaces the first (#2052).
let e = p::str(v, "effect").unwrap_or("blur").to_string();
relook(s, move |l| l.effect = (e != "none").then_some(e))
})
})
.params(r#"{"effect": "blur|sharpen|invert|posterize|pixelate|none"} (replaces the picture's effect)"#)
.when(has_picture),
CommandSpec::new("picture.transparency", "Transparency", "Picture Format › Adjust", |s, v| {
let t = p::f32(v, "percent").unwrap_or(50.0).clamp(0.0, 100.0);
// Absolute, not compounding: 0% is always the original pixels fully opaque.
// The base is the pre-edit original (kept for Reset Picture), so dragging a
// slider back and forth never fades what a previous pass already faded.
// (Combining with other pixel edits then re-setting transparency drops those
// edits; a full live-effect stack is future work.)
// The file's own transparency (`fx`, `a:alphaModFix`) is replaced too: it's baked
// into the pixels from here on.
let base = original_media(s)?;
adjust_media(s, &base, |fx: &mut PicFx| fx.transparency = 0, move |img| {
let mut rgba = img.to_rgba8();
for px in rgba.pixels_mut() {
px.0[3] = (px.0[3] as f32 * (1.0 - t / 100.0)) as u8;
}
Ok(image::DynamicImage::ImageRgba8(rgba))
each_picture(s, |s| {
let t = p::f32(v, "percent").unwrap_or(50.0).clamp(0.0, 100.0);
// Absolute, not compounding: 0% is always the original pixels fully opaque.
// The base is the pre-edit original (kept for Reset Picture), so dragging a
// slider back and forth never fades what a previous pass already faded.
// (Combining with other pixel edits then re-setting transparency drops those
// edits; a full live-effect stack is future work.)
// The file's own transparency (`fx`, `a:alphaModFix`) is replaced too: it's baked
// into the pixels from here on.
let base = original_media(s)?;
adjust_media(s, &base, |fx: &mut PicFx| fx.transparency = 0, move |img| {
let mut rgba = img.to_rgba8();
for px in rgba.pixels_mut() {
px.0[3] = (px.0[3] as f32 * (1.0 - t / 100.0)) as u8;
}
Ok(image::DynamicImage::ImageRgba8(rgba))
})
})
})
.params(r#"{"percent": 0..100}"#)
.when(has_picture),
CommandSpec::new("picture.removeBackground", "Remove Background", "Picture Format › Adjust", |s, v| {
let tol = p::f32(v, "tolerance").unwrap_or(30.0).clamp(0.0, 255.0);
adjust(s, move |img| Ok(remove_background(img, tol)))
each_picture(s, |s| {
let tol = p::f32(v, "tolerance").unwrap_or(30.0).clamp(0.0, 255.0);
adjust(s, move |img| Ok(remove_background(img, tol)))
})
})
.params(r#"{"tolerance"?: 0..255}"#)
.when(has_picture),
CommandSpec::new("picture.compress", "Compress Pictures", "Picture Format › Adjust", |s, v| {
let max = p::u64(v, "maxPixels").unwrap_or(1600).clamp(32, 20000) as u32;
adjust(s, move |img| Ok(if img.width().max(img.height()) > max { img.resize(max, max, image::imageops::FilterType::Lanczos3) } else { img }))
each_picture(s, |s| {
let max = p::u64(v, "maxPixels").unwrap_or(1600).clamp(32, 20000) as u32;
adjust(s, move |img| Ok(if img.width().max(img.height()) > max { img.resize(max, max, image::imageops::FilterType::Lanczos3) } else { img }))
})
})
.params(r#"{"maxPixels"?: n}"#)
.when(has_picture),
CommandSpec::new("picture.reset", "Reset Picture", "Picture Format › Adjust", reset).when(has_picture),
CommandSpec::new("picture.reset", "Reset Picture", "Picture Format › Adjust", |s, v| each_picture(s, |s| reset(s, v))).when(has_picture),
CommandSpec::new("picture.change", "Change Picture", "Picture Format › Adjust", |s, v| {
let bytes = if let Some(d) = p::str(v, "data") {
crate::cmd::insert::base64_decode(d).ok_or_else(|| CmdError::Params("bad base64".into()))?
@@ -184,20 +200,24 @@ pub fn specs() -> Vec<CommandSpec> {
.params(r#"{"path"?: string, "data"?: base64}"#)
.when(has_picture),
CommandSpec::new("picture.style", "Picture Styles", "Picture Format › Picture Styles", |s, v| {
// A style replaces the picture's style and border, as Word's gallery does (#2052).
let style = p::str(v, "style").unwrap_or("simpleFrame").to_string();
relook(s, move |l| {
l.style = Some(style);
l.border = None;
each_picture(s, |s| {
// A style replaces the picture's style and border, as Word's gallery does (#2052).
let style = p::str(v, "style").unwrap_or("simpleFrame").to_string();
relook(s, move |l| {
l.style = Some(style);
l.border = None;
})
})
})
.params(r#"{"style": "simpleFrame|thickFrame|rounded|softEdge|shadow"} (replaces the picture's style and border)"#)
.when(has_picture),
CommandSpec::new("picture.border", "Picture Border", "Picture Format › Picture Styles", |s, v| {
let c = p::str(v, "color").and_then(Rgb::parse).unwrap_or(Rgb::BLACK);
let w = p::u64(v, "width").unwrap_or(4).clamp(1, 200) as u32;
// Replaces the picture's border, keeping its style (#2052).
relook(s, move |l| l.border = Some((c, w)))
each_picture(s, |s| {
let c = p::str(v, "color").and_then(Rgb::parse).unwrap_or(Rgb::BLACK);
let w = p::u64(v, "width").unwrap_or(4).clamp(1, 200) as u32;
// Replaces the picture's border, keeping its style (#2052).
relook(s, move |l| l.border = Some((c, w)))
})
})
.params(r#"{"color"?: "RRGGBB", "width"?: px} (replaces the picture's border)"#)
.when(has_picture),
+22
View File
@@ -432,6 +432,28 @@ fn two_inserted_pictures_in_a_row_are_both_kept() {
assert_eq!(s.run("arrange.selectionPane", &json!({})).unwrap().as_array().map(Vec::len), Some(2));
}
/// #8832: a picture command on several selected pictures changes each, in one undo step.
#[test]
fn picture_border_applies_to_every_selected_picture() {
let data = super::super::insert::base64_encode(&png(20, 10));
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("insert.picture", &json!({"data": data})).unwrap();
s.run("insert.picture", &json!({"data": data})).unwrap();
s.run("select.addObject", &json!({"index": 0})).unwrap();
s.run("select.addObject", &json!({"index": 1})).unwrap();
let media = |s: &Session| {
all_objects(s)
.into_iter()
.map(|(_, o)| matches!(o, InlineObject::Image { media, .. } if s.picture_looks.get(&media).is_some_and(|l| l.border.is_some())))
.collect::<Vec<_>>()
};
assert_eq!(media(&s), [false, false]);
s.run("picture.border", &json!({"width": 3})).unwrap();
assert_eq!(media(&s), [true, true]);
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(media(&s), [false, false]);
}
/// #2019: Insert › Shapes adds each new shape beside the selected one, as Word draws it, so
/// shapes inserted in a row are all kept (the second used to replace the first, which stays
/// selected after its insert). Selected text stays too, and the new shape is selected.
+2 -2
View File
@@ -97,8 +97,8 @@ mod tests {
use super::*;
use crate::packs::{Backend, FixedBackend};
/// Tests that set the process-wide backend take turns.
static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
/// Tests that set the process-wide backend or packs directory share the dictionary test lock.
use crate::custom_dict::DICT_TEST_LOCK as LOCK;
/// Puts the process back to no backend and no background thread when dropped, even when
/// the test panicked.
+4 -3
View File
@@ -37,10 +37,11 @@ fn read_only_with_an_exception_allows_edits_only_inside_it() {
/// the replacement in the editable region still goes through.
#[test]
fn replace_all_in_a_protected_document_skips_protected_matches() {
use wordcraft_doc::{CharProps, Paragraph, PartKind, para_block};
let mut s = Session::new(Document::from_text("Locked [NAME].\nFill [NAME] in."));
let header = s.doc.add_part(PartKind::Header, vec![para_block(Paragraph::with_text("Header [NAME]", CharProps::default()))]);
let note = s.doc.add_part(PartKind::Footnote, vec![para_block(Paragraph::with_text(" Note [NAME]", CharProps::default()))]);
let header = s.run("insert.header", &json!({"text": "Header [NAME]"})).unwrap()["story"].as_u64().unwrap() as u32;
s.run("caret.docStart", &json!({})).unwrap();
let note = s.run("references.footnote", &json!({"text": "Note [NAME]"})).unwrap()["id"].as_u64().unwrap() as u32;
s.sel = Selection::caret(Pos::body(0, 0));
select(&mut s, "Fill [NAME] in.");
s.run("review.restrict", &json!({"exception": "add"})).unwrap();
s.run("review.restrict", &json!({"mode": "readOnly"})).unwrap();
+6 -1
View File
@@ -273,7 +273,7 @@ pub fn save_custom_dictionary(path: &Path, removed: &[String]) -> Result<(), Str
}
#[cfg(test)]
pub(crate) use tests::{DICT_TEST_LOCK, TestDir};
pub(crate) use tests::{DICT_TEST_LOCK, TestDir, dict_test_lock};
#[cfg(test)]
mod tests {
@@ -282,6 +282,11 @@ mod tests {
/// Test lock serializing tests that access the global proofing dictionary.
pub(crate) static DICT_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
/// Acquire [`DICT_TEST_LOCK`], recovering cleanly if an earlier test panicked while holding it.
pub(crate) fn dict_test_lock() -> std::sync::MutexGuard<'static, ()> {
DICT_TEST_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
/// RAII guard for temporary directories in dictionary tests.
pub(crate) struct TestDir(pub(crate) std::path::PathBuf);
+1
View File
@@ -300,6 +300,7 @@ mod tests {
#[test]
fn layout_drops_stale_revision_slot_but_keeps_same_revision_mode() {
let _dict_guard = crate::custom_dict::dict_test_lock();
let mut session = Session::new(Document::new());
let first = session.layout();
let first_weak = Arc::downgrade(&first);
+10
View File
@@ -465,6 +465,16 @@ impl Session {
| "shape.size"
| "shape.rotation"
| "picture.size"
| "picture.reset"
| "picture.corrections"
| "picture.color"
| "picture.iconColor"
| "picture.effects"
| "picture.transparency"
| "picture.removeBackground"
| "picture.compress"
| "picture.style"
| "picture.border"
| "arrange.rotate"
| "arrange.rotation"
| "shape.alignText"
+81 -42
View File
@@ -11890,19 +11890,17 @@ fn next_footnote_skips_endnotes() {
assert_eq!(s.sel.focus.off, 9);
}
/// Tests that install a test dictionary wait for the dictionaries-folder test, which changes the
/// folder and then reads what each language reports: an install in between reports no file.
static DICTIONARIES: std::sync::Mutex<()> = std::sync::Mutex::new(());
/// Tests that read or mutate process-wide proofing dictionaries take turns through `DICT_TEST_LOCK`.
fn dictionaries_turn() -> std::sync::MutexGuard<'static, ()> {
DICTIONARIES.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
crate::custom_dict::dict_test_lock()
}
/// A tiny synthetic Polish Hunspell dictionary (written for these tests). Real dictionaries are
/// installed on the system, never bundled; every Polish test installs this same one.
fn polish_test_dictionary() {
let _turn = dictionaries_turn();
fn polish_test_dictionary() -> std::sync::MutexGuard<'static, ()> {
let turn = dictionaries_turn();
wordcraft_proof::pl::install_dictionary(POLISH_TEST_AFF, POLISH_TEST_DIC).unwrap();
turn
}
const POLISH_TEST_AFF: &str = "SET UTF-8\nTRY aioeznrwcyszżtkpdmłjlubąęgh\nMAP 2\nMAP oó\nMAP zż\nREP 2\nREP ż rz\nREP rz ż\n";
@@ -11910,9 +11908,10 @@ const POLISH_TEST_DIC: &str = "12\npłynie\nrzeka\na\nto\nwiem\nże\ntak\nw\nog
/// A tiny synthetic Portuguese Hunspell dictionary (written for these tests). Real dictionaries
/// are installed on the system, never bundled; every Portuguese test installs this same one.
fn portuguese_test_dictionary() {
let _turn = dictionaries_turn();
fn portuguese_test_dictionary() -> std::sync::MutexGuard<'static, ()> {
let turn = dictionaries_turn();
wordcraft_proof::pt::install_dictionary(PORTUGUESE_TEST_AFF, PORTUGUESE_TEST_DIC).unwrap();
turn
}
const PORTUGUESE_TEST_AFF: &str =
@@ -11987,7 +11986,7 @@ fn dictionaries_folder_option_is_saved_searched_and_reported() {
/// grammar, suggestions come from it, and a suggestion fixes the text.
#[test]
fn portuguese_proofing_through_the_review_commands() {
portuguese_test_dictionary();
let _turn = portuguese_test_dictionary();
let mut s = s();
run(&mut s, "document.setText", json!({"text": "Saudade coraçao, e ele ele disse."}));
// English by default: the Portuguese words are English misspellings.
@@ -12018,9 +12017,10 @@ fn portuguese_proofing_through_the_review_commands() {
assert_eq!(left.as_array().unwrap().len(), 1, "{left}");
}
fn indonesian_test_dictionary() {
let _turn = dictionaries_turn();
fn indonesian_test_dictionary() -> std::sync::MutexGuard<'static, ()> {
let turn = dictionaries_turn();
wordcraft_proof::id::install_dictionary(INDONESIAN_TEST_AFF, INDONESIAN_TEST_DIC).unwrap();
turn
}
// Hand-written synthetic fixture (no system dictionary data).
@@ -12031,7 +12031,7 @@ const INDONESIAN_TEST_DIC: &str = "8\nrumah\nsekolah\nanak\nbermain\ndi\nmakan/A
/// Dictionary.
#[test]
fn indonesian_proofing_through_the_review_commands() {
indonesian_test_dictionary();
let _turn = indonesian_test_dictionary();
let mut s = s();
run(&mut s, "document.setText", json!({"text": "Saya di sekolha, anak anak bermain."}));
run(&mut s, "select.all", json!({}));
@@ -12086,6 +12086,7 @@ fn english_dialects_through_the_review_commands() {
if no_language_data("english_dialects_through_the_review_commands") {
return;
}
let _turn = dictionaries_turn();
let mut s = s();
run(&mut s, "document.setText", json!({"text": "The colour of the center."}));
// US English by default: the British spelling is flagged, the American one isn't.
@@ -12193,19 +12194,20 @@ const SPANISH_TEST_AFF: &str =
const SPANISH_TEST_DIC: &str = "10\nesto\nes\nuna\nprueba/S\ndel\ncorrector\ntambién\nhabéis\nvenido\ndecir\n";
const URUGUAYAN_TEST_DIC: &str = "10\nesto\nes\nuna\nprueba/S\ndel\ncorrector\ntambién\ntener\nvenir\ndecir\n";
fn spanish_test_dictionaries() {
fn spanish_test_dictionaries() -> std::sync::MutexGuard<'static, ()> {
use wordcraft_proof::ProofLang;
let _turn = dictionaries_turn();
let turn = dictionaries_turn();
for (lang, dic) in [(ProofLang::Es, SPANISH_TEST_DIC), (ProofLang::EsUy, URUGUAYAN_TEST_DIC)] {
wordcraft_proof::es::install_dictionary(lang, SPANISH_TEST_AFF, dic).unwrap();
}
turn
}
/// #3553: Spanish proofing through the same commands as Review, F7, Change and Add to
/// Dictionary: `prueva` and `corector` are flagged with `prueba` and `corrector` offered.
#[test]
fn spanish_proofing_through_the_review_commands() {
spanish_test_dictionaries();
let _turn = spanish_test_dictionaries();
let mut s = s();
run(&mut s, "document.setText", json!({"text": "esto es una prueva del corector. Habéis venido?"}));
run(&mut s, "select.all", json!({}));
@@ -12236,7 +12238,7 @@ fn spanish_proofing_through_the_review_commands() {
/// bytes.
#[test]
fn add_and_ignore_all_accept_both_normalization_forms() {
spanish_test_dictionaries();
let _turn = spanish_test_dictionaries();
let mut s = s();
let text = "esto zqanade\u{301}do y zqignora\u{301}do";
run(&mut s, "document.setText", json!({"text": text}));
@@ -12265,7 +12267,7 @@ fn add_and_ignore_all_accept_both_normalization_forms() {
/// Uruguayan Spanish accepts the `vos` forms, imperatives included, that Spain's flags.
#[test]
fn uruguayan_spanish_accepts_vos_forms() {
spanish_test_dictionaries();
let _turn = spanish_test_dictionaries();
let mut s = s();
run(&mut s, "document.setText", json!({"text": "Vení, decime qué tenés."}));
run(&mut s, "select.all", json!({}));
@@ -12284,7 +12286,7 @@ fn uruguayan_spanish_accepts_vos_forms() {
/// Czech proofing through the same commands as Review, F7, Change and Add to Dictionary.
#[test]
fn czech_proofing_through_the_review_commands() {
czech_test_dict::install();
let _turn = czech_test_dict::install();
let mut s = s();
run(&mut s, "document.setText", json!({"text": "Město pocitac, škola škola."}));
assert!(run(&mut s, "review.issues", json!({})).as_array().unwrap().len() >= 3);
@@ -12323,9 +12325,10 @@ fn czech_proofing_through_the_review_commands() {
const ITALIAN_TEST_AFF: &str = "SET UTF-8\nTRY aeiortnsclcaffèéè\nMAP 2\nMAP aà\nMAP eéè\nREP 1\nREP caffe caffè\n";
const ITALIAN_TEST_DIC: &str = "6\ncasa\ncaffè\nroma\ndisse\ne\nper\n";
fn italian_test_dictionary() {
let _turn = dictionaries_turn();
fn italian_test_dictionary() -> std::sync::MutexGuard<'static, ()> {
let turn = dictionaries_turn();
wordcraft_proof::it::install_dictionary(ITALIAN_TEST_AFF, ITALIAN_TEST_DIC).unwrap();
turn
}
/// Review › Language and the proofing commands work in Italian end to end: the language makes
@@ -12333,7 +12336,7 @@ fn italian_test_dictionary() {
/// suggestions come from it, and a suggestion fixes the text.
#[test]
fn italian_proofing_through_the_review_commands() {
italian_test_dictionary();
let _turn = italian_test_dictionary();
let mut s = s();
run(&mut s, "document.setText", json!({"text": "Casa caffe, e roma roma disse."}));
// English by default: the Italian words are English misspellings.
@@ -12366,7 +12369,7 @@ fn italian_proofing_through_the_review_commands() {
#[test]
fn polish_proofing_through_the_review_commands() {
polish_test_dictionary();
let _turn = polish_test_dictionary();
let mut s = s();
run(&mut s, "document.setText", json!({"text": "Płynie żeka, a wogóle to wiem że tak."}));
// English by default: the Polish words are English misspellings.
@@ -12406,6 +12409,7 @@ fn turkish_proofing_through_the_review_commands() {
if !crate::proof::tr::has_dictionary() {
return;
}
let _turn = dictionaries_turn();
let mut s = s();
run(&mut s, "document.setText", json!({"text": "Bana bazen gelenler oldu ise de. Sana olacaklardan sonra sorna"}));
run(&mut s, "select.all", json!({}));
@@ -12433,7 +12437,7 @@ fn turkish_proofing_through_the_review_commands() {
/// no parameters keep the old meaning (US English), and `default` needs a language.
#[test]
fn review_language_validates_tags_and_marks_text_unchecked() {
polish_test_dictionary();
let _turn = polish_test_dictionary();
let mut s = s();
run(&mut s, "document.setText", json!({"text": "Hello wrold"}));
run(&mut s, "select.all", json!({}));
@@ -12461,7 +12465,7 @@ fn review_language_validates_tags_and_marks_text_unchecked() {
/// the caret, not the document's default, so what is typed in them is proofed in that language.
#[test]
fn a_new_table_is_in_the_language_at_the_caret() {
polish_test_dictionary();
let _turn = polish_test_dictionary();
let cell_langs = |s: &Session| -> Vec<Option<String>> {
let t = s.doc.body.iter().find_map(|b| b.as_table()).unwrap();
t.rows.iter().flat_map(|r| &r.cells).flat_map(|c| &c.blocks).filter_map(|b| b.as_para()).map(|p| p.mark.lang.clone()).collect()
@@ -12505,7 +12509,7 @@ fn a_new_table_is_in_the_language_at_the_caret() {
/// a document with changes never does, and templates stay English.
#[test]
fn new_documents_follow_the_editing_language() {
polish_test_dictionary();
let _turn = polish_test_dictionary();
let mut s = s();
s.set_editing_language(Some("pl-PL"));
assert_eq!(s.doc.styles.default_chr.lang.as_deref(), Some("pl-PL"), "the untouched blank document switches");
@@ -12611,7 +12615,7 @@ fn rejected_default_proofing_language_does_not_survive_a_restart() {
/// English run (`w:lang`) come back, and so does the proofing.
#[test]
fn proofing_languages_survive_a_docx_round_trip() {
polish_test_dictionary();
let _turn = polish_test_dictionary();
let mut s = s();
run(&mut s, "document.setText", json!({"text": "Płynie żeka. Hello wrold."}));
run(&mut s, "select.all", json!({}));
@@ -15856,7 +15860,7 @@ fn page_down_and_up_never_stay_on_a_line_in_the_continuous_views() {
for view in ["view.draft", "view.outline", "view.webLayout"] {
let mut s = s();
run(&mut s, "layout.margins", json!({"top": 370, "bottom": 370}));
let long = "Lorem ipsum dolor sit amet ".repeat(4);
let long = "Lorem ipsum dolor sit amet ".repeat(2);
run(&mut s, "text.insert", json!({"text": long}));
run(&mut s, "text.newParagraph", json!({}));
run(&mut s, "para.indents", json!({"right": 700}));
@@ -15930,34 +15934,35 @@ fn replace_all_replaces_in_every_story() {
run(&mut t, "document.setText", json!({"text": "Body: [NAME] and [NAME]."}));
// A text box the body shows (one nothing shows is pruned with the next command).
let boxed = run(&mut t, "insert.textBox", json!({"text": "Text box: [NAME]"}))["story"].as_u64().unwrap() as u32;
let mut add = |kind, text: &str| t.doc.add_part(kind, vec![para_block(Paragraph::with_text(text, CharProps::default()))]);
let ids = [
add(PartKind::Header, "Header: [NAME]"),
add(PartKind::Footer, "Footer: [NAME]"),
add(PartKind::Footnote, " Footnote: [NAME]"),
add(PartKind::Endnote, " Endnote: [NAME]"),
boxed,
add(PartKind::Comment, "Comment: [NAME]"),
];
run(&mut t, "caret.docStart", json!({}));
let header = run(&mut t, "insert.header", json!({"text": "Header: [NAME]"}))["story"].as_u64().unwrap() as u32;
let footer = run(&mut t, "insert.footer", json!({"text": "Footer: [NAME]"}))["story"].as_u64().unwrap() as u32;
run(&mut t, "caret.docStart", json!({}));
let footnote = run(&mut t, "references.footnote", json!({"text": "Footnote: [NAME]"}))["id"].as_u64().unwrap() as u32;
run(&mut t, "caret.docStart", json!({}));
let endnote = run(&mut t, "references.endnote", json!({"text": "Endnote: [NAME]"}))["id"].as_u64().unwrap() as u32;
run(&mut t, "caret.docStart", json!({}));
let comment = t.doc.add_part(PartKind::Comment, vec![para_block(Paragraph::with_text("Comment: [NAME]", CharProps::default()))]);
let ids = [header, footer, footnote, endnote, boxed, comment];
(t, ids)
};
let (mut t, ids) = build();
let r = run(&mut t, "edit.replaceAll", json!({"text": "[NAME]", "with": "Jane"}));
assert_eq!(r["replaced"], 7, "{r}");
assert_eq!(story_text(&t, StoryRef::Body), "Body: Jane and Jane.");
let texts: Vec<String> = ids.iter().map(|id| story_text(&t, StoryRef::Part(*id))).collect();
assert_eq!(story_text(&t, StoryRef::Body).replace(wordcraft_doc::para::OBJ, ""), "Body: Jane and Jane.");
let texts: Vec<String> = ids.iter().map(|id| story_text(&t, StoryRef::Part(*id)).replace(wordcraft_doc::para::OBJ, "")).collect();
assert_eq!(texts, ["Header: Jane", "Footer: Jane", " Footnote: Jane", " Endnote: Jane", "Text box: Jane", "Comment: [NAME]"]);
// One undo step brings every story back.
run(&mut t, "edit.undo", json!({}));
assert_eq!(story_text(&t, StoryRef::Body), "Body: [NAME] and [NAME].");
assert_eq!(story_text(&t, StoryRef::Body).replace(wordcraft_doc::para::OBJ, ""), "Body: [NAME] and [NAME].");
assert_eq!(story_text(&t, StoryRef::Part(ids[0])), "Header: [NAME]");
assert_eq!(story_text(&t, StoryRef::Part(ids[2])), " Footnote: [NAME]");
assert_eq!(story_text(&t, StoryRef::Part(ids[2])).replace(wordcraft_doc::para::OBJ, ""), " Footnote: [NAME]");
// From the caret in a footnote the body is replaced too.
let (mut t, ids) = build();
t.sel = crate::session::Selection::caret(wordcraft_doc::Pos::new(StoryRef::Part(ids[2]), wordcraft_doc::Path::top(0), 0));
let r = run(&mut t, "edit.replaceAll", json!({"text": "[NAME]", "with": "Jane"}));
assert_eq!(r["replaced"], 7, "{r}");
assert_eq!(story_text(&t, StoryRef::Body), "Body: Jane and Jane.");
assert_eq!(story_text(&t, StoryRef::Body).replace(wordcraft_doc::para::OBJ, ""), "Body: Jane and Jane.");
// Under Track Changes the replacements are revisions in every story, and nothing breaks.
let (mut t, ids) = build();
run(&mut t, "review.trackChanges", json!({"enabled": true}));
@@ -15966,6 +15971,40 @@ fn replace_all_replaces_in_every_story() {
assert!(story_text(&t, StoryRef::Part(ids[0])).contains("Jane"));
}
/// #9064: Replace All skips stories nothing shows any more (a removed header, a footnote whose
/// reference was deleted without tracking) and does not count them.
#[test]
fn replace_all_skips_removed_header_and_deleted_footnote_stories() {
use wordcraft_doc::StoryRef;
let mut t = s();
run(&mut t, "document.setText", json!({"text": "Body."}));
let header = run(&mut t, "insert.header", json!({"text": "Header [NAME]"}))["story"].as_u64().unwrap() as u32;
run(&mut t, "insert.removeHeader", json!({}));
run(&mut t, "caret.docStart", json!({}));
let footnote = run(&mut t, "references.footnote", json!({"text": "Footnote [NAME]"}))["id"].as_u64().unwrap() as u32;
// Delete the footnote reference from the body without Track Changes, leaving the part behind.
t.doc.delete_range(&Pos::body(0, 0), &Pos::body(0, 1)).unwrap();
t.sel = crate::session::Selection::caret(Pos::body(0, 0));
let r = run(&mut t, "edit.replaceAll", json!({"text": "[NAME]", "with": "Jane"}));
assert_eq!(r["replaced"], 0, "{r}");
assert_eq!(t.status, "All done. We made 0 replacements.");
for id in [header, footnote] {
let first = Pos::new(StoryRef::Part(id), wordcraft_doc::Path::top(0), 0);
assert!(t.doc.para_at(&first).unwrap().text.contains("[NAME]"));
}
// A match in a shown story still replaces, without touching or counting the hidden ones.
run(&mut t, "document.setText", json!({"text": "Body [NAME]."}));
let r = run(&mut t, "edit.replaceAll", json!({"text": "[NAME]", "with": "Jane"}));
assert_eq!(r["replaced"], 1, "{r}");
assert_eq!(t.doc.plain_text(StoryRef::Body), "Body Jane.");
for id in [header, footnote] {
let first = Pos::new(StoryRef::Part(id), wordcraft_doc::Path::top(0), 0);
assert!(t.doc.para_at(&first).unwrap().text.contains("[NAME]"));
}
}
#[test]
fn page_down_and_up_reach_the_ends_on_first_and_last_page() {
let mut s = s();
+3 -1
View File
@@ -54,6 +54,8 @@ to
zqzakázané/F
";
pub fn install() {
pub fn install() -> std::sync::MutexGuard<'static, ()> {
let turn = super::dictionaries_turn();
super::install_dictionary(AFF, DIC).unwrap();
turn
}
+62
View File
@@ -195,6 +195,68 @@ fn enter_on_an_empty_nested_item_moves_it_up_a_level_first() {
assert_eq!(paras(&s), vec![para("A", Some(0)), para("B", Some(1)), para("text", None)]);
}
#[test]
fn enter_outdents_an_empty_list_item_and_drops_direct_indents() {
use wordcraft_doc::props::{NumRef, ParaProps};
use wordcraft_doc::styles::Style;
let fixture = typed("* One\n\tTwo\n");
let at = fixture.sel.focus.clone();
let item = fixture.doc.para_at(&at).unwrap();
assert!(item.is_empty());
let nested = item.props.numbering.unwrap();
assert_eq!(nested.level, 1);
let promoted = NumRef { level: 0, ..nested };
let mut doc = fixture.doc.clone();
Arc::make_mut(&mut doc.styles).upsert(Style {
id: "NestedFixture".into(),
name: "Nested Fixture".into(),
para: ParaProps { numbering: Some(nested), ..Default::default() },
..Default::default()
});
let caret_x = |s: &mut Session| s.layout().caret(&at).expect("the empty list item's caret").x;
for inherited in [false, true] {
let mut doc = doc.clone();
let props = &mut doc.para_mut(at.story, &at.path).unwrap().props;
props.style = Some("NestedFixture".into());
props.numbering = (!inherited).then_some(nested);
props.indent_right = Some(12.0);
props.space_after = Some(9.0);
let mut expected = props.clone();
expected.numbering = Some(promoted);
let mut control = Session::new(doc.clone());
control.sel = crate::Selection::caret(at.clone());
typ(&mut control, "\n");
assert_eq!(control.doc.para_at(&at).unwrap().props, expected);
let promoted_x = caret_x(&mut control);
for chars in [false, true] {
let mut s = Session::new(doc.clone());
s.sel = crate::Selection::caret(at.clone());
let props = &mut s.doc.para_mut(at.story, &at.path).unwrap().props;
if chars {
props.indent_left_chars = Some(8.0);
props.indent_first_chars = Some(-2.0);
} else {
props.indent_left = Some(144.0);
props.indent_first = Some(-18.0);
}
let before = props.clone();
let depth = s.undo_depth();
typ(&mut s, "\n");
assert_eq!(s.doc.para_at(&at).unwrap().props, expected, "inherited={inherited}, chars={chars}");
assert_eq!(caret_x(&mut s), promoted_x, "indent matches the new level without an override");
assert_eq!(s.sel.focus, at);
assert_eq!(s.undo_depth(), depth + 1);
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.doc.para_at(&at).unwrap().props, before, "Undo restores both numbering and indentation");
}
}
}
/// #2143: in a Word file whose list comes from the paragraph styles (List Number, List Number 2
/// with `w:numPr` in styles.xml, none on the paragraphs), Enter on an empty nested item moves it
/// up a level and then ends the list, as with direct numbering.
+135 -12
View File
@@ -13,14 +13,56 @@ use crate::model::{FBlock, ListCounter, from_doc};
#[cfg(test)]
mod legacy_oracle_tests;
const UTF32_LE_BOM: &[u8] = &[0xFF, 0xFE, 0x00, 0x00];
const UTF32_BE_BOM: &[u8] = &[0x00, 0x00, 0xFE, 0xFF];
fn utf32(b: &[u8], le: bool) -> String {
let units: Vec<char> = b
.as_chunks::<4>()
.0
.iter()
.map(|c| {
let u = if le { u32::from_le_bytes(*c) } else { u32::from_be_bytes(*c) };
char::from_u32(u).unwrap_or('\u{FFFD}')
})
.collect();
units.into_iter().collect()
}
fn decode_utf32_bom(b: &[u8]) -> Option<String> {
if let Some(rest) = b.strip_prefix(UTF32_LE_BOM) {
return Some(utf32(rest, true));
}
b.strip_prefix(UTF32_BE_BOM).map(|rest| utf32(rest, false))
}
// Detection is shared with the other Craft apps. WordCraft's `cp1252` and encoding_rs agree on
// every byte (pinned by `legacy_oracle_tests`), so a Windows-1252 guess needs no local mapping.
pub use craft_mime::detect::{decode, is_text, legacy};
pub use craft_mime::detect::legacy;
/// Does `b` look like plain text ([`craft_mime::detect::is_text`])? A UTF-32 BOM counts as text.
pub fn is_text(b: &[u8]) -> bool {
b.starts_with(UTF32_LE_BOM) || b.starts_with(UTF32_BE_BOM) || craft_mime::detect::is_text(b)
}
/// Decode text bytes: a UTF-32 BOM first, then [`craft_mime::detect::decode`] (other BOMs, UTF-16
/// without BOM, UTF-8, the legacy encoding the bytes look like).
pub fn decode(b: &[u8]) -> String {
decode_utf32_bom(b).unwrap_or_else(|| craft_mime::detect::decode(b))
}
/// Decode bytes in a named encoding (a WHATWG label such as `gbk`, `gb18030`, `big5`,
/// `shift_jis`, `euc-kr`, `utf-16le`, `windows-1251`); `None` when the label isn't known.
/// The generic `utf-32` label honors either BOM and defaults to little-endian without one.
pub fn decode_as(b: &[u8], label: &str) -> Option<String> {
let enc = encoding_rs::Encoding::for_label(label.trim().as_bytes())?;
let clean = label.trim().to_ascii_lowercase();
match clean.as_str() {
"utf-32" => return Some(decode_utf32_bom(b).unwrap_or_else(|| utf32(b, true))),
"utf-32le" => return Some(utf32(b.strip_prefix(UTF32_LE_BOM).unwrap_or(b), true)),
"utf-32be" => return Some(utf32(b.strip_prefix(UTF32_BE_BOM).unwrap_or(b), false)),
_ => {}
}
let enc = encoding_rs::Encoding::for_label(clean.as_bytes())?;
Some(enc.decode(b).0.into_owned())
}
@@ -28,7 +70,7 @@ pub fn decode_as(b: &[u8], label: &str) -> Option<String> {
pub fn import(bytes: &[u8]) -> Document {
let text = decode(bytes);
let text = text.replace("\r\n", "\n").replace('\r', "\n");
let clean: String = text.chars().filter(|c| !c.is_control() || matches!(c, '\n' | '\t' | '\u{000C}')).collect();
let clean: String = text.chars().filter(|c| !c.is_control() || matches!(c, '\n' | '\t' | '\u{000B}' | '\u{000C}' | '\u{000E}')).collect();
Document::from_text(&clean)
}
@@ -57,18 +99,23 @@ fn blocks_text(blocks: &[FBlock], out: &mut Vec<String>, lists: &mut ListCounter
}
FBlock::Table(t) => {
lists.reset();
let cols = t.cols();
for row in &t.rows {
let cells: Vec<String> = row
.iter()
.map(|c| {
if depth > 8 {
return String::new();
}
let mut cells: Vec<String> = Vec::new();
for c in row {
if c.covered || depth > 8 {
cells.push(String::new());
} else {
let mut v = Vec::new();
blocks_text(&c.blocks, &mut v, &mut ListCounter::default(), depth + 1);
v.join(" ")
})
.collect();
let text = v.join(" ").split_whitespace().collect::<Vec<_>>().join(" ");
cells.push(text);
}
for _ in 1..c.colspan.clamp(1, 63) {
cells.push(String::new());
}
}
cells.resize(cols, String::new());
out.push(cells.join("\t"));
}
}
@@ -86,3 +133,79 @@ pub fn export(doc: &Document) -> Vec<u8> {
blocks_text(&flow.blocks, &mut lines, &mut ListCounter::default(), 0);
lines.join("\r\n").into_bytes()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::{Cell, Fmt, Para};
use wordcraft_doc::StoryRef;
#[test]
fn test_utf32_bom_decode_and_sniffing() {
let mut u32le = vec![0xFF, 0xFE, 0x00, 0x00];
for c in "Hello 🦀".chars() {
u32le.extend((c as u32).to_le_bytes());
}
assert!(is_text(&u32le));
assert_eq!(decode(&u32le), "Hello 🦀");
assert_eq!(decode_as(&u32le, "utf-32"), Some("Hello 🦀".into()));
assert_eq!(decode_as(&u32le, "utf-32le"), Some("Hello 🦀".into()));
assert_eq!(decode_as(&u32le[4..], "utf-32"), Some("Hello 🦀".into()));
let mut u32be = vec![0x00, 0x00, 0xFE, 0xFF];
for c in "World 🌍".chars() {
u32be.extend((c as u32).to_be_bytes());
}
assert!(is_text(&u32be));
assert_eq!(decode(&u32be), "World 🌍");
assert_eq!(decode_as(&u32be, "utf-32"), Some("World 🌍".into()));
assert_eq!(decode_as(&u32be, "utf-32be"), Some("World 🌍".into()));
}
#[test]
fn test_import_preserves_soft_breaks() {
let raw = b"Line 1\x0BSoft break\x0ECol break";
let doc = import(raw);
let text = doc.plain_text(StoryRef::Body);
assert_eq!(text, "Line 1\u{000B}Soft break\u{000E}Col break");
}
#[test]
fn test_table_export_colspan_covered_and_newline_cleaning() {
let mut t = crate::model::FTable::default();
let mut c1 = Cell { colspan: 2, ..Default::default() };
let mut p1 = Para::default();
p1.push_text("Merged\nHeader\tItem", &Fmt::default());
c1.blocks.push(FBlock::Para(p1));
let mut c2 = Cell::default();
let mut p2 = Para::default();
p2.push_text("Col 3", &Fmt::default());
c2.blocks.push(FBlock::Para(p2));
let c3 = Cell { covered: true, ..Default::default() };
let mut c4 = Cell::default();
let mut p4 = Para::default();
p4.push_text("Row 2 Col 2", &Fmt::default());
c4.blocks.push(FBlock::Para(p4));
let mut c5 = Cell::default();
let mut p5 = Para::default();
p5.push_text("Row 2 Col 3", &Fmt::default());
c5.blocks.push(FBlock::Para(p5));
t.rows.push(vec![c1, c2]);
t.rows.push(vec![c3, c4, c5]);
let mut out = Vec::new();
let blocks = vec![FBlock::Table(t)];
blocks_text(&blocks, &mut out, &mut ListCounter::default(), 0);
assert_eq!(out.len(), 2);
// Row 1: Merged Header Item (colspan 2) -> "Merged Header Item\t\tCol 3"
assert_eq!(out[0], "Merged Header Item\t\tCol 3");
// Row 2: Covered cell is empty -> "\tRow 2 Col 2\tRow 2 Col 3"
assert_eq!(out[1], "\tRow 2 Col 2\tRow 2 Col 3");
}
}
+6 -5
View File
@@ -1,6 +1,7 @@
use super::ctx::{Ctx, Joining, page_anchored};
use super::floats::{
AnchoredFloat, ObjFrame, ObjectPlacement, WrapArea, align_in, float_rect, floating, left_out_objects, place_objects, rel_exclusions, wrap_area,
AnchoredFloat, AreaKind, ObjFrame, ObjectPlacement, WrapArea, align_in, float_rect, floating, left_out_objects, place_objects, rel_exclusions,
wrap_area,
};
use super::flow::again;
use super::page::PageFrame;
@@ -162,11 +163,11 @@ fn layout_table_block(input: TableBlockContext<'_, '_, '_>) -> bool {
Some(float) => {
let place = FloatPlace { shift: table::float_offset_shift(ctx, t), modern: ctx.doc.settings.compat_mode >= 15 };
let (rect, area) = box_float_table_rect(frame, width, *y, &layout, &float, place, float_tables);
exclusions.push((area, false, None, WrapText::BothSides, true));
exclusions.push((area, false, None, WrapText::BothSides, AreaKind::Table));
float_tables.push(area);
table_areas.push(area);
if float.v_rel == Anchor::Page {
page_table_wraps.push((area, false, None, WrapText::BothSides, true));
page_table_wraps.push((area, false, None, WrapText::BothSides, AreaKind::Table));
}
(rect.x, rect.y)
}
@@ -812,7 +813,7 @@ impl Joint {
let probe = again(ctx, eq, |ctx| ctx.para_labelled(q, width, table, &[], 0.0, None));
let (gap, height) = probe.lines.first().map_or((0.0, self.height), |l| ((self.baseline - (l.baseline - l.top)).max(0.0), l.height));
let rect = Rect::new(self.left, self.top, (self.end - self.left).max(0.0), (gap + height - 0.01).max(0.01));
let mut areas = vec![(rect, false, None, WrapText::Right, false)];
let mut areas = vec![(rect, false, None, WrapText::Right, AreaKind::Object)];
// Just below the first row as the line breaker tests it: the breaker tests every row at
// its estimate (`row_est`), not at the line's height, so the first row never meets this
// area and every later row, starting lower, does and moves below it. The probe's own first
@@ -820,7 +821,7 @@ impl Joint {
// line), so its height can't be used here.
let below = self.top + gap + probe.row_est + 0.01;
if self.bottom() > below {
areas.push((Rect::new(self.left, below, width.max(0.01), self.bottom() - below), true, None, WrapText::BothSides, false));
areas.push((Rect::new(self.left, below, width.max(0.01), self.bottom() - below), true, None, WrapText::BothSides, AreaKind::Object));
}
(gap, areas)
}
+20 -6
View File
@@ -117,8 +117,20 @@ pub(crate) fn align_in((start, extent): (f32, f32), offset: f32, size: f32, alig
/// An area text keeps clear of: its bounds, whether text may only go above and below it, and
/// (Tight and Through wrapping) the outline text follows inside it, the sides text may go on,
/// and whether it comes from a floating table (inclusive line-bottom contact, #3977).
pub(crate) type WrapArea = (Rect, bool, Option<Arc<contour::Contour>>, WrapText, bool);
/// and what it comes from (a floating table: inclusive line-bottom contact, #3977; Tight and
/// Through wrapping: a narrower gap beside it before Word 2013 layout, #6316).
pub(crate) type WrapArea = (Rect, bool, Option<Arc<contour::Contour>>, WrapText, AreaKind);
/// What a [`WrapArea`] keeps text clear of.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum AreaKind {
/// A floating picture, shape, text box or chart wrapped Square or Top and Bottom.
Object,
/// A floating object wrapped Tight or Through, with or without an outline.
Tight,
/// A floating table.
Table,
}
/// Wrap areas a page starts with (#2048): by page index, the floating objects (block, object
/// index) placed above the top of their anchor paragraph, with text before it on the page, and
@@ -210,13 +222,14 @@ pub(crate) fn wrap_area(r: Rect, float: &Float, outline: Option<&[(f32, f32)]>)
if matches!(float.wrap, Wrap::Tight | Wrap::Through)
&& let Some((area, c)) = outline.and_then(|o| contour::contour_area(r, float, o))
{
return Some((area, false, Some(Arc::new(c)), float.wrap_text, false));
return Some((area, false, Some(Arc::new(c)), float.wrap_text, AreaKind::Tight));
}
let d = |v: f32| if v.is_finite() { v.clamp(0.0, 1584.0) } else { 0.0 };
let (side, top, bottom) = (d(float.dist), d(float.dist_top), d(float.dist_bottom));
// A rotated object keeps text clear of its rotated bounds.
let r = float.spin().bounds(r);
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))
let kind = if matches!(float.wrap, Wrap::Tight | Wrap::Through) { AreaKind::Tight } else { AreaKind::Object };
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, kind))
}
/// Wrap areas relative to a paragraph whose column starts at `x0` and whose top is `y0`, with
@@ -224,7 +237,7 @@ pub(crate) fn wrap_area(r: Rect, float: &Float, outline: Option<&[(f32, f32)]>)
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 {
.map(|(r, tb, c, side, kind)| para::Exclusion {
top: r.y - y0,
bottom: r.bottom() - y0,
left: r.x - x0,
@@ -232,7 +245,8 @@ pub(crate) fn rel_exclusions(excl: &[WrapArea], x0: f32, y0: f32, space_before:
top_bottom: *tb,
contour: c.clone(),
side: *side,
table: *table,
table: *kind == AreaKind::Table,
tight: *kind == AreaKind::Tight,
})
// 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
+1 -1
View File
@@ -1332,7 +1332,7 @@ mod tests {
pb.cap_columns();
// A preceding floating object leaves a narrow strip of the first column, but does
// not occupy the second column. The same kept paragraph fits there in one line.
pb.excl.push((Rect::new(pb.col_x(), top, pb.col_w() - 26.0, 100.0), false, None, WrapText::BothSides, false));
pb.excl.push((Rect::new(pb.col_x(), top, pb.col_w() - 26.0, 100.0), false, None, WrapText::BothSides, crate::floats::AreaKind::Object));
place_para_in_flow(ctx, pb, p, 0, top);
assert_eq!(pb.pages.len(), 1, "a fitting candidate kept the balance attempt on its page");
+36
View File
@@ -786,6 +786,42 @@ impl DocLayout {
None
}
/// The text direction of the lines holding `pos`; `None` for upright (horizontal) text.
pub fn turn_at(&self, pos: &Pos, page_hint: usize) -> Option<TextDirection> {
self.pieces(pos.story, &pos.path, page_hint).into_iter().find_map(|(_, it)| match it {
Placed::Lines { para, l0, l1, turn, .. } if turn.is_turned() && (*l0..*l1).contains(&para.line_of(pos.off)) => Some(*turn),
_ => None,
})
}
/// In turned text, the position on the next (`next`) or previous line in reading order, at
/// `goal` along the line (its own frame; `None` keeps the caret's). Returns it with that
/// along-line coordinate. Only lines of the same flow count (the paragraphs of one story
/// level or of one table cell, not another cell's), so `None` at the first/last line of the
/// caret's flow on the page.
pub fn turned_line(&self, pos: &Pos, goal: Option<f32>, next: bool, page_hint: usize) -> Option<(Pos, f32)> {
let c = self.caret_on(pos, page_hint)?;
let lines: Vec<(&Path, &std::sync::Arc<ParaLayout>, usize)> = items_of(self.pages.get(c.page)?, pos.story)
.filter_map(|it| match it {
Placed::Lines { story, path, para, l0, l1, turn, .. }
if *story == pos.story && turn.is_turned() && path.parent() == pos.path.parent() =>
{
Some((path, para, *l0, *l1))
}
_ => None,
})
.flat_map(|(path, para, l0, l1)| (l0..l1).map(move |li| (path, para, li)))
.collect();
let here = lines.iter().position(|(path, para, li)| *path == &pos.path && *li == para.line_of(pos.off))?;
let (path, para, li) = lines.get(if next { here + 1 } else { here.checked_sub(1)? })?;
let gx = match goal {
Some(g) => g,
None => lines[here].1.x_of(lines[here].2, pos.off)?,
};
let off = para.off_at_x(*li, gx);
Some((Pos { story: pos.story, path: (*path).clone(), off }, gx))
}
/// The position one line up (`dir < 0`) or down from `pos`, keeping `goal_x` (page x).
pub fn vertical(&self, pos: &Pos, goal_x: Option<f32>, dir: i32, page_hint: usize) -> Option<(Pos, f32)> {
let c = self.caret_on(pos, page_hint)?;
+3
View File
@@ -173,6 +173,9 @@ pub struct Exclusion {
pub side: WrapText,
/// A floating table counts a line touching its top as overlapping; shapes do not (#3977).
pub table: bool,
/// Tight and Through wrapping: before Word 2013 layout text goes in a narrower gap beside
/// it (#6316).
pub tight: bool,
}
impl Exclusion {
+118 -18
View File
@@ -30,6 +30,9 @@ struct Breaker<'e> {
/// Word 2013+ (compatibility mode 15) fits more text on a justified line by shrinking its
/// spaces (`space_room`); on a line with tabs, only the spaces after a final left/default tab.
shrink_spaces: bool,
/// Word 2013+ layout (compatibility mode 15): the narrowest span beside a Tight or Through
/// object is the same as beside any other ([`min_span`]).
layout_2013: bool,
/// Word 2003's indent rules (`w:doNotSuppressIndentation`) before Word 2013's layout, for an
/// unnumbered paragraph: a row starts right after a floating object before the indent.
tight_indent: bool,
@@ -208,6 +211,7 @@ impl<'e> Breaker<'e> {
hanging_at: if rp.indent_first < 0.0 { Some(rp.indent_left) } else { None },
tab_origin: if settings.odf.is_some_and(|o| o.tabs_from_indent) { rp.indent_left } else { 0.0 },
shrink_spaces: rp.align == Align::Justify && settings.compat_mode >= wordcraft_doc::COMPAT_MODE_CURRENT,
layout_2013: settings.compat_mode >= wordcraft_doc::COMPAT_MODE_CURRENT,
tight_indent: settings.do_not_suppress_indentation
&& settings.compat_mode < wordcraft_doc::COMPAT_MODE_CURRENT
&& level.is_none()
@@ -295,7 +299,9 @@ impl<'e> Breaker<'e> {
}
}
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)) {
match row_spans(self.exclusions, row, (lo, self.base_right), self.tight_indent, self.layout_2013)
.map(|mut spans| (spans.pop_front(), spans))
{
Ok((Some((a, b)), rest)) => {
// Under Word 2003's indent rules a row can start left of the indent too.
let moved = if self.tight_indent { (a - lo).abs() > 0.01 } else { a > lo };
@@ -1190,10 +1196,28 @@ fn line_end_kern(pl: &ParaLayout, j: usize) -> f32 {
}
}
/// Narrowest span text flows into beside a floating object, points. Word puts an empty
/// Narrowest span text flows into beside a floating table, 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;
/// Narrowest span text flows into beside a floating picture or shape, points: Word puts a line
/// in an 18pt gap to its wrap area but not in a 17.95pt one, for square, tight and through
/// wrapping alike, whatever the text (#6316).
const MIN_SPAN_OBJECT: f32 = 18.0;
/// Tight and Through wrapping before Word 2013 layout (compatibility mode 14 and below) need
/// only half that: 9pt fits, 8.95pt doesn't.
const MIN_SPAN_CONTOUR_OLD: f32 = 9.0;
/// The narrowest span text goes into beside `e`, with Word 2013 layout or later (`current`).
fn min_span(e: &Exclusion, current: bool) -> f32 {
match (e.table, e.tight) {
(true, _) => MIN_SPAN,
(false, true) if !current => MIN_SPAN_CONTOUR_OLD,
_ => MIN_SPAN_OBJECT,
}
}
/// Where a row starts under Word 2003's indent rules: right after the floating objects that end
/// at or before the indent `lo` on this row and let text past their right side (their outline's
/// right edge for Tight and Through wrapping), never left of the paragraph's own left edge (0) or
@@ -1224,16 +1248,18 @@ fn baseline_offset(spacing: LineSpacing, asc: f32, height: f32, desc: f32) -> f3
}
/// The spans of a row at `top` (about `h` tall) between `lo` and `hi` that text can use around
/// the exclusions, left to right (Square wrapping uses both sides of an object). `Err(y)`: none
/// here, try again at `y` (below what's in the way). With `tight_indent` (Word 2003's indent
/// rules, `w:doNotSuppressIndentation`) a row starts right after a floating object that ends
/// before `lo`, the indent ignored (ECMA-376 Part 4 §14.8.3.12: a paragraph indented 1" tightly
/// wraps an object at 0.25").
/// the exclusions, left to right (Square wrapping uses both sides of an object); a span must be
/// as wide as the minimum of each object it borders (`current`: Word 2013 layout or later).
/// `Err(y)`: none here, try again at `y` (below what's in the way). With `tight_indent` (Word
/// 2003's indent rules, `w:doNotSuppressIndentation`) a row starts right after a floating object
/// that ends before `lo`, the indent ignored (ECMA-376 Part 4 §14.8.3.12: a paragraph indented
/// 1" tightly wraps an object at 0.25").
fn row_spans(
exclusions: &[Exclusion],
(top, h, table_h): (f32, f32, f32),
(lo, hi): (f32, f32),
tight_indent: bool,
current: bool,
) -> Result<VecDeque<(f32, f32)>, f32> {
let lo = if tight_indent { tight_row_start(exclusions, (top, h, table_h), lo) } else { lo };
let here: Vec<&Exclusion> = exclusions.iter().filter(|e| e.intersects_row(top, h, table_h, lo, hi)).collect();
@@ -1241,13 +1267,14 @@ fn row_spans(
return Err(below);
}
// What each object takes of the row: its whole area, or (Tight, Through) the stretches its
// outline takes, as (left, right, bottom of the object's area).
let mut taken: Vec<(f32, f32, f32)> = Vec::new();
// outline takes, as (left, right, bottom of the object's area, the narrowest span beside it).
let mut taken: Vec<(f32, f32, f32, f32)> = Vec::new();
for e in &here {
let first = taken.len();
let min = min_span(e, current);
match &e.contour {
None => taken.push((e.left, e.right, e.bottom)),
Some(c) => taken.extend(c.occupied(top - e.top, top + h - e.top).into_iter().map(|(a, b)| (a + e.left, b + e.left, e.bottom))),
None => taken.push((e.left, e.right, e.bottom, min)),
Some(c) => taken.extend(c.occupied(top - e.top, top + h - e.top).into_iter().map(|(a, b)| (a + e.left, b + e.left, e.bottom, min))),
}
// Text on one side only: the object's other side of the row is taken too.
let Some(mine) = taken.get(first..).filter(|t| !t.is_empty() && !e.side.is_both()) else { continue };
@@ -1260,23 +1287,96 @@ fn row_spans(
_ => left - lo >= hi - right,
};
taken.truncate(first);
taken.push(if text_left { (left, hi.max(right), e.bottom) } else { (lo.min(left), right, e.bottom) });
taken.push(if text_left { (left, hi.max(right), e.bottom, min) } else { (lo.min(left), right, e.bottom, min) });
}
taken.retain(|(l, r, _)| *r > lo && *l < hi);
taken.retain(|(l, r, _, _)| *r > lo && *l < hi);
if taken.is_empty() {
return Ok(VecDeque::from([(lo, hi)]));
}
let mut spans = vec![(lo, hi)];
for &(left, right, _) in &taken {
// Each span with the minimum of what borders it on the left and on the right (nothing at the
// row's ends): an object cutting a span becomes the new edge of both pieces, and an object
// ending right at a span's edge borders it too, the larger minimum winning (a picture and a
// table both ending at 70: the span after them needs the table's).
let mut spans = vec![(lo, hi, 0.0_f32, 0.0_f32)];
for &(left, right, _, min) in &taken {
spans = spans
.into_iter()
.flat_map(|(a, b)| if right <= a || left >= b { vec![(a, b)] } else { vec![(a, left.min(b)), (right.max(a), b)] })
.flat_map(|(a, b, ml, mr)| {
if right <= a || left >= b {
let ml = if (right - a).abs() < 0.01 { ml.max(min) } else { ml };
let mr = if (left - b).abs() < 0.01 { mr.max(min) } else { mr };
vec![(a, b, ml, mr)]
} else {
vec![(a, left.min(b), ml, min), (right.max(a), b, min, mr)]
}
})
.collect();
}
spans.retain(|(a, b)| b - a >= MIN_SPAN);
let spans: VecDeque<(f32, f32)> = spans.into_iter().filter(|(a, b, ml, mr)| b - a >= ml.max(*mr)).map(|(a, b, ..)| (a, b)).collect();
if spans.is_empty() {
// Nothing wide enough: the line goes below the first object that ends.
return Err(taken.iter().map(|t| t.2).reduce(f32::min).unwrap_or(top));
}
Ok(spans.into())
Ok(spans)
}
#[cfg(test)]
mod tests {
use super::*;
/// An exclusion from the row's left edge to `right`, 100pt tall.
fn area(right: f32, table: bool, tight: bool) -> Exclusion {
Exclusion { top: 0.0, bottom: 100.0, left: 0.0, right, top_bottom: false, contour: None, side: WrapText::BothSides, table, tight }
}
/// Whether a line at the top of a 100pt row finds a span `gap` points wide beside `e`.
fn fits(e: Exclusion, gap: f32, current: bool) -> bool {
let hi = e.right + gap;
row_spans(&[e], (0.0, 12.0, 12.0), (0.0, hi), false, current).is_ok()
}
/// #6316: 18pt beside pictures and shapes; Tight and Through 9pt before Word 2013 layout;
/// floating tables keep 20.
#[test]
fn the_narrowest_span_depends_on_the_object() {
for current in [true, false] {
assert!(fits(area(50.0, false, false), 18.0, current) && !fits(area(50.0, false, false), 17.9, current));
assert!(fits(area(50.0, true, false), 20.0, current) && !fits(area(50.0, true, false), 19.9, current));
}
assert!(fits(area(50.0, false, true), 18.0, true) && !fits(area(50.0, false, true), 17.9, true));
assert!(fits(area(50.0, false, true), 9.0, false) && !fits(area(50.0, false, true), 8.9, false));
// A span between a picture and a table needs the table's 20.
let both = |gap: f32| {
let table = Exclusion { left: 50.0 + gap, right: 300.0, ..area(0.0, true, false) };
row_spans(&[area(50.0, false, false), table], (0.0, 12.0, 12.0), (0.0, 300.0), false, true).is_ok()
};
assert!(both(20.0) && !both(19.9));
// A span bordered only by a picture needs 18, whichever order the objects come in, also
// when a table cut the span first (a table at 0..70, a picture at 80..100, a 19pt span
// right of the picture).
let table = area(70.0, true, false);
let picture = Exclusion { left: 80.0, right: 100.0, ..area(0.0, false, false) };
for order in [[table.clone(), picture.clone()], [picture.clone(), table.clone()]] {
let spans = row_spans(&order, (0.0, 12.0, 12.0), (0.0, 119.0), false, true);
assert_eq!(spans, Ok(VecDeque::from([(100.0, 119.0)])), "{order:?}");
}
}
/// A picture and a table ending at the same edge: the span after them needs the table's 20,
/// whichever comes first, and on the other side too.
#[test]
fn objects_sharing_an_edge_need_the_larger_minimum() {
let row = (0.0, 12.0, 12.0);
let (picture, table) = (area(70.0, false, false), area(70.0, true, false));
for order in [[picture.clone(), table.clone()], [table.clone(), picture.clone()]] {
assert!(row_spans(&order, row, (0.0, 89.0), false, true).is_err(), "19pt: {order:?}");
assert_eq!(row_spans(&order, row, (0.0, 90.0), false, true), Ok(VecDeque::from([(70.0, 90.0)])), "20pt: {order:?}");
}
let picture = Exclusion { left: 30.0, right: 100.0, ..picture };
let table = Exclusion { left: 30.0, right: 100.0, ..table };
for order in [[picture.clone(), table.clone()], [table.clone(), picture.clone()]] {
assert!(row_spans(&order, row, (11.0, 100.0), false, true).is_err(), "19pt: {order:?}");
assert_eq!(row_spans(&order, row, (10.0, 100.0), false, true), Ok(VecDeque::from([(10.0, 30.0)])), "20pt: {order:?}");
}
}
}
+51
View File
@@ -2038,6 +2038,57 @@ mod width_tests {
assert_eq!(grid, [100.0, 200.0, 250.0, 100.0], "a fixed table keeps its grid");
}
#[test]
fn grid_before_row_keeps_grid() {
let mut table = Table::new(2, 3, 300.0);
for row in &mut table.rows {
for cell in &mut row.cells {
cell.props.width = Some(100.0);
}
}
table.rows[1].props.grid_before = 1;
table.grid = vec![150.0, 150.0, 150.0];
table.props.width = Some(300.0);
let mut grid = table.grid.clone();
apply_cell_widths(&table, &mut grid);
assert_eq!(grid, [150.0, 150.0, 150.0]);
}
#[test]
fn grid_after_row_keeps_grid() {
let mut table = Table::new(2, 3, 300.0);
for row in &mut table.rows {
for cell in &mut row.cells {
cell.props.width = Some(100.0);
}
}
table.rows[1].props.grid_after = 1;
table.grid = vec![150.0, 150.0, 150.0];
table.props.width = Some(300.0);
let mut grid = table.grid.clone();
apply_cell_widths(&table, &mut grid);
assert_eq!(grid, [150.0, 150.0, 150.0]);
}
#[test]
fn disagreeing_row_edges_keep_grid() {
let mut table = Table::new(2, 3, 300.0);
for (cell, width) in table.rows[0].cells.iter_mut().zip([100.0, 100.0, 100.0]) {
cell.props.width = Some(width);
}
for (cell, width) in table.rows[1].cells.iter_mut().zip([120.0, 80.0, 100.0]) {
cell.props.width = Some(width);
}
table.grid = vec![150.0, 150.0, 150.0];
table.props.width = Some(300.0);
let mut grid = table.grid.clone();
apply_cell_widths(&table, &mut grid);
assert_eq!(grid, [150.0, 150.0, 150.0]);
}
#[test]
fn autofit_keeps_fitting_widths() {
crate::test_fonts();
+2 -2
View File
@@ -1,6 +1,6 @@
use super::boxes::{BoxInput, clear_of_float_tables, layout_box};
use super::ctx::{Ctx, with_pct_base};
use super::floats::{WrapArea, align_in, body_wraps};
use super::floats::{AreaKind, WrapArea, align_in, body_wraps};
use super::flow::again;
use super::headers::{begins_section, header_items_cap, header_table_areas, placed_cost};
use super::notes::table_notes;
@@ -435,7 +435,7 @@ fn place_floating_table(ctx: &mut Ctx, pb: &mut PageBuilder, tl: &table::TableLa
pg.float_tables.push(Path::top(block));
}
let area = r.inset(-dl, -dt, -dr, -db);
pb.excl.push((area, false, None, WrapText::BothSides, true));
pb.excl.push((area, false, None, WrapText::BothSides, AreaKind::Table));
pb.float_tables.push(area);
return;
}
+62
View File
@@ -12574,6 +12574,68 @@ fn tight_wrap_follows_an_ellipse() {
assert_eq!(through, tight);
}
/// #6316: how many of seven empty paragraphs (the first anchoring a 200pt-tall rectangle at the
/// column's left with `wrap`) go in the `free` points it leaves on its right (column edge to its
/// wrap area, 9pt from text included), in compatibility mode `mode`.
fn empty_lines_beside(wrap: wordcraft_doc::para::Wrap, free: f32, mode: u32) -> usize {
use wordcraft_doc::para::{Anchor, Float, ShapeKind};
let w = 468.0 - 9.0 - free;
let mut d = Document::from_text("");
d.settings.compat_mode = mode;
let float = Float { wrap, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, dist: 9.0, ..Default::default() };
let shape = InlineObject::Shape {
kind: ShapeKind::Rectangle,
w,
h: 200.0,
fill: None,
stroke: None,
stroke_width: 1.0,
float,
story: None,
effects: Default::default(),
freeform: None,
extra: Default::default(),
};
d.insert_object(&Pos::body(0, 0), shape, &Default::default()).unwrap();
for i in 1..7 {
d.insert_block(StoryRef::Body, &Path::top(i), wordcraft_doc::Block::Para(Default::default())).unwrap();
}
let l = lay(&d);
let lines: Vec<(f32, f32)> =
l.pages[0].items.iter().filter_map(|i| if let Placed::Lines { y, para, .. } = i { Some((para.lines[0].left, *y)) } else { None }).collect();
let Some(top) = lines.iter().map(|l| l.1).reduce(f32::min) else { return 0 };
lines.iter().filter(|(left, y)| *left >= w + 9.0 - 0.01 && *y < top + 200.0).count()
}
/// #6316: Word puts a line beside a floating picture or shape when the gap between the column
/// edge and the object's wrap area is at least 18pt, for square, tight and through wrapping; a
/// tight-wrapped cover with 17.55 and 19.15pt gaps was pushed onto three pages by a 20pt minimum.
#[test]
fn text_goes_beside_a_float_in_an_18pt_gap() {
crate::test_fonts();
use wordcraft_doc::para::Wrap;
let current = wordcraft_doc::COMPAT_MODE_CURRENT;
for wrap in [Wrap::Square, Wrap::Tight, Wrap::Through] {
assert_eq!(empty_lines_beside(wrap, 18.1, current), 7, "{wrap:?} 18.1");
assert_eq!(empty_lines_beside(wrap, 17.9, current), 0, "{wrap:?} 17.9");
}
}
/// Before Word 2013 layout (mode 14 and below) a line goes beside a tight or through object in
/// a 9pt gap; square wrapping still needs 18.
#[test]
fn tight_wrap_needs_only_9pt_beside_it_before_word_2013_layout() {
crate::test_fonts();
use wordcraft_doc::para::Wrap;
for wrap in [Wrap::Tight, Wrap::Through] {
assert_eq!(empty_lines_beside(wrap, 9.1, 14), 7, "{wrap:?} 9.1");
assert_eq!(empty_lines_beside(wrap, 8.9, 14), 0, "{wrap:?} 8.9");
assert_eq!(empty_lines_beside(wrap, 9.1, wordcraft_doc::COMPAT_MODE_CURRENT), 0, "{wrap:?} 9.1 in mode 15");
}
assert_eq!(empty_lines_beside(Wrap::Square, 17.9, 14), 0);
assert_eq!(empty_lines_beside(Wrap::Square, 18.1, 14), 7);
}
#[test]
fn contour_wrap_turns_with_the_object() {
crate::test_fonts();
+43
View File
@@ -171,3 +171,46 @@ fn a_click_outside_a_floating_table_in_a_vertical_section_skips_its_cells() {
// Inside the table a click still lands in a cell.
assert!(l.hit(0, cx, cy, StoryRef::Body).unwrap().path.0.len() > 1);
}
/// #8986: in vertical text the next line is the next paragraph's, left of this one, at the same
/// distance along it; the first and last lines have no previous/next.
#[test]
fn turned_line_steps_to_the_adjacent_column() {
crate::test_fonts();
let mut d = Document::from_text("abc\ndef\nghi");
d.last_section.text_direction = TextDirection::Down;
let l = lay(&d);
let p = Pos::body(1, 1);
assert_eq!(l.turn_at(&p, 0), Some(TextDirection::Down));
let (next, g) = l.turned_line(&p, None, true, 0).unwrap();
assert_eq!((next.path, next.off), (Path::top(2), 1));
let (prev, _) = l.turned_line(&p, Some(g), false, 0).unwrap();
assert_eq!((prev.path, prev.off), (Path::top(0), 1));
assert!(l.turned_line(&Pos::body(2, 0), None, true, 0).is_none());
assert_eq!(lay(&Document::from_text("abc")).turn_at(&Pos::body(0, 0), 0), None);
}
/// #8986: in a table whose cells run vertical text, the next line is one of the same cell, never
/// another cell's (a cell's only line has no previous/next).
#[test]
fn turned_line_stays_in_its_table_cell() {
crate::test_fonts();
let mut d = Document::from_text("before");
let mut t = wordcraft_doc::Table::new(1, 3, 468.0);
for (i, c) in t.rows[0].cells.iter_mut().enumerate() {
c.props.text_direction = TextDirection::Down;
let paras = if i == 1 { ["abc", "def"].as_slice() } else { ["xyz"].as_slice() };
c.blocks = paras.iter().map(|s| wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text(s, Default::default()))).collect();
}
d.insert_block(StoryRef::Body, &Path::top(1), Block::Table(t)).unwrap();
let l = lay(&d);
let at = |cell: u32, para: u32, off: usize| Pos { story: StoryRef::Body, path: Path(vec![1, 0, cell, para]), off };
let (next, _) = l.turned_line(&at(1, 0, 1), None, true, 0).unwrap();
assert_eq!((next.path, next.off), (Path(vec![1, 0, 1, 1]), 1));
assert!(l.turned_line(&at(1, 1, 1), None, true, 0).is_none());
assert!(l.turned_line(&at(1, 0, 1), None, false, 0).is_none());
for cell in [0, 2] {
assert!(l.turned_line(&at(cell, 0, 1), None, true, 0).is_none());
assert!(l.turned_line(&at(cell, 0, 1), None, false, 0).is_none());
}
}
+7 -2
View File
@@ -126,6 +126,7 @@ impl WordApp {
applied_editing: None,
frame_ms: 0.0,
quit_requested: false,
quit_recheck: false,
autosave: true,
zotero: zotero::ZoteroLink::default(),
ctx: None,
@@ -264,8 +265,12 @@ impl WordApp {
if let Some(ctx) = self.ctx.clone() {
self.run_fired(&ctx, &out);
self.canvas.take_focus_after_pass(&ctx);
self.native_scale = theme::usable_scale(ctx.native_pixels_per_point().unwrap_or(1.0));
if let Some(native) = ctx.native_pixels_per_point()
// The zoom is context-wide but the display scale is per window: read it from the active
// document window. The windowless root has no window, so it reports none (#8853).
let active = self.active_viewport();
let native_now = ctx.input_for(active, |i| i.viewport().native_pixels_per_point).or_else(|| ctx.native_pixels_per_point());
self.native_scale = theme::usable_scale(native_now.unwrap_or(1.0));
if let Some(native) = native_now
&& let Some(old) = self.legacy_interface_size.take()
{
self.ui.interface_size = theme::migrate_legacy_interface_size(old, native);
+6 -1
View File
@@ -519,7 +519,12 @@ impl WordApp {
return false;
}
if self.quit_requested {
return true;
// A quit that found nothing unsaved: the close that ends it has committed the focused field's typed text,
// which is asked about like any other change (#8790). Once only, so an answered prompt is not asked again.
if !(std::mem::take(&mut self.quit_recheck) && self.has_unsaved_documents()) {
return true;
}
self.quit_requested = false;
}
// Nothing to save, also with no document open in this window (#1129) and none elsewhere.
if !self.has_unsaved_documents() {
+15 -5
View File
@@ -653,13 +653,17 @@ fn mark_areas(app: &mut WordApp, layout: &DocLayout, selected: &[(usize, wordcra
areas
}
/// The navigation options of WordCraft's canvas: the document wheel scheme, and middle-click autoscroll where the
/// platform has the gesture (not macOS, iOS or the web, whose middle button has its own meaning).
fn navigation_options() -> NavigationOptions {
/// The navigation options of WordCraft's canvas: the document wheel scheme, the document wheel notch
/// ([`crate::scroll::NOTCH_PX`]), eased wheel scrolling when animations are enabled, and middle-click autoscroll
/// where the platform has the gesture (not macOS, iOS or the web, whose middle button has its own meaning).
fn navigation_options(animations: bool) -> NavigationOptions {
let mut options = NavigationOptions::default();
options.middle_button =
if cfg!(any(target_os = "macos", target_os = "ios", target_arch = "wasm32")) { MiddleButton::Pan } else { MiddleButton::AutoScroll };
options.wheel = WheelScheme::Document;
// Browsers report three lines per notch where native platforms report one.
options.wheel_line = if cfg!(target_arch = "wasm32") { crate::scroll::NOTCH_PX / 3.0 } else { crate::scroll::NOTCH_PX };
options.eased_wheel = animations;
options
}
@@ -862,11 +866,12 @@ fn show_pages(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: Rec
.into_iter()
.filter(|(_, id)| !crate::app::command_board::command_enabled(app, id))
.fold(EditSet::NONE, |set, (command, _)| set.with(command));
let animations = app.animations_on();
let out = PageView::new(tl!("Document"), &source, &mut state, paper)
.options(options)
// Hide White Space cuts each page to its text area: without the bodies the pages show whole.
.bodies(&bodies)
.navigation(navigation_options())
.navigation(navigation_options(animations))
.editor(craft::ui::primitives::EditorPurpose::Text)
.inactive_edits(inactive_edits)
.rulers(show_rulers)
@@ -1054,7 +1059,12 @@ fn show_pages(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: Rec
app.canvas.mini_dismissed = None;
}
balloons::balloons(app, ui, &out, layout);
rulers::page_rulers(app, ui, &out, layout);
if show_rulers {
rulers::page_rulers(app, ui, &out, layout);
} else if app.canvas.table_resize.as_ref().is_some_and(crate::table_resize::ResizeDrag::on_ruler) {
// Hidden rulers can't finish a border drag they started: drop it with its preview.
app.canvas.table_resize = None;
}
// The one context-menu ask of the pass: Shift+F10 or `ui.contextMenu` (below the caret), a click on the equation
// frame's options strip, then the tool host's own request by how it was asked for.
let ask = app.canvas.context_request.take().or_else(|| strip_click.map(ContextAsk::AtPointer));
+4 -1
View File
@@ -66,6 +66,8 @@ pub(crate) struct EquationFrameStyle {
line: StyleColor,
accent: StyleColor,
soft: StyleColor,
/// Behind the equation's text, so translucent: the argument the caret is in.
shade: StyleColor,
handle_fill: StyleColor,
handle_stroke: StyleColor,
}
@@ -121,6 +123,7 @@ impl Component for EquationFrameControl<'_> {
line: cx.color(t.color.overlay.line),
accent: cx.color(t.color.accent.solid),
soft: cx.color(t.color.accent.soft),
shade: cx.color(t.color.accent.solid.with_alpha(40)),
handle_fill: cx.color(t.color.overlay.handle_fill),
handle_stroke: cx.color(t.color.overlay.handle_stroke),
}
@@ -160,7 +163,7 @@ impl Component for EquationFrameControl<'_> {
let EquationFrame { outline, grip, strip } = equation_frame(self.page, self.bx, &style.sizes);
let corner = CornerRadius::from(style.radius);
if let Some(arg) = self.argument {
draw.fill(&PaintShape::Rect(arg, CornerRadius::ZERO), style.soft);
draw.fill(&PaintShape::Rect(arg, CornerRadius::ZERO), style.shade);
}
draw.fill(&PaintShape::Rect(strip, CornerRadius::ZERO), style.soft);
let (c, w) = (strip.center(), style.chevron / 2.0);
+68 -2
View File
@@ -8,9 +8,11 @@ use crate::test_harness::AppFrames as _;
use std::collections::HashSet;
/// Rests the pointer for as long as the framework's tooltip waits before it shows a tool's tip
/// (`tooltip::DELAY`, the framework's look), at the harness's default step of a quarter second.
/// (`tooltip::DELAY`, the framework's look), at the harness's configured step time (`predicted_dt`).
fn rest_for_tip(h: &mut H) {
let frames = (craft::ui::contract::tooltip::DELAY / 0.25).ceil() as usize + 3;
let step_dt = f64::from(h.ctx.input(|i| i.predicted_dt));
assert!(step_dt > 0.0, "harness step_dt must be positive, got {step_dt}");
let frames = (craft::ui::contract::tooltip::DELAY / step_dt).ceil() as usize + 3;
steps(h, frames);
}
@@ -2899,3 +2901,67 @@ fn shift_clicking_a_picture_does_not_scroll_the_view() {
assert!(picked.contains(&first) && picked.contains(&second), "both pictures are selected: {picked:?} {:?} at {at:?}", h.state().session.sel);
assert_eq!(h.state().canvas.view.offset, before, "the view stayed where it was");
}
/// Mouse-wheel notches scroll by WordCraft's document line distance (`NOTCH_PX`, 56 pt) rather than the framework's
/// 16 pt default, and rapid flick notches accelerate when animations are enabled (#8840).
#[test]
fn mouse_wheel_notch_scrolls_document_line_distance_and_accelerates_on_flick() {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
a.run("text.insert", json!({"text": "lorem ipsum dolor sit amet consectetur ".repeat(2000)})).unwrap();
a.run("caret.docStart", json!({})).unwrap();
a.ui.animations = crate::theme::Animations::Off;
let mut h = crate::test_harness::builder().with_size(egui::vec2(1280.0, 800.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
a,
);
steps(&mut h, 4);
let center = h.state().canvas.view_rect().expect("the canvas laid out").center();
let wheel = || egui::Event::MouseWheel {
unit: egui::MouseWheelUnit::Line,
delta: egui::vec2(0.0, -1.0),
phase: egui::TouchPhase::Move,
modifiers: egui::Modifiers::NONE,
source: egui::MouseWheelSource::Wheel,
};
// With animations off, one notch jumps the full document line distance in a single frame.
let start_y = h.state().canvas.view.offset.1;
h.event(egui::Event::PointerMoved(center));
h.event(wheel());
h.app_frame();
let one_notch = h.state().canvas.view.offset.1 - start_y;
assert!(
(one_notch - f64::from(crate::scroll::NOTCH_PX)).abs() < 2.0,
"one mouse-wheel notch should scroll ~{} pt, got {one_notch}",
crate::scroll::NOTCH_PX
);
// With animations on, a single notch eases to the same distance, and a rapid flick accelerates past it.
h.state_mut().ui.animations = crate::theme::Animations::On;
h.state_mut().canvas.view.offset.1 = 0.0;
steps(&mut h, 4);
let eased_start = h.state().canvas.view.offset.1;
h.event(wheel());
steps(&mut h, 30);
let eased_notch = h.state().canvas.view.offset.1 - eased_start;
assert!(
(eased_notch - f64::from(crate::scroll::NOTCH_PX)).abs() < 2.0,
"an eased notch should settle at ~{} pt, got {eased_notch}",
crate::scroll::NOTCH_PX
);
h.state_mut().canvas.view.offset.1 = 0.0;
steps(&mut h, 30);
let flick_start = h.state().canvas.view.offset.1;
for _ in 0..5 {
h.event(wheel());
h.app_frame();
}
steps(&mut h, 40);
let flicked = h.state().canvas.view.offset.1 - flick_start;
assert!(flicked > 5.0 * eased_notch, "a rapid 5-notch flick ({flicked}) should accelerate past 5 single notches ({})", 5.0 * eased_notch);
}
+33 -5
View File
@@ -14,7 +14,14 @@ fn window(a: WordApp) -> H {
/// [`window`] with a chosen step time (the time one frame adds), for gestures whose outcome
/// depends on how long frames last.
fn window_dt(a: WordApp, dt: Option<f32>) -> H {
let mut b = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0));
sized_window(a, egui::vec2(1440.0, 900.0), dt, 6)
}
/// A harness around `a` in a window of `size`, with step time `dt` (the default when `None`),
/// after `settle` frames: a smaller window and fewer frames keep a test that needs little of
/// the window fast.
fn sized_window(a: WordApp, size: egui::Vec2, dt: Option<f32>, settle: usize) -> H {
let mut b = crate::test_harness::builder().with_size(size);
if let Some(dt) = dt {
b = b.with_step_dt(dt);
}
@@ -26,9 +33,7 @@ fn window_dt(a: WordApp, dt: Option<f32>) -> H {
},
a,
);
for _ in 0..6 {
h.app_frame();
}
steps(&mut h, settle);
h
}
@@ -262,12 +267,17 @@ fn ruler_tab_stops_are_set_moved_and_cleared_with_the_pointer() {
/// #1348: an app with one comment ("Original") on some text, its balloon on screen.
fn comment_harness() -> (H, u32) {
comment_harness_in(egui::vec2(1440.0, 900.0), 6)
}
/// [`comment_harness`] in a window of `size`, after `settle` frames.
fn comment_harness_in(size: egui::Vec2, settle: usize) -> (H, u32) {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
a.run("text.insert", json!({"text": "Some text here"})).unwrap();
a.run("select.text", json!({"text": "text"})).unwrap();
let id = a.run("review.newComment", json!({"text": "Original"})).unwrap()["id"].as_u64().unwrap() as u32;
a.run("view.commentsPane", json!({"value": false})).unwrap();
(window_dt(a, Some(1.0 / 60.0)), id)
(sized_window(a, size, Some(1.0 / 60.0), settle), id)
}
/// Click comment `id`'s balloon (from no selected balloon): the card is selected with no edit open (as in Word), then
@@ -408,6 +418,24 @@ fn a_refused_comment_edit_keeps_the_draft() {
assert!(text.contains("Edited"), "the typed text survived the refusal: {text:?}");
}
/// #1348: Escape in a balloon throws the draft away and shows the comment's text again, and leaving the field writes nothing.
#[test]
fn escape_reverts_a_comment_draft() {
// No settle frames of its own (`click_balloon` settles before it clicks) keep the test fast. The window stays
// wide enough for the click on the page's centre to land on the page, not on a balloon.
let (mut h, id) = comment_harness_in(egui::vec2(1440.0, 900.0), 0);
click_balloon(&mut h, id);
type_in(&mut h, "Discarded ");
assert!(draft_text(h.state()).is_some_and(|d| d.contains("Discarded")), "the draft was recorded before Escape");
h.event(egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() });
h.app_frame();
assert_eq!(draft_text(h.state()), None, "the draft is gone");
assert_eq!(comment_text(h.state(), id), "Original", "nothing was written");
leave_field(&mut h);
assert_eq!(h.state().canvas.selected_balloon(), None, "the click on the page left the balloon");
assert_eq!(comment_text(h.state(), id), "Original", "and nothing is written later");
}
/// #3268: clicking a balloon's Reply button, typing a reply and clicking away posts it as a
/// reply comment under the original, not a draft that silently disappears.
#[test]
+58
View File
@@ -425,3 +425,61 @@ fn inspect_lists_recent_documents_as_full_paths() {
let Reply::Done(r) = control::handle(&mut a, &installed(), &req) else { panic!("ui.inspect answers at once") };
assert_eq!(r["result"]["ui"]["recent"], json!([full]), "{r}");
}
/// Quit with a table title still typed in the focused Alt Text field: the root window's close (the built-in Quit)
/// commits the draft and asks Save Changes; `ui.quit` (the app menu's Quit, ⌘Q, the Dock) must do the same (#8790),
/// and asks only once: Don't Save quits.
#[test]
fn quit_commits_the_focused_fields_draft_before_asking() {
use egui::accesskit::Role;
use egui_kittest::kittest::Queryable;
fn caption(a: &WordApp) -> Option<String> {
let focus = &a.session.sel.focus;
let (path, _, _) = focus.path.cell()?;
a.session.doc.table(focus.story, &path)?.props.caption.clone()
}
fn typed_title() -> egui_kittest::Harness<'static, WordApp> {
let mut a = app();
a.run("insert.table", json!({"rows": 1, "cols": 1})).unwrap();
a.session.dirty = false;
a.session.view.alt_text_pane = true;
let mut h = harness(a);
h.get_by_role_and_label(Role::TextInput, "Title:").click();
frames(&mut h, 2);
h.get_by_role_and_label(Role::TextInput, "Title:").type_text("Prices");
frames(&mut h, 2);
assert!(!h.state().session.dirty && caption(h.state()).is_none(), "the title is still a draft in the focused field");
h
}
fn host_close(h: &mut egui_kittest::Harness<'static, WordApp>) {
h.input_mut().viewports.entry(egui::ViewportId::ROOT).or_default().events.push(egui::ViewportEvent::Close);
frames(h, 6);
}
// The root window's close, as the built-in Quit sent it.
let mut h = typed_title();
host_close(&mut h);
let a = h.state();
assert_eq!(prompt(a), Some("saveChanges"), "root close asks about the committed title");
// The app menu's Quit (⌘Q), then the close the host sends once `quit_requested` is set.
let mut h = typed_title();
h.state_mut().run("ui.quit", json!({})).unwrap();
frames(&mut h, 2);
host_close(&mut h);
let a = h.state();
assert!(
prompt(a) == Some("saveChanges") && !a.quit_requested,
"ui.quit lost the typed title: caption={:?} dirty={} quit_requested={}",
caption(a),
a.session.dirty,
a.quit_requested
);
assert_eq!(caption(a).as_deref(), Some("Prices"), "the prompt is about the committed title");
// Don't Save answers the quit: it is not asked again, though the last document stays open and modified.
h.state_mut().run("ui.saveChanges", json!({"answer": "dontSave"})).unwrap();
assert!(h.state().quit_requested, "Don't Save quits");
host_close(&mut h);
assert!(h.state().quit_requested && prompt(h.state()).is_none(), "the answered quit is not asked about again");
}
@@ -167,7 +167,7 @@ pub fn field_kind(name: &str) -> FieldKind {
pub struct FieldForm {
pub category: String,
pub name: String,
/// `\@` picture for date fields.
/// `\@` picture for date fields. Empty uses the field language's default.
pub date_format: String,
/// `\*` value for number fields (empty = none).
pub number_format: String,
@@ -206,7 +206,7 @@ impl FieldForm {
let mut f = FieldForm {
category: FIELD_CATEGORIES.first().copied().unwrap_or("(All)").to_string(),
name: "DATE".into(),
date_format: DATE_FORMATS.first().copied().unwrap_or("M/d/yyyy").to_string(),
date_format: String::new(),
number_format: String::new(),
text_format: String::new(),
typed_text_formats: Vec::new(),
@@ -257,7 +257,7 @@ impl FieldForm {
};
self.style_switches.clear();
if field_kind(name) == FieldKind::Date {
self.date_format = if name == "TIME" { "h:mm am/pm" } else { "M/d/yyyy" }.into();
self.date_format.clear();
}
self.code = self.instruction();
}
@@ -377,10 +377,14 @@ impl FieldForm {
match field_kind(&self.name) {
FieldKind::Date => {
text_field(ui, "field_date", &word("Date formats:"), &mut self.date_format);
let samples: Vec<String> = DATE_FORMATS.iter().map(|p| wordcraft_engine::cmd::insert::format_date(p)).collect();
let current = DATE_FORMATS.iter().position(|p| *p == self.date_format);
let formats: Vec<_> = std::iter::once("").chain(DATE_FORMATS.iter().copied()).collect();
let samples = formats
.iter()
.map(|p| if p.is_empty() { tl!("Default (field language)").to_string() } else { wordcraft_engine::cmd::insert::format_date(p) })
.collect::<Vec<_>>();
let current = formats.iter().position(|p| *p == self.date_format.trim());
if let Some(at) = list_index(ui, &word("Date formats:"), &samples, current).selected
&& let Some(p) = DATE_FORMATS.get(at)
&& let Some(p) = formats.get(at)
{
self.date_format = (*p).to_string();
}
@@ -247,7 +247,7 @@ fn cross_font_recent_symbol_inserts_clicked_character() {
fn field_dialog_builds_the_instruction() {
let a = app();
let mut f = FieldForm::new(&a);
assert_eq!(f.instruction(), r#"DATE \@ "M/d/yyyy" \* MERGEFORMAT"#);
assert_eq!(f.instruction(), r"DATE \* MERGEFORMAT");
f.date_format = "yyyy-MM-dd".into();
f.preserve = false;
assert_eq!(f.instruction(), r#"DATE \@ "yyyy-MM-dd""#);
@@ -275,6 +275,73 @@ fn field_dialog_builds_the_instruction() {
assert!(f.params().is_none());
}
#[test]
fn field_dialog_date_and_time_defaults_follow_the_field_language_on_update() {
use crate::dialogs::host::WordForm;
use wordcraft_doc::InlineObject;
use wordcraft_engine::cmd::{insert::format_date_at_in, local_offset_secs, now_unix};
let locales = [("de-DE", "HH:mm", "dd.MM.yyyy", "04.12.2026"), ("en-US", "h:mm am/pm", "M/d/yyyy", "12/4/2026")];
for (lang, time, date, created) in locales {
let mut a = app();
a.session.doc.core.created = "2026-12-04".into();
a.session.run("review.language", &json!({"lang": lang, "default": true})).unwrap();
let mut form = FieldForm::new(&a);
let mut expected = Vec::new();
let start = now_unix();
for name in ["TIME", "DATE", "CREATEDATE", "SAVEDATE", "PRINTDATE"] {
let picture = if name == "TIME" { time } else { date };
a.run("insert.field", json!({"instr": name})).unwrap();
expected.push((name.to_string(), picture));
form.select(name);
assert!(form.date_format.is_empty(), "{name} starts from the field-language default");
let instruction = format!(r"{name} \* MERGEFORMAT");
assert_eq!(form.final_code(), instruction);
let (command, params) = form.commands().pop().expect("the dialog inserts a field");
a.run(&command, params).unwrap();
expected.push((instruction, picture));
}
for (name, picture) in [("TIME", "HH:mm:ss"), ("DATE", "yyyy-MM-dd")] {
form.select(name);
form.date_format = picture.into();
let (command, params) = form.commands().pop().unwrap();
a.run(&command, params).unwrap();
expected.push((format!(r#"{name} \@ "{picture}" \* MERGEFORMAT"#), picture));
}
let check = |a: &WordApp, from, to| {
let p = a.session.doc.body.first().and_then(|b| b.as_para()).unwrap();
assert_eq!(p.objects.len(), expected.len());
for (object, (instruction, picture)) in p.objects.iter().zip(&expected) {
let InlineObject::Field { instr, result, .. } = object else { panic!("expected {instruction}") };
assert_eq!(instr, instruction);
if instr.starts_with("CREATEDATE") {
assert_eq!(result, created);
} else {
// The clock can roll over while the command is running.
assert!(
(from..=to).any(|t| *result == format_date_at_in(picture, Some(lang), t, local_offset_secs(t))),
"{lang}: {instr} showed {result:?}, expected {picture}"
);
}
}
};
check(&a, start, now_unix());
let p = a.session.doc.para_mut(wordcraft_doc::StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap();
for o in &mut p.objects {
if let InlineObject::Field { result, .. } = o {
*result = "stale".into();
}
}
let start = now_unix();
a.run("references.updateFields", json!({"all": true})).unwrap();
check(&a, start, now_unix());
}
}
/// Text fields take a capitalization Format: each choice writes its `\*` switch before
/// `\* MERGEFORMAT`, after the field's own arguments and switches, and (none) writes none.
#[test]
+3
View File
@@ -481,6 +481,9 @@ pub struct WordApp {
/// Escape may leave full screen. Read before anything handles the frame's keys.
escape_free: bool,
pub quit_requested: bool,
/// A quit ([`WordApp::quit`]) went ahead with nothing unsaved. The root close that ends it checks once more,
/// because a focused field's typed text commits to its document only on that close (#8790).
pub(crate) quit_recheck: bool,
pub autosave: bool,
/// The document's fonts that aren't installed, for the status bar and the font box, and the
/// layout they were read from.
+35 -11
View File
@@ -50,6 +50,39 @@ fn anchor_skips_rects_scrolled_offscreen_and_clips_partial_ones() {
assert_eq!(visible_anchor([nan], clip, false), None);
}
/// #7317: a viewport narrower than the bar still places the mini toolbar inside the canvas and viewport on all four sides.
#[test]
fn a_viewport_narrower_than_the_bar_still_yields_a_rect() {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
a.run("text.insert", json!({"text": "The quick brown fox"})).unwrap();
a.run("select.text", json!({"text": "quick"})).unwrap();
let viewport = Rect::from_min_size(pos2(0.0, 0.0), Vec2::new(220.0, 480.0));
let mut h = crate::test_harness::builder().with_size(viewport.size()).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
a,
);
steps(&mut h);
let bold = member(&h, "Bold").expect("mini toolbar Bold inside canvas");
// The framework's selection task bar is the group named "Formatting" that holds the bar's Bold.
let bar = h
.query_all_by_role(Role::Group)
.filter(|n| n.accesskit_node().label().as_deref() == Some("Formatting"))
.map(|n| n.rect())
.find(|r| r.contains_rect(bold))
.expect("the selection bar is shown around its Bold");
assert!(bar.is_finite() && bar.is_positive(), "bar placed at {bar:?}");
for (area, name) in [(canvas(&h), "canvas"), (viewport, "narrow viewport")] {
assert!(bar.left() >= area.left(), "bar's left edge stays inside the {name}: {bar:?} vs {area:?}");
assert!(bar.top() >= area.top(), "bar's top edge stays inside the {name}: {bar:?} vs {area:?}");
assert!(bar.right() <= area.right(), "bar's right edge stays inside the {name}: {bar:?} vs {area:?}");
assert!(bar.bottom() <= area.bottom(), "bar's bottom edge stays inside the {name}: {bar:?} vs {area:?}");
}
}
/// The whole window over a document with `pick` selected, run until the bar is up.
fn bar_over(pick: &str) -> H {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
@@ -59,7 +92,8 @@ fn bar_over(pick: &str) -> H {
}
/// `bar_over` for an app whose document and selection are already set up.
fn bar_over_app(a: WordApp) -> H {
fn bar_over_app(mut a: WordApp) -> H {
a.font_catalog.get_or_insert_with(crate::test_harness::fixed_catalog);
let mut h = crate::test_harness::builder().with_size(Vec2::new(1440.0, 900.0)).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
@@ -352,16 +386,6 @@ fn hovering_a_bar_member_previews_its_command() {
h.get_by_label("20").rect().center()
}
Member::Font => {
// `FontPicker` scans `Catalog::global()` on a background thread; wait until ready so the
// chevron click isn't ignored while the picker is still disabled in a fresh test process.
let catalog = craft::font_manager::Catalog::global();
catalog.scan_in_background();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while !catalog.is_ready() && std::time::Instant::now() < deadline {
std::thread::sleep(std::time::Duration::from_millis(10));
}
assert!(catalog.is_ready(), "font catalog finished scanning");
steps(&mut h);
let b = font_box(&h);
let c = canvas(&h);
// A click on a Plain picker's name only selects it (craft-libs #3103); the chevron opens the list.
+6 -1
View File
@@ -86,7 +86,12 @@ fn tabs(app: &mut WordApp, ui: &mut Ui) {
.shown(shown)
.show_items(ui, &places(&labels), &mut |key, _| Tab::new(labels.get(*key).map(|label| label.1.clone()).unwrap_or_default()));
if let Some((key, _)) = out.picked.and_then(|k| TABS.get(k)) {
// A click or the keyboard arrives as a selection event; `out.picked` is only the overflow menu's pick.
let clicked = out.response.events.iter().rev().find_map(|event| match event {
CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } => keys.last().copied(),
_ => None,
});
if let Some((key, _)) = out.picked.or(clicked).and_then(|k| TABS.get(k)) {
app.ui.nav_tab = (*key).into();
}
}
+6 -3
View File
@@ -204,8 +204,9 @@ pub(super) fn home(row: &mut RibbonRow<'_>, app: &mut WordApp) {
if let Some(f) = out.picked {
let _ = app.run("format.font", json!({"name": f}));
}
let mut size = st.get("size").and_then(Value::as_f64).map(format_font_size).unwrap_or_default();
let out = craft::ui::pickers::ComboBox::new(tl!("Font Size").to_string(), Bind::bound(&mut size), font_size_entries())
// Given, not bound: a bound local rebuilt from the engine each frame cancels the typed draft (#8921).
let size = st.get("size").and_then(Value::as_f64).map(format_font_size).unwrap_or_default();
let out = craft::ui::pickers::ComboBox::new(tl!("Font Size").to_string(), Bind::given(size), font_size_entries())
.tooltip(tl!("Font Size").to_string())
.show(ui);
painted_ibeam_over(ui, &out.edit.response);
@@ -554,7 +555,9 @@ mod tests {
h.app_frame();
assert!(!tooltip_visible(&h), "just focused: hint should not show before tooltip delay");
let delay_frames = (craft::ui::contract::tooltip::DELAY / 0.25).ceil() as usize + 3;
let step_dt = f64::from(h.ctx.input(|i| i.predicted_dt));
assert!(step_dt > 0.0, "harness step_dt must be positive, got {step_dt}");
let delay_frames = (craft::ui::contract::tooltip::DELAY / step_dt).ceil() as usize + 3;
for _ in 0..delay_frames {
h.step();
}
+30
View File
@@ -413,6 +413,11 @@ fn smart_art_design_layouts_are_one_strip_and_size_is_labelled() {
/// control lies inside its group's access node.
#[test]
fn ribbon_groups_fit_above_their_labels() {
if crate::i18n::Lang::all().any(|l| l.code() == "ar")
&& crate::test_harness::skip_without_embedded_script("ribbon::tests::ribbon_groups_fit_above_their_labels", "Arab")
{
return;
}
fn rects(node: &egui_kittest::Node<'_>, out: &mut Vec<egui::Rect>) {
for child in node.children() {
// The framework's parts (a split button's arrow, a field's adornments) can be nodes with no
@@ -471,6 +476,11 @@ fn ribbon_groups_fit_above_their_labels() {
/// Language Preferences… opens Options › Language, and French text shows by name, checked.
#[test]
fn language_menu_reaches_every_language() {
if crate::i18n::Lang::all().any(|l| l.code() == "ar")
&& crate::test_harness::skip_without_embedded_script("ribbon::tests::language_menu_reaches_every_language", "Arab")
{
return;
}
let app = WordApp::new(Session::new(wordcraft_doc::Document::from_text("Bonjour")), crate::Services::default());
let mut h = tab_harness(app, "Review");
click_button(&mut h, "Language");
@@ -1624,3 +1634,23 @@ fn the_numbering_menu_offers_a_dot_b_dot_c_dot() {
crate::test_harness::frames(&mut h, 3);
assert_eq!(label(&mut h).as_deref(), Some("A."), "another preset changes the list");
}
/// #8921: a size typed in the Font Size box and committed with Enter formats the selection.
#[test]
fn a_size_typed_in_the_font_size_box_formats_the_selection() {
use egui::accesskit::Role;
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::from_text("Sample\n\nafter")), crate::Services::default());
app.run("select.all", json!({})).unwrap();
let mut h = tab_harness(app, "Home");
h.get_all_by_role(Role::TextInput).find(|n| n.value().is_some_and(|v| v.trim().parse::<f64>().is_ok())).expect("the font size box").focus();
crate::test_harness::frames(&mut h, 2);
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
crate::test_harness::frames(&mut h, 2);
h.event(egui::Event::Text("15".into()));
crate::test_harness::frames(&mut h, 2);
h.key_press(egui::Key::Enter);
crate::test_harness::frames(&mut h, 3);
let st = wordcraft_engine::cmd::format::cached_state(&h.state().session);
assert_eq!(st.get("size").and_then(Value::as_f64), Some(15.0));
}
+5 -1
View File
@@ -1,5 +1,9 @@
//! The user's scrolling-speed choice (issue #6146). The wheel and touchpad themselves are scrolled by the
//! framework's canvas navigation; this module keeps the setting and its multipliers.
//! framework's canvas navigation; this module keeps the setting, the document wheel notch, and its multipliers.
/// Screen points one mouse-wheel notch scrolls at 100% zoom: about three lines of body text,
/// like other desktop apps (the framework's default canvas line is 16).
pub const NOTCH_PX: f32 = 56.0;
/// The user's choice for scrolling speed, relative to the platform's normal speed (#6146).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
+5
View File
@@ -50,6 +50,11 @@ pub(crate) struct ResizeDrag {
}
impl ResizeDrag {
/// Started on a ruler marker.
pub(crate) fn on_ruler(&self) -> bool {
self.ruler
}
/// Who makes up a column border's move, by the keys held: Ctrl the columns on the
/// right; Shift nobody on the page but the neighbour on a ruler marker, which works the other
/// way round; else the neighbour on the page and nobody on the ruler. The one place the key rule lives.
+57
View File
@@ -169,3 +169,60 @@ pub(crate) fn frames(h: &mut egui_kittest::Harness<'_, crate::WordApp>, n: usize
frame(h);
}
}
/// A font catalog scanned synchronously from the bundled `assets/fonts/` directory, with no
/// host system fonts or background font service.
pub(crate) fn fixed_catalog() -> std::sync::Arc<craft::font_manager::Catalog> {
use craft::font_manager::Catalog;
use craft::font_manager::craft_font_catalog::{FontEnv, Os};
let env = FontEnv { os: Os::None, ..Default::default() };
let catalog = std::sync::Arc::new(Catalog::new(env).with_font_service(false));
catalog.set_app_dirs(vec![std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts")]);
catalog.rescan();
assert!(catalog.is_ready(), "fixed font catalog scanned synchronously");
assert!(catalog.families().iter().any(|f| f == "Inter"), "fixed catalog loaded assets/fonts");
catalog
}
/// Evaluate whether a test missing an embedded `script` face should skip under
/// `CRAFT_FONTS_REQUIRED` (`None` / `""` skips, `"1"` fails, any other value fails naming the
/// variable and accepted values).
fn should_skip_missing_script(test: &str, script: &str, required: Option<&str>) -> bool {
match required {
None | Some("") => {
eprintln!("SKIPPED ({test}): no embedded {script} face in CRAFT_FONTS (set CRAFT_FONTS_DIR)");
true
}
Some("1") => panic!("{test}: missing embedded {script} face in CRAFT_FONTS (CRAFT_FONTS_REQUIRED=1)"),
Some(other) => panic!("{test}: invalid CRAFT_FONTS_REQUIRED={other:?}; accepted values are empty/unset (skip) or \"1\" (require)"),
}
}
/// Skip `test` when no embedded `craft-fonts` face covers `script`, unless `CRAFT_FONTS_REQUIRED`
/// requires or rejects the value.
pub(crate) fn skip_without_embedded_script(test: &str, script: &str) -> bool {
if crate::app::fonts::CRAFT_FONTS.iter().any(|f| f.has_script(script)) {
return false;
}
let required = std::env::var("CRAFT_FONTS_REQUIRED").ok();
should_skip_missing_script(test, script, required.as_deref())
}
#[cfg(test)]
mod tests {
use super::should_skip_missing_script;
#[test]
fn craft_fonts_required_controls_skip_and_rejects_unknown_values() {
assert!(should_skip_missing_script("t", "Arab", None));
assert!(should_skip_missing_script("t", "Arab", Some("")));
let required_err = std::panic::catch_unwind(|| should_skip_missing_script("t", "Arab", Some("1"))).unwrap_err();
let required_msg = required_err.downcast_ref::<String>().map(String::as_str).unwrap_or("");
assert!(required_msg.contains("CRAFT_FONTS_REQUIRED=1"), "{required_msg}");
let invalid_err = std::panic::catch_unwind(|| should_skip_missing_script("t", "Arab", Some("yes"))).unwrap_err();
let invalid_msg = invalid_err.downcast_ref::<String>().map(String::as_str).unwrap_or("");
assert!(invalid_msg.contains("CRAFT_FONTS_REQUIRED") && invalid_msg.contains("\"1\""), "{invalid_msg}");
}
}
+2 -2
View File
@@ -814,8 +814,8 @@ fn ctrl_wheel_zoom_keeps_the_place_under_the_pointer() {
modifiers,
source: egui::MouseWheelSource::Unknown,
};
// Away from the caret, several pages down (a wheel line scrolls less under the framework's page view).
for _ in 0..240 {
// Away from the caret, several pages down.
for _ in 0..40 {
frame(&mut a, vec![wheel(-1.0, egui::Modifiers::NONE)]);
}
for _ in 0..60 {
+15
View File
@@ -470,3 +470,18 @@ fn find_replace_and_go_to_keys_like_word() {
assert_eq!(h.state().ui.nav_tab, "results", "Find leaves Pages to show the selected-text matches");
assert_eq!(h.state().session.find.results.len(), 2);
}
/// #8945: clicking a Navigation pane tab shows that view (the tab strip's selection event, not its overflow pick).
#[test]
fn nav_pane_tabs_switch_on_click() {
let mut h = crate::test_harness::builder().with_size(egui::vec2(800.0, 500.0)).build_eframe(|_| app());
h.state_mut().session.view.nav_pane = true;
for _ in 0..2 {
h.step();
}
for (label, key) in [("Pages", "pages"), ("Results", "results"), ("Headings", "headings")] {
h.get_by_role_and_label(egui::accesskit::Role::Tab, label).click();
h.run();
assert_eq!(h.state().ui.nav_tab, key);
}
}
+1 -13
View File
@@ -1,8 +1,5 @@
use std::path::Path;
use std::sync::Arc;
use craft::font_manager::Catalog;
use craft::font_manager::craft_font_catalog::{FontEnv, Os};
use craft::font_manager::missing::MissingFontsWords;
use craft::host::{Host, PickKind, ScriptedFiles};
use craft::ui::buttons::IconButton;
@@ -13,18 +10,9 @@ use egui_kittest::kittest::{By, NodeT, Queryable};
use serde_json::{Value, json};
use wordcraft_engine::Session;
use crate::test_harness::fixed_catalog;
use crate::{Services, WordApp};
fn fixed_catalog() -> Arc<Catalog> {
let env = FontEnv { os: Os::None, ..Default::default() };
let catalog = Arc::new(Catalog::new(env).with_font_service(false));
catalog.set_app_dirs(vec![Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts")]);
catalog.rescan();
assert!(catalog.is_ready(), "fixed font catalog scanned synchronously");
assert!(catalog.families().iter().any(|f| f == "Inter"), "fixed catalog loaded assets/fonts");
catalog
}
fn open_ribbon_font_box(h: &mut egui_kittest::Harness<'static, WordApp>) {
h.get_by_role_and_label(Role::ComboBox, "Font").click();
h.run_steps(1);
+1
View File
@@ -176,6 +176,7 @@ impl WordApp {
applied_editing: _,
frame_ms: _,
quit_requested: _,
quit_recheck: _,
autosave: _,
zotero: _,
ctx: _,
+8 -1
View File
@@ -254,11 +254,18 @@ impl WordApp {
/// Quit the app (the app menu's Quit): ask about every document with unsaved work, each in
/// its window, as [`WordApp::close_requested`] does. True when the app may quit now; the
/// host closes it once `quit_requested` is set.
/// host closes it once `quit_requested` is set. The text typed in a focused field commits
/// only on that close, so a quit that found nothing unsaved checks once more there and asks
/// then if the text left something unsaved: a true answer can still turn into a prompt.
pub fn quit(&mut self) -> bool {
// A quit already pending: leave `quit_recheck` for the host's close, which a second quit must not use up.
if self.quit_requested && !self.printing.busy() {
return true;
}
let go = self.close_requested();
if go {
self.quit_requested = true;
self.quit_recheck = true;
}
go
}
+15 -9
View File
@@ -1089,13 +1089,19 @@ fn new_document_cascade_skips_ineligible_recent_window_to_earlier_predecessor()
let root_client = egui::vec2(800.0, 600.0);
let root_outer = egui::Rect::from_min_size(root_origin, root_client + egui::vec2(16.0, 38.0));
let root_inner = egui::Rect::from_min_size(root_origin + egui::vec2(8.0, 30.0), root_client);
let valid = egui::Rect::from_min_size(egui::pos2(200.0, 220.0), egui::vec2(500.0, 400.0));
let zero = egui::Rect::from_min_size(egui::pos2(200.0, 220.0), egui::Vec2::ZERO);
let infinite_size = egui::Rect::from_min_size(egui::pos2(200.0, 220.0), egui::vec2(f32::INFINITY, 400.0));
let child_origin = egui::pos2(200.0, 220.0);
let child_client = egui::vec2(700.0, 520.0);
let child_outer = egui::Rect::from_min_size(child_origin, child_client + egui::vec2(12.0, 34.0));
let child_inner = egui::Rect::from_min_size(child_origin + egui::vec2(6.0, 28.0), child_client);
let zero = egui::Rect::from_min_size(child_origin, egui::Vec2::ZERO);
let infinite_size = egui::Rect::from_min_size(child_origin, egui::vec2(f32::INFINITY, 400.0));
for (label, child_inner, child_outer) in
[("zero outer", Some(valid), Some(zero)), ("zero inner", Some(zero), Some(valid)), ("infinite outer size", Some(valid), Some(infinite_size))]
{
for (label, inner, outer, expected_client, expected_origin) in [
("valid child", Some(child_inner), Some(child_outer), child_client, child_origin),
("zero outer", Some(child_inner), Some(zero), root_client, root_origin),
("zero inner", Some(zero), Some(child_outer), root_client, root_origin),
("infinite outer size", Some(child_inner), Some(infinite_size), root_client, root_origin),
] {
let mut rig = Rig::new();
let mut a = app("First draft");
rig.kit.root_info(ViewportInfo { inner_rect: Some(root_inner), outer_rect: Some(root_outer), focused: Some(true), ..Default::default() });
@@ -1108,7 +1114,7 @@ fn new_document_cascade_skips_ineligible_recent_window_to_earlier_predecessor()
a.run("file.new", json!({})).unwrap();
assert_eq!(a.window_count(), 2);
rig.kit.root_info(ViewportInfo { inner_rect: Some(root_inner), outer_rect: Some(root_outer), focused: Some(false), ..Default::default() });
rig.kit.child_info(ViewportInfo { inner_rect: child_inner, outer_rect: child_outer, focused: Some(true), ..Default::default() });
rig.kit.child_info(ViewportInfo { inner_rect: inner, outer_rect: outer, focused: Some(true), ..Default::default() });
for _ in 0..3 {
rig.frame_with_reported_info(&mut a, Vec::new(), Vec::new());
}
@@ -1118,8 +1124,8 @@ fn new_document_cascade_skips_ineligible_recent_window_to_earlier_predecessor()
let third_title = a.window_title();
rig.frame_with_reported_info(&mut a, Vec::new(), Vec::new());
let builder = rig.builders.into_iter().find(|b| b.title.as_ref() == Some(&third_title)).expect("the third document opened a native window");
assert_eq!(builder.inner_size, Some(root_client), "{label}: skipped ineligible child to earlier root client size");
assert_eq!(builder.position, Some(root_origin + egui::Vec2::splat(step)), "{label}: skipped ineligible child to earlier root origin");
assert_eq!(builder.inner_size, Some(expected_client), "{label}: third window client size");
assert_eq!(builder.position, Some(expected_origin + egui::Vec2::splat(step)), "{label}: third window origin");
}
}
File diff suppressed because one or more lines are too long
+2 -1
View File
@@ -86,7 +86,7 @@ Bullets and Numbering decide whether to toggle off from the selected paragraphs'
|---|---|---|
| `* item` Enter Enter `text` | the second Enter ends the list; `text` is a **Normal** paragraph (no list indent left behind) | `enter_twice_after_a_list_item_ends_the_list`, `the_paragraph_after_a_list_is_normal_text` |
| … Enter ×3, ×4 | each further Enter adds a blank Normal paragraph (never swallowed) | `more_enters_after_a_list_make_blank_paragraphs` |
| Enter on an empty **nested** item | moves it up one level; only a top-level empty item leaves the list. The same when the list comes from the paragraph style (List Number 2 in a Word file, #2143) | `enter_on_an_empty_nested_item_moves_it_up_a_level_first`, `enter_on_an_empty_item_numbered_by_its_style_moves_it_up_a_level` |
| Enter on an empty **nested** item | moves it up one level and uses that level's indentation, dropping direct leading and first-line indents (#8929). Only a top-level empty item leaves the list. The same applies when numbering comes from the paragraph style (#2143). | `enter_on_an_empty_nested_item_moves_it_up_a_level_first`, `enter_on_an_empty_item_numbered_by_its_style_moves_it_up_a_level`, `enter_outdents_an_empty_list_item_and_drops_direct_indents` |
| Enter (Return) on a selected picture or shape, inline or floating | nothing: the object stays, still selected, and no paragraph is added, however many times it is pressed (Word for Mac, observed 2026-10-24; #4126). On a selected text box, Enter puts the caret in its text | `enter_on_a_selected_picture_does_nothing` |
| Shift+Enter (⇧Return), Insert › Page Break (⌘Return) on a selected picture or shape | the break goes in front of it (in front of a content control around it) and the object stays selected: each Shift+Enter moves an inline picture down a line (with a floating picture, the text after its anchor), and a page break moves it to the next page (Word for Mac, observed 2026-10-24; #4126). A column break does the same (not observed) | `a_break_on_a_selected_picture_goes_in_front_of_it`, `a_break_on_a_picture_in_a_picture_control_keeps_the_picture_selected` |
| `* ` Enter (nothing typed) | list cancelled, Normal paragraph | `enter_right_after_starting_a_list_cancels_it` |
@@ -169,6 +169,7 @@ including in headers and notes when the body uses balloons. Shift extends across
| Backspace, then type | the typed text takes the formatting of the character Backspace deleted, not of the one now left of the caret: in `Abc abc` with `Abc` bold, Backspace after the space then `X` gives a plain X; Backspace after a bold letter that follows a plain space gives a bold X. The Bold button shows it before typing, also with the caret inside a word (where it otherwise shows the word). Several Backspaces: the last deleted character's formatting. A Backspace that changes nothing (at the start of the document) keeps it, and keeps formatting set at the caret too. Typing goes on with it (in `ab Cd` with `C` bold, Backspace after the C then `YX` gives a bold YX), and undoing that typing brings it back. Moving the caret any way drops it, not only with the caret keys: a click elsewhere (also one that comes back to the same place), Go To, Find (typing over the found word takes that word's formatting; a Find with no match keeps it) and a paste, whose text never takes it (formatted or plain; a paste with nothing on the clipboard keeps it); typing then takes the formatting where the caret is. A command that is refused (a Backspace into a content control locked against editing) keeps it, and formatting set at the caret too. Forward Delete, a deleted selection, a paragraph join, an object or a break carry nothing. With Track Changes on Backspace carries it too: the character stays, marked deleted (or goes, when it is the author's own tracked insertion), and the typed text is a tracked insertion with that formatting, never marked deleted; moving the caret away and back drops it. Ctrl+Backspace that deletes a word or joins paragraphs drops formatting carried by an earlier Backspace (one that deletes nothing, at the start of the document, keeps it, like Backspace). Undo takes the carried formatting back with the Backspace. Observed in Word for Windows (#6518) | `typing_after_backspace_takes_the_deleted_characters_formatting`, `backspace_formatting_is_dropped_by_a_caret_move_and_delete_does_not_carry`, `backspace_at_the_document_start_keeps_waiting_formatting`, `ctrl_backspace_at_the_document_start_keeps_waiting_formatting`, `backspace_formatting_is_not_kept_past_a_paste`, `backspace_formatting_is_not_kept_past_find_or_go_to`, `backspace_formatting_survives_a_paste_of_an_empty_clipboard`, `backspace_formatting_is_not_kept_past_a_direct_caret_move_and_back`, `a_refused_backspace_keeps_the_formatting_waiting_at_the_caret`, `backspace_formatting_follows_typing_and_comes_back_with_undo`, `tracked_backspace_carries_the_deleted_characters_formatting` |
| select text right to left (from its end), type | the new text takes the first selected character's formatting (font, size…), as with a selection made left to right; not the text's before it (#2879) | `typing_over_backward_selection_keeps_its_font` |
| Down / Up (↓ / ↑) from a line beside a table | into the table's nearest row: the cell under the caret, or the nearest one when the caret is left or right of the cells' text (the start of the line above a table is left of the first cell's text); never past the table to the paragraph beyond it | `down_and_up_from_a_line_start_beside_a_table_go_into_it` |
| Arrows in vertical text (top-to-bottom, lines stacking leftwards, #8986) | Up / Down step to the previous / next character along the line; Left / Right go to the next / previous line (the column to the left / right), keeping the distance along the line. In bottom-to-top text Up steps forward and Left goes to the previous line. Left / Right stay within the text flow of the caret (a vertical section's paragraphs, or one table cell's): at its first or last line (a table cell's only line, say) they step along the text, as in horizontal text | `turned_line_steps_to_the_adjacent_column`, `turned_line_stays_in_its_table_cell` (layout) |
| Alt+Shift+Up / Down (⌃⇧↑ / ⌃⇧↓) | the paragraphs the selection touches swap with the paragraph above / below, keeping style and list membership; the selection moves with them; one undo step. A selection ending at the start of a paragraph doesn't take it along. Refused at the top or bottom of the story or cell, next to a table and across a section break | `alt_shift_down_then_up_moves_a_paragraph_and_back_and_undoes` |
| Alt+Shift+Left / Right (⌃⇧← / ⌃⇧→) | Promote / Demote: a heading goes up or down one level (Heading 1 and Heading 9 are the ends); promoted body text becomes a heading at the level of the heading before it; a list item changes level like Shift+Tab / Tab | `alt_shift_left_and_right_promote_and_demote_headings_and_list_items` |
| Outline view: Alt+Shift+Up / Down, Left / Right | as above, but a collapsed heading takes what is hidden under it along: moving passes whole shown paragraphs with their hidden content; promote/demote shifts the hidden subheadings too | `outline_collapse_hides_descendants_and_expand_restores` |
+17 -3
View File
@@ -337,9 +337,23 @@ mod tests {
#[test]
fn wasm_summary_lists_only_crates_with_checked_test_targets() {
let set = vec!["wordcraft-geom".to_string(), "wordcraft-doc".to_string(), "wordcraft-layout".to_string(), "wordcraft-ui-egui".to_string()];
let included = "wordcraft-geom".to_string();
let excluded: Vec<String> = WASM_TEST_EXCLUDED.iter().map(|s| format!("wordcraft-{s}")).collect();
let mut set = vec![included.clone()];
set.extend(excluded.iter().cloned());
let test_set = wasm_test_set(&set);
assert_eq!(test_set, vec!["wordcraft-geom", "wordcraft-layout"]);
assert_eq!(wasm_summary(&set, &test_set), "wasm32-unknown-unknown check: ok (4 crates, 2 test crates: wordcraft-geom, wordcraft-layout)");
assert!(test_set.contains(&included));
for pkg in &excluded {
assert!(!test_set.contains(pkg), "{pkg} should be excluded from wasm_test_set");
}
let summary = wasm_summary(&set, &test_set);
for pkg in &test_set {
assert!(summary.contains(pkg), "summary should include {pkg}: {summary}");
}
for pkg in &excluded {
assert!(!summary.contains(pkg), "summary should omit excluded {pkg}: {summary}");
}
}
}