Compare commits

..
Author SHA1 Message Date
Martin Ball 8f627faed0 Merge remote-tracking branch 'origin/fix/8811-status-ink' into test/overnight-5dec 2026-12-05 08:48:48 +00:00
Martin Ball 8cc1912dc0 test: trial repin to craft-libs test/overnight-5dec (18499ec3) 2026-12-05 08:48:48 +00:00
Martin BallandClaude Opus 5.5 0eda97fe8c #8811: the status bar's muted-ink override returns nothing
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCXNomWeGUu3duixKdm
2026-12-05 08:48:41 +00:00
Martin Ball db301eb1ba Merge remote-tracking branch 'origin/fix/8980-vertical-ime-preedit' into test/overnight-5dec
; Conflicts:
;	crates/ui-egui/src/canvas/tests.rs
2026-12-05 08:41:38 +00:00
Martin Ball ab05f3f6d4 Merge remote-tracking branch 'origin/fix/8855-touchpad-glide' into test/overnight-5dec
; Conflicts:
;	crates/ui-egui/src/canvas.rs
2026-12-05 08:41:28 +00:00
Martin Ball 440243e3d7 Merge remote-tracking branch 'origin/fix/8969-flatpak-kde-clipboard' into test/overnight-5dec 2026-12-05 08:41:20 +00:00
Martin Ball 18369a756e Merge remote-tracking branch 'origin/fix/8811-status-ink' into test/overnight-5dec 2026-12-05 08:41:20 +00:00
Martin Ball e8b2c87781 Merge remote-tracking branch 'origin/fix/8853-interface-scale' into test/overnight-5dec 2026-12-05 08:41:18 +00:00
Martin Ball bf556a1cd6 Merge remote-tracking branch 'origin/fix/9111-print-preview-sheet-edge' into test/overnight-5dec 2026-12-05 08:41:18 +00:00
Martin Ball 0bcb856280 Merge remote-tracking branch 'origin/fix/8872-vmerge-page-split' into test/overnight-5dec 2026-12-05 08:41:16 +00:00
aiongg c555672b56 Merge pull request #8416 from davidmann4/feat/agents-open-window
feat(automation): agents in the open window through the ArtCraft Launcher's switch
2026-12-05 02:35:57 -05:00
Martin BallandClaude Sonnet 5.5 c1a23c6a1f #8872: a merge's continuing fill no longer covers the cell's side borders
The continuation fill was pushed after the row's items, so it painted over the inner half of the side and bottom borders. Fills now go first, the opening top rules last.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-05 07:19:01 +00:00
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 a4ad65c372 docs(layout-parity): fix rows_outrank_grid_total module path (#9076) 2026-12-05 03:12:17 -03:00
Martin BallandClaude Sonnet 5.5 04a3c76c10 #8872: a merged cell keeps its fill across a column break and a page start
A column change now starts a merge continuation like a page change; closing a page
trims only items this table placed there; a row laid out alone for a page start
still knows the restart fills of earlier rows.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-05 06:04:47 +00:00
Martin BallandClaude Opus 5.5 fbe41cca76 #9111: no test for a pixel loop; an empty sheet image is left alone
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCXNomWeGUu3duixKdm
2026-12-05 05:55:54 +00:00
Martin BallandClaude Sonnet 5.5 553f0058ee #9111: Print preview shows the sheet's edge, so a portrait page no longer looks like a landscape sheet
The preview pane's background is as white as the paper, so the sheet's own shape was invisible: a portrait sheet centred in a wide pane read as a landscape sheet with the page off to one side. The sheet and orientation logic were correct (Auto keeps the page's own orientation, page centred). The drawn sheet now has a one-pixel grey edge.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCXNomWeGUu3duixKdm
2026-12-05 05:50:55 +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
Martin BallandClaude Sonnet 5.5 f086af023f #8980: IME composition in vertical text runs down the line at the text size
The composition was drawn horizontally in the interface font whenever the
caret lay in turned text (typing_style and the caret were horizontal-only).
Caret now carries the line's direction and typing_style serves turned text;
the canvas stacks the composition's characters upright down (tbRl) or up
(btLr) the line at the run's size, and reports the column it fills as the
candidate window rect.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCXNomWeGUu3duixKdm
2026-12-05 04:35:45 +00:00
Martin BallandClaude Sonnet 5.5 f9ff36d67c #8811: status bar page, word count and language read in the muted ink again
Cause: the craft-ui port drew the readouts in full ink; v0.19.1 used text_dim.
Fix: set AfterInk::Muted around the readouts; craft-libs now honours it on ghost buttons
(depends on the craft-libs PR, builds after the repin).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCXNomWeGUu3duixKdm
2026-12-05 04:26:00 +00: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] 84118adcf9 Merge pull request #9088 2026-12-05 03:27:47 +00:00
autocraft-bot[bot] 8a7fef3ec6 Merge pull request #9061 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
Martin BallandClaude Sonnet 5.5 ce2b01e005 #8855: touchpad scrolling glides on after the fingers lift again on Linux
The v0.19.1 scroll code synthesised touchpad momentum where the system sends none. The craft-ui port moved wheel handling to craft-libs' canvas, whose touchpad_glide option is off by default and was never enabled. Enable it on the platforms v0.19.1 used (not macOS, Windows, web).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCXNomWeGUu3duixKdm
2026-12-05 03:15:27 +00:00
batistalucasv 1129aa51f2 Replace All: skip hidden stories via Document::shown_stories (#9064) 2026-12-05 00:08:38 -03:00
Martin BallandClaude Sonnet 5.5 4ad6272409 #8975: Ctrl/Cmd over a link shows the pointing hand
Cause: the page tool's cursor never considered links; Word shows the hand when Ctrl/Cmd is held over one (a click then follows it). Link style (Hyperlink char style) was already applied by insert.link and renders underlined.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCXNomWeGUu3duixKdm
2026-12-05 03:04:15 +00: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
Martin BallandClaude Sonnet 5.5 0739eb7379 #8969: Flatpak on KDE Plasma Wayland can paste again
Cause: KWin has no data-control protocol, arboard falls back to X11, but fallback-x11 gives the sandbox no X11 under Wayland.
Fix: grant --socket=x11 beside wayland so the XWayland clipboard bridge is reachable. Interim: a real wl_data_device clipboard belongs in craft-libs.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCXNomWeGUu3duixKdm
2026-12-05 02:33:00 +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
autocraft-bot[bot] 7b213b331b Merge pull request #9028 2026-12-05 02:00:10 +00:00
batistalucasv d62508ca40 Docs: document stale_grid_widths handling of missing or mismatched tblGrid (#8924) 2026-12-04 23:00:10 -03: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
autocraft-bot[bot] fbde8c47a3 Merge pull request #9024 2026-12-05 01:57:02 +00:00
batistalucasv 481207f29d docs: update typing-parity Tab / Shift+Tab row (#8933) 2026-12-04 22:57:02 -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] 4add275c07 Merge pull request #9022 2026-12-05 01:53:36 +00:00
batistalucasv 5f39de62f8 Tests: set en-US explicitly in Change Case English control check (#8953) 2026-12-04 22:53:36 -03:00
autocraft-bot[bot] 830065bd62 Merge pull request #9021 2026-12-05 01:53:08 +00:00
batistalucasv 31b2be75f4 Windows: test zero-size, non-finite, and skipped cascade predecessors (#8944) 2026-12-04 22:53:08 -03: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
autocraft-bot[bot] 96b8c1c58b Merge pull request #9020 2026-12-05 01:51:30 +00:00
batistalucasv de30199f1f test(ui-egui): cover multi-candidate srcset clipboard offers (#8941) 2026-12-04 22:51:30 -03:00
autocraft-bot[bot] 14ed0bfa28 Merge pull request #3309
With AutoCraft's conflict resolution e8108806.
2026-12-05 01:49:31 +00:00
autocraft-bot[bot] bf54864f37 Merge pull request #9019 2026-12-05 01:49:31 +00:00
batistalucasv 61893e1950 test(docx): assert full run emphasis mark list in run_props 2026-12-04 22:49:31 -03:00
batistalucasv b6777d494c test(wordcraft-cli): move reproducible_pdf integration tests into tests/it 2026-12-04 22:38:32 -03:00
autocraft-bot[bot] 434d9b223e Merge pull request #9016 2026-12-05 01:38:10 +00:00
autocraft-bot[bot] 802a2e2120 Merge pull request #9015 2026-12-05 01:38:10 +00:00
batistalucasv 83f437ec89 Tests: restore selection-based mixed-run Change Case check (#8952) 2026-12-04 22:38:10 -03:00
batistalucasv 3bae0c1cdb test(engine): pass whole: false in staged table-end select.all test (#8961) 2026-12-04 22:38:04 -03:00
autocraft-bot[bot] aa2c33e5a9 Merge pull request #9013 2026-12-05 01:32:46 +00:00
autocraft-bot[bot] c26f801e20 Merge pull request #9012 2026-12-05 01:32:46 +00:00
batistalucasv 7b1d234029 test(cli): clean up temp script on drop in failed_run_commands_still_exit_with_an_error 2026-12-04 22:32:46 -03:00
autocraft-bot[bot] 7361228721 Merge pull request #9009 2026-12-05 01:32:46 +00:00
batistalucasv 05dda70d5c tests(engine): simplify select_all_then_delete_removes_tables after #8862 2026-12-04 22:31:35 -03:00
Martin BallandClaude Sonnet 5.5 17fecc43ec #8872: an unshaded merge does not take the shading of an earlier one
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCXNomWeGUu3duixKdm
2026-12-05 01:29:10 +00:00
autocraft-bot[bot] 0d8409ea36 Merge pull request #9010 2026-12-05 01:27:59 +00:00
batistalucasv 4281ebbcb1 docs(layout-parity): clarify first-pass 648 pt cap and second-pass 1584 pt rewrap for turned text (#8976) 2026-12-04 22:27:59 -03:00
batistalucasv 3843ada39b docs(ui-egui): document params.pointer(at) precedence in colors::current_of (#8982) 2026-12-04 22:27:33 -03:00
autocraft-bot[bot] ed17e883e5 Merge pull request #9008 2026-12-05 01:24:45 +00:00
batistalucasv a0ca3766b3 xtask(wasm): unit-test wasm summary instead of running cargo check 2026-12-04 22:24:45 -03:00
Martin BallandClaude Sonnet 5.5 1a7b691293 #8872: a merged cell crossing a page break closes at the page end and continues on the next page
Rows are laid out before pagination, so a vertically merged cell had no border where a
page ended and no fill or top border where it went on. Rows now carry the merge's closing
bottom border and its continuation fill and top border; place_table adds them when a page
ends or starts inside a merge, and the cell areas end with the last row on the page.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCXNomWeGUu3duixKdm
2026-12-05 01:23:40 +00:00
autocraft-bot[bot] 3ebe82eb5e Merge pull request #4321
With AutoCraft's conflict resolution 711cb4aa.
2026-12-05 01:22:13 +00:00
autocraft-bot[bot] e9708b91ae Merge pull request #9005 2026-12-05 01:22:13 +00:00
autocraft-bot[bot] 9f28b67cbc Merge pull request #9006 2026-12-05 01:22:13 +00:00
batistalucasv 2ddf619270 Test #7757 ribbon painted I-beam with explicit Windows and Linux shells (#8981) 2026-12-04 22:22:13 -03:00
batistalucasv 27da3abc76 test(widgets): derive tooltip wait frames from harness step time (#8995) 2026-12-04 22:21:17 -03:00
Martin BallandClaude Sonnet 5.5 a6e831e8ca #8872: a merged table cell crossing a page break ends at the page bottom
A restart cell's fill, picture clip and cell box span all merged rows, but rows are
placed page by page, so the box hung past the page edge (gridlines crossed the gap).
Cut those rects at the page's content bottom when the row is placed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCXNomWeGUu3duixKdm
2026-12-05 01:13:02 +00:00
autocraft-bot[bot] ecd8b5db7b Merge pull request #9003 2026-12-05 01:08:28 +00:00
batistalucasv ffadc1d8de fix(ui): run edit.paste directly from context and ribbon Paste menu items (#8849) 2026-12-04 22:08:28 -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] e4e2c2d9d7 Merge pull request #7110
With AutoCraft's conflict resolution 6f202ab6.
2026-12-05 00:08:07 +00:00
autocraft-bot[bot] dba4269b25 Merge pull request #8805 2026-12-05 00:08:07 +00:00
batistalucasv 7888d77bbd caret: skip hidden tracked deletions in Ctrl+Left and Ctrl+Right (#8772) 2026-12-04 21:08:07 -03: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] 51ef42c9f5 Merge pull request #7948 2026-12-04 22:28:41 +00:00
autocraft-bot[bot] a57a77d4c5 Two of the three changes were already in the head commit (c984354a9). Th
Two of the three changes were already in the head commit (c984354a9). The second was only half done: its cross-font test single-clicked the tile and then pressed Insert, so it never tested double-clicking. I changed that test to double-click, and I reworded the harness comment. The tests have not run: formatting passes, but the test build never finished.

1. Already done: in `recent_row`, `form.selected = Some(c)` is set again after `form.load()`, with a comment saying why.
2. Changed: `cross_font_recent_symbol_inserts_clicked_character` now double-clicks the recent U+E999 tile, whose font is "Missing Recent Font", using the existing `double_click_recent_symbol` helper. It checks that U+E999 is inserted in that font and that the dialog stays open. I removed the single click, the Insert-button press and the imports they used.
3. Reworded: the comment in `symbol_double_click_harness` now says outright that it builds its own harness instead of `testing::harness` because a double click needs `with_step_dt` to land both clicks inside egui's double-click window.

`cargo fmt --all -- --check` passes. I could not confirm that the `dialogs::dialogs_insert::tests::` tests pass. The first run timed out waiting for build room. The second sat with no output for about 78 minutes while the build pod restarted several times, and I stopped it. CI needs to show that the changed test passes.
2026-12-04 22:28:41 +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
autocraft-bot[bot] 79ab962f36 Merge pull request #8819
With AutoCraft's conflict resolution ba887ee7.
2026-12-04 19:46:28 +00:00
autocraft-bot[bot] 43f636055e Merge pull request #8798
With AutoCraft's conflict resolution e7b9c769.
2026-12-04 19:46:28 +00:00
autocraft-bot[bot] 76e76b7697 Merge pull request #8789
With AutoCraft's conflict resolution 367694e5.
2026-12-04 19:46:28 +00:00
autocraft-bot[bot] 4c467c1485 Merge pull request #8766
With AutoCraft's conflict resolution 2541c1f4.
2026-12-04 19:46:28 +00:00
autocraft-bot[bot] f9b8b60873 Merge pull request #7955 2026-12-04 19:46:28 +00:00
autocraft-bot[bot] 259870a313 Merge pull request #7197 2026-12-04 19:46:28 +00:00
autocraft-bot[bot] b864439f5c The cause is in the PR's new test, not the app. The test takes the picke
The cause is in the PR's new test, not the app. The test takes the picker's Close button as the first node labelled "Close" inside the picker. The Add a language dialog has two: one in its title bar, at y0=208 in a 1440x900 frame, and the footer's at y0=670. Which one comes first in the accessibility tree depends on node ids. On macOS in the batch it picked the title-bar one, so the test computed the list's visible bottom as 208, above its top of 275. That is the `(reason, top, bottom)` of `Some((… y0: 390 …), 275.0, 208.0)` in the log, so the fit assertion at line 1744 failed. I did not run it on macOS. On Linux the test passed before and after the change, and I printed the nodes there to confirm the title-bar Close at y0=208. The fix is in the test helper in `crates/ui-egui/src/language_packs.rs`. It now collects every Close inside the picker. It keeps only those below the Search field and takes the topmost, which is the footer's. The test is no looser: it still checks that the whole reason fits in the list's visible area. `cargo fmt --check` is clean. Clippy is clean with `-D warnings`. All 18 `language_packs` tests pass.
2026-12-04 19:46:28 +00:00
autocraft-bot[bot] cd7c14e776 Merge pull request #8865 2026-12-04 17:53:43 +00:00
autocraft-bot[bot] 85dd661854 Merge pull request #7856
With AutoCraft's conflict resolution 61f8e8d7.
2026-12-04 17:53:43 +00:00
Dylan M. Taylor b7f512d037 Merge pull request #8864 from storytold/docs/freebsd-15-release-requirement
docs: specify the FreeBSD release requirement
2026-12-04 12:53:43 -05:00
autocraft-bot[bot] 62ff8ba0c2 Merge pull request #8722
With AutoCraft's conflict resolution f72513fa.
2026-12-04 17:53:43 +00:00
autocraft-bot[bot] 4680b9a270 Merge pull request #7067
With AutoCraft's conflict resolution 1c87a92b.
2026-12-04 17:53:43 +00:00
skylar taylorandskylartaylor 29c67c62d7 Release: bump WordCraft to v0.20.1 (#8889)
Co-authored-by: skylartaylor <skylartaylor@users.noreply.github.com>
2026-12-04 11:37:41 -06:00
autocraft-bot[bot] 0866c5bfaa Merge pull request #8870 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 68680e0665 Merge pull request #8867 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 78d6825d3b Merge pull request #8873 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] be1f9c0a1f Merge pull request #8866 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] f329ff6e81 Merge pull request #8863 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 8f330f5e26 Merge pull request #8862 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] a6ee9f22a4 Merge pull request #8858 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] cf95e5a37a Merge pull request #8845 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 1469c44e81 Merge pull request #8844 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] d184ccbfb4 Merge pull request #8833 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 0adadeed56 Merge pull request #8826 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] b3dbe51f1a Merge pull request #8817 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] b1a17b688f Merge pull request #8816 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 3adb7b5055 Merge pull request #8815 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 92c65bc00b Merge pull request #8807 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 61b83a4927 Merge pull request #8806 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 84d46c47f4 Merge pull request #8804 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] ae760626cf Merge pull request #8803 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] c2d2e93500 Merge pull request #8802 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 995746d24e Merge pull request #8688
With AutoCraft's conflict resolution 10509511.
2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 21671b9b66 Merge pull request #1259
With AutoCraft's conflict resolution 198d76f0.
2026-12-04 16:37:24 +00:00
autocraft-bot[bot] e2079632f3 Merge pull request #8003
With AutoCraft's conflict resolution e89186d1.
2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 22f774fb9f Merge pull request #6974
With AutoCraft's conflict resolution 504e41b8.
2026-12-04 16:37:24 +00:00
autocraft-bot[bot] d847fa225e Merge pull request #6525
With AutoCraft's conflict resolution 3e473b5a.
2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 6a91bc63f6 Merge pull request #4582
With AutoCraft's conflict resolution 5a6712e2.
2026-12-04 16:37:24 +00:00
autocraft-bot[bot] a8628f3969 Merge pull request #4322
With AutoCraft's conflict resolution 9f1ca725.
2026-12-04 16:37:24 +00:00
autocraft-bot[bot] d46178a145 Merge pull request #5954
With AutoCraft's conflict resolution ffbe0065.
2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 489d61cd10 Merge pull request #4995
With AutoCraft's conflict resolution f4a74773.
2026-12-04 16:37:24 +00:00
autocraft-bot[bot] f71bf017a7 Merge pull request #3089
With AutoCraft's conflict resolution 199d64f9.
2026-12-04 16:37:24 +00:00
autocraft-bot[bot] da8845c810 Merge pull request #8797 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 7605fd3c8a Merge pull request #8796 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 51b1933480 Merge pull request #8794 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] d0fc72a7ba Merge pull request #8788 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] e4950a63b5 Merge pull request #8781 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 7b7e2a7ff6 Merge pull request #8765 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 1f57c527a2 Merge pull request #8762 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 450938fe00 Merge pull request #8764 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] a9917af050 Merge pull request #8761 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 9757882dda Merge pull request #8760 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] e85e15ee14 Merge pull request #8757 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 5abe5745ce Merge pull request #8754 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 522597264c Merge pull request #8753 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 78bec40359 Merge pull request #8748 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] d3508c9d18 Merge pull request #8724 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 366ecb731e Merge pull request #8713 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 0dac42909e Merge pull request #8712 2026-12-04 16:37:24 +00:00
Martin BallandClaude Opus 5.5 3f33f90f31 #8838: a document window can be maximized and taken full screen again on Windows (#8871)
* #8838: a document window can be maximized and taken full screen again on Windows

Repin craft-libs from 5299d8d9 to ad10c35a: 5299d8d9 plus one fix
(storytold/craft-libs#5339). Since v0.20.0 a document is a child window,
and the runtime sent a maximized window its saved normal place on the word
of facts the root's input listed passes late; winit on Windows takes a
moved window out of the maximized state, so the maximize button, Win+Up
and snapping to the top shook the window and left it at its normal size,
and View > Full Screen slid it off to the side. The window's own pass now
notes its state with its place, and nothing is sent while it is maximized,
full screen or minimized.

Closes #8838, closes #8861

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* #8838: progress log and parity docs for the Windows maximize fix

ROADMAP progress log, hardware parity (windows row: maximize and full
screen, #8838) and UI parity (View > Window > Full Screen), each with its
status line and revision history.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 10:37:24 -06:00
Dylan M. Taylor e7dc3bf319 docs: list the published FreeBSD ARM archive 2026-12-04 11:24:19 -05:00
autocraft-bot[bot] 34cc9214d9 Part 1: in recent_paths_inside_home_contract_and_expand (crates/ui-egu
Part 1: in `recent_paths_inside_home_contract_and_expand` (crates/ui-egui/src/prefs/tests.rs), the round-trip half now gets its home folder from `super::home_dir()`. It no longer reads HOME with a USERPROFILE fallback, so on Windows it uses USERPROFILE like the code it checks. `cargo fmt --check` and `cargo clippy --offline -p wordcraft-ui-egui --all-targets -- -D warnings` passed. I did not see the `prefs` tests run: the test build was still compiling after about 80 minutes, so I stopped it.
2026-12-04 16:17:21 +00:00
yoriswind 3cef779801 Paste clipboard pixels when rich formats have no content
* Paste clipboard pixels when rich formats have no content

* fix(ui-egui): import the bitmap paste helper

* fix(paste): report fallback bitmap read errors
2026-12-04 09:31:54 -06:00
Luis ad958edfce #8562: a TIME field without a picture shows the 24-hour clock in German documents 2026-12-04 16:02:26 +01:00
Luis a3ee0d1ae2 #8507: perf_probe --synthetic stops when a build step fails 2026-12-04 15:52:32 +01:00
Luis f0ab199fa3 #8379: the Multilevel List's Change to Level items are translated 2026-12-04 15:41:45 +01:00
Luis 8ef485cb08 #8421: ui.inspect lists recent documents as full paths again 2026-12-04 15:38:40 +01:00
Luis 7417fbbb0f #8458: on Windows, the recent list's home folder is USERPROFILE, not HOME 2026-12-04 15:18:05 +01:00
Dylan M. Taylor e1fccab746 docs: specify the FreeBSD release requirement 2026-12-04 09:11:37 -05:00
Max MittelstädtandGPT-6-Luna 0081098f4f Preserve exact table row heights below four points
Fixes #8860

Co-Authored-By: GPT-6-Luna <noreply@openai.com>
2026-12-04 13:44:09 +00:00
Max MittelstädtandGPT-6.1-SOL 99917717fd Select the document with Ctrl+A inside tables
Fixes #8857

Co-Authored-By: GPT-6.1-SOL <noreply@openai.com>
2026-12-04 13:20:14 +00:00
autocraft-bot[bot] 87dc3b203e CI failed in wordcraft-validate tests because existing fixtures used orp
CI failed in wordcraft-validate tests because existing fixtures used orphan parts that the PR's reachability requirement no longer gives story roles. Locally 5 unit tests and 26 integration tests failed; CI had stopped at the first. I fixed one real defect: check_commentex in the no-root fallback scope treated an unreachable comments part as an empty contributor and claimed 'no paragraph'; it now marks that set incomplete with a note (contract updated, register regenerated). I fixed the wrong test fixtures by linking the parts via relationships (new Doc::link_main/link_package/add_linked helpers in tests/common/mod.rs) and kept their assertions. The one assertion I changed: compat_counts_unknown_settings_incomplete and compat_flag_in_malformed_settings_is_unknown now expect Fail with XML-MALFORMED (reachable malformed settings is an Error that outranks Incomplete), and the second also asserts the compatibility-limits note. fmt, clippy -D warnings, generate.py --check and the full wordcraft-validate tests pass (218 unit, 510 integration). A wordcraft-cli test run was attempted but the build pod hung; its only validate use is a CT-UNDECLARED check that this change does not touch.
2026-12-04 13:06:14 +00:00
Max MittelstädtandGPT-6.1-SOL cbe03ab801 Tolerate noncanonical field character spellings in validation
Fixes #8850

Co-Authored-By: GPT-6.1-SOL <noreply@openai.com>
2026-12-04 12:48:54 +00:00
autocraft-bot[bot] a969c01e57 Declared field.reachable*2 in the story_roles contract. Gave report_unkn
Declared field.reachable*2 in the story_roles contract. Gave report_unknown_story_reachability its own observation_contract (field.content_types*1, field.entries*1, field.reachable*1). Added that function's pkg.reachable membership to the structural_membership allowlist in observations/generate.py, like report_malformed. Regenerated observation-contracts.md. generate.py --check passes, fmt and clippy are clean, and the contract unit test passes. Five other wordcraft-validate tests still fail, which is outside this part.
2026-12-04 11:27:44 +00:00
Max MittelstädtandGPT-6.1-SOL b1eb5ffb5e Require package reachability before assigning story roles
Fixes #8839

Co-Authored-By: GPT-6.1-SOL <noreply@openai.com>
2026-12-04 10:55:45 +00:00
Max MittelstädtandGPT-6-Luna 2dd637028a Prefer image pixels for browser title and srcset clipboard text
Fixes #8814

Co-Authored-By: GPT-6-Luna <noreply@openai.com>
Co-Authored-By: GPT-6.1-SOL <noreply@openai.com>
2026-12-04 09:39:29 +00:00
pakiatandClaude Opus 5.5 ab0dcf391c Tables: a right-to-left table's floating offset and its nested fit match Word
Follow-ups to #6941, which stopped mirroring cell margins in a right-to-left table.

#8441: fitting a column of a table nested in a right-to-left cell stopped at that cell's
left margin, which #6941 left on the cell's left; it now stops at its right margin, as
the layout draws it.

#8517: a floating right-to-left table placed by an offset has its left edge at the
offset in every mode (measured in Word for Windows): before Word 2013 Word moves it by
neither its first cell's left margin nor w:tblInd, and from it not in by half its left
border. An inline one still moves out by that margin before Word 2013, as Word does;
a comment at start_offset says so.

Fixes #8441. Fixes #8517.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 16:23:21 +07:00
yoriswind f4ac3b9ef5 fix(cli): surface command result warnings in run 2026-12-04 00:09:45 -08:00
RickiNano 967d608eb5 Links: the link warning applies to every target; the test checks the status repeats it (#8541)
The insert.link params doc put the warning inside the Place in This
Document note, though a URL link gets it too. The two-paragraph test
now checks that the warning is not empty and that the status line
shows the same message, without pinning its wording.
2026-12-04 08:56:21 +01:00
autocraft-bot[bot] 51359bf825 Part 1: the save.autosave setter in crates/ui-egui/src/options.rs now cl
Part 1: the save.autosave setter in crates/ui-egui/src/options.rs now clears autosave_choice only when it is Some(false), so an opened-only file keeps its switch approval across an Options untick and re-tick. I added the test autosave_option_retick_keeps_the_switch_approval_of_an_opened_file in options/tests.rs. cargo fmt --check passed. Clippy did not finish because the harfbuzz C++ dependency compile ate the session's shell time; its log shows no errors. The tests, including the new one, were not run.
2026-12-04 07:47:17 +00:00
RickiNano 121a43de5b Links: say when Text to display is not applied (#8541)
Ctrl+K on a selection that isn't one plain line (several paragraphs,
a picture or field, a field's result) shows <<Selection in document>>
in Text to display, but the field stays editable. Text typed over it
reached insert.link, which linked the selection with its own text and
reported success, so the edit vanished without a word.

insert.link now notes when a given text differs from the selection
and is not applied: the status line says so and the result carries a
"warning", so the dialog, the CLI and MCP all report it. A text equal
to the selection, or the placeholder the dialog drops, still links
silently.
2026-12-04 07:50:10 +01:00
yoriswind 571473749e Font dialog: Show the resolved East Asian theme font 2026-12-03 22:15:21 -08:00
Max MittelstädtandGPT-6-Luna 6fc57857c8 Report wasm test crates accurately
Fixes #8799

Co-Authored-By: GPT-6-Luna <noreply@openai.com>
2026-12-04 06:06:08 +00:00
RickiNanoandFredApps 2d9790c374 #7887: hovering a tracked change shows its kind, author and time (#7967)
* #7887: hovering a tracked change shows its kind, author and time

Resting the pointer on a tracked insertion, deletion, move or formatting
change shows a tip with what the change is (Inserted, Deleted, Moved to,
Moved from, Formatted), its author and its time. Only changes the page
marks count: none with markup hidden, insertions and deletions while Show
Markup shows them, formatting while it shows formatting. A link's tip
comes first. The time is shown as written in w:date, as Word does, since
a revision has no UTC time beside it.

* #7887: tips for paragraph formatting changes, and in notes and text boxes

The hover tip resolves the story under the pointer as a click does, so a
change in a footnote or text box shows its tip while the caret is in the
body. A paragraph whose own formatting changed while tracking (alignment,
indents) shows a Formatted tip on its text when the character under the
pointer has no change of its own.

* #7887: the link tip looks in the story under the pointer too

A link in a footnote or endnote now shows its tip while the caret is in
the body, so the link's tip still comes before the tracked change tip
there.

* #7887: a change made here shows its time in local time

A change WordCraft makes keeps its UTC time beside the local w:date
(#6876's Revision::date_utc). revision_time now passes it to stamp, as
comment_time does, so the tip shows the user's local time for it. A
change from a file with only a Z date still shows as written.

changes_made_here_show_in_local_time builds the revision through
made_revision, as new_revision does, and reads it at UTC+2: 14:05 for
12:05Z. Without the fix it shows the machine's own wall time instead.
The canvas hover test sets a canned date, so it now clears date_utc
too, as a file's change has none.

* #7887: the tip's time is optional, and a w:date offset is converted (docs)

---------

Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-12-04 06:11:22 +01:00
Max MittelstädtandGPT-6-Luna 9621688eae Insert mid-document TOCs before paragraphs at offset zero
Fixes #8768

Co-Authored-By: GPT-6-Luna <noreply@openai.com>
Co-Authored-By: GPT-6.1-SOL <noreply@openai.com>
2026-12-04 05:10:34 +00:00
yoriswind 3ced0353e1 OpenDocument: Report fallback page conversion errors 2026-12-03 19:28:24 -08:00
batistalucasv 7e402c7529 fix(macos): allow ui.quit while a modal dialog is open (#8792) 2026-12-04 00:16:25 -03:00
batistalucasv ea7fe218ea fix(options): reflect document AutoSave opt-out in Save checkbox (#8795) 2026-12-04 00:14:59 -03:00
batistalucasv eb3ae58fd4 Control: refuse programmatic ui.quit with unsaved work unless forced (#8793) 2026-12-04 00:14:08 -03:00
batistalucasv bd7c07aea1 Tests: check block count and middle paragraph text after compare (#8769) 2026-12-03 23:51:34 -03:00
batistalucasv 6c37ffb1eb test(widgets): isolate font-box tests to fixed assets/fonts catalog (#8777) 2026-12-03 23:43:12 -03:00
batistalucasv 4876dc7fbd test(widgets): assert font_box warning advice, Add Font… position, and font.add action (#8778) 2026-12-03 23:43:08 -03:00
batistalucasv ca6a949a24 Docs: clarify default (0, 0) coordinates on ui.click and ui.wheel (#8775) 2026-12-03 23:39:03 -03:00
yoriswind ba775deed9 References: Import NodeT for Index dialog checks 2026-12-03 18:38:33 -08:00
Martin BallandClaude Opus 5.5 17da903053 packaging(linux): riscv64 smoke test sets MALLOC_TRIM_THRESHOLD_ so the CLI doesn't restart under QEMU (#8786)
Since #7914 the CLI restarts itself to set MALLOC_TRIM_THRESHOLD_. Under user-mode
qemu-riscv64 with no binfmt handler the restart can't run the riscv64 binary, glibc's
execvp hands it to /bin/sh, and the release job fails with 'Syntax error: word
unexpected'. Setting the variable skips the restart. Real riscv64 hosts are unaffected.


Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 02:27:27 +00:00
batistalucasv e253cac545 Docs: clarify control protocol test doc comment (#8782) 2026-12-03 23:21:42 -03:00
batistalucasv 6985800d23 docs(layout-parity): mark continuous-section run-over case as inferred (#8779) 2026-12-03 23:13:30 -03:00
batistalucasv 08d6f87dca docs(formats): document shared conversion error hooks on test-support feature (#8784) 2026-12-03 23:13:13 -03:00
Max MittelstädtandGPT-6.1-SOL 401eabf292 Resolve empty East Asian theme faces through per-script fonts
Fixes #8749

Co-Authored-By: GPT-6.1-SOL <noreply@openai.com>
2026-12-04 01:54:36 +00:00
batistalucasv 320af8dbe1 Tests: cover neighbouring table cells carrying the same link (#8657) 2026-12-03 22:43:21 -03:00
batistalucasv 0b0011e053 Layout: document and test small-caps marks sharing the letter run (#8571)
Clarifies in segment_keys and docs/layout-parity.md that combining marks after a lower-case letter in small capitals take the letter's 0.8 size and share its shaping run even when the run's font already draws every mark, and adds a regression test for that case.
2026-12-03 22:40:39 -03:00
David MannandClaude Opus 5.5 187a36e16c fix(cli): mcp --author without a name is a usage error
`arg_value` returned nothing for a trailing `--author` (the session started
with the default author) and took the next option as the name in
`--author --headless`. `mcp_author` goes through `find_option_arg`, as
--page, --scale and --format do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 02:33:23 +01:00
yoriswind 2573d54c4d Layout: Scope Rect import to flow tests 2026-12-03 17:32:46 -08:00
batistalucasv 752b78cd18 docs(layout-parity): update cell frame placement for #6523 (#8326) 2026-12-03 22:28:22 -03:00
yoriswind 20f91f5bdf References: Keep range-field settings in the Index dialog 2026-12-03 17:26:13 -08:00
batistalucasv 69f3ccbba8 Layout: assert line wrapping and letter overhang in turned at-least row test (#8745) 2026-12-03 22:18:04 -03:00
yoriswind 29c5c19d67 Keep floating objects at the drop position above pushed text 2026-12-03 17:17:58 -08:00
David MannandClaude Opus 5.5 903edaffc7 Merge main into feat/agents-open-window
main dedented the window closure (windowless root); the agent link block
replaces main's control-server block there. docs/mcp.md keeps main's
`file.close` sentence with the open-window wording.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 02:12:43 +01:00
Max MittelstädtandGPT-6.1-SOL 34c6eeff8d Preserve PDF link reading order across split paragraphs
Fixes #8744

Co-Authored-By: GPT-6.1-SOL <noreply@openai.com>
2026-12-04 01:09:28 +00:00
batistalucasv 8725caa4a3 docs(layout-parity): document turned text wrapping for at-least and merged rows (#8391) 2026-12-03 22:00:42 -03:00
David MannandClaude Opus 5.5 3e3975d3a0 Merge main into feat/agents-open-window
Takes main's craft-libs pin (5299d8d, which contains storytold/craft-libs#4905's
head); keeps both sides' file-dialog tests and the control-protocol history.
Moves `wordcraft-cli mcp` into `run_mcp` so `run` stays under clippy's
cognitive-complexity limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 01:58:38 +01:00
batistalucasv 77d00e0ee1 Layout: re-apply space before below a second stacked Top-and-Bottom object 2026-12-03 21:46:39 -03:00
yoriswind 9cda9db296 Customize Keyboard: keep categories for unimplemented commands 2026-12-03 16:44:55 -08:00
autocraft-bot[bot] 500e150132 Merge pull request #8733 2026-12-04 00:42:46 +00:00
autocraft-bot[bot] 416db1b645 Merge pull request #7727 2026-12-04 00:42:46 +00:00
Martin BallandClaude Opus 5.5 8baa46395f Release: version 0.20.0 (#8711)
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 00:42:46 +00:00
Martin BallandClaude Opus 5.5 2f08031e75 macOS: Cmd+Q and WordCraft › Quit ask about every unsaved document (#8709) (#8741)
* fix(macos): Cmd+Q and the app menu's Quit ask about every document (#8709)

The app menu had no Quit item, so craft added its own, whose click only
closed the root window. Add a ui.quit command (WordApp::quit, as the
Dock's Quit) and a Quit-role app-menu item that runs it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

* native_menu test: CommandRef is not an Option (#8709)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 00:42:23 +00:00
Martin BallandClaude Opus 5.5 e9f07d8837 Multi-window: file.close save, ui.closeWindow window, close-prompt coverage (#7822) (#8624)
* Closing document windows: file.close save, ui.closeWindow window, prompt raised on window focus (#7822)

Spec rules 3, 5, 6 and 8 of docs/specs/multi-window-close.md that the close-owner
work (#8277) left open, with a test each.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

* Review fixes: file.close save keeps the comment-draft refusal; drop redundant focus hunk (#7822)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

* ADR 0001: X11, XWayland and BSD on X11 keep a visible root (amendment)

egui's windowless root returns UnsupportedConfiguration there; WordCraft
falls back to the windowed root. The close rules still apply.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

* Repin craft-libs to 5299d8d9 (windowless root support, IconPicker previews, CellGrid fix)

craft-libs d73e274a -> 5299d8d9 (every craft-libs rev, craft-nightly and the
patches), egui 07c20531 -> 399fc6e0, winit 0dfcec0e -> 3fd7ae64, the revs
craft-libs main builds with. Cargo.lock updated for those packages only.

Adapt to the hosted unsaved-changes question: the dialog host takes
HostedUnsavedChangesDialog, not UnsavedChangesDialog.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

* Windowless root: every document window is a child; X11 keeps the visible root (#7822)

Use eframe's RootViewportMode::Windowless with InstallSpec::windowless_root unless
the session is X11, and fall back to the visible root on UnsupportedConfiguration.
active_viewport/viewports no longer fall back to ROOT when windowless; close_decision
closes when no documents remain; a window that failed to open is dropped and the user
told; ui.closeWindow replies requested:false while a Save prompt is open.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

* Windowless root: save window place every frame, raise Save prompt on sole-window close (#7822)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

* fix(windows): save on window-only file.close; point ui.closeWindow docs at ui.inspect; document save scope (#8624)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

* ADR 0001: X11 keeps #7752; dialogs have no parent under the windowless root

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

* Windowless root: only the first window takes the saved place; a promoted survivor stays put (#7822)

Reported on macOS: closing the first window moved the surviving window to the
first window's saved place.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

* Windowless root: files dropped on a document window reach the intake (#7822)

eframe runs raw_input_hook only for the root and deferred viewports; document
windows are immediate viewports, so under the windowless root no drop reached
the app. A viewport hook forwards child-window drops. Pointed out by Skylar
(windowless/default-on-reference).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 00:42:19 +00:00
batistalucasv 3c79eca060 Tests: merge Turkic Change Case checks into typing.rs (#8423) 2026-12-03 21:42:17 -03:00
autocraft-bot[bot] a1aa614bf1 Merge main (5073f8e7) into the pull request
Resolved the conflict in crates/ui-egui/Cargo.toml. I kept the pull requ

Resolved the conflict in crates/ui-egui/Cargo.toml. I kept the pull request's `craft-html = { workspace = true }` line and took main's craft-libs pin 5299d8d9 for craft-fonts-build, which matches the workspace pin. Cargo.lock already lists craft-html and craft-fonts-build under wordcraft-ui-egui and has no references to the old d73e274a pin, so I left it alone. No conflict markers remain. I couldn't build or test the result: `cargo check --offline` fails because the egui git dependency can't be checked out without network access.
2026-12-04 00:36:14 +00:00
yoriswind 71abe1c4c9 Windows: preserve client size when cascading documents (#8752) 2026-12-03 16:10:28 -08:00
yoriswind 5ca9917471 Caret: follow editor visibility for tracked deletions (#8746) 2026-12-03 15:40:57 -08:00
yoriswind 37c8061088 Caret: skip wholly deleted paragraphs in No Markup (#8743) 2026-12-03 15:31:05 -08:00
yoriswind d53ba37903 Web: accept the screenshot helper inline data flag (#8726) 2026-12-03 14:28:42 -08:00
autocraft-bot[bot] 5073f8e7c2 Merge pull request #8728 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] 0df3151f01 Merge pull request #8727 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] 92eb57fd08 Merge pull request #8703 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] f1fb526f3f Merge pull request #8721 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] b4ecd20dba Merge pull request #8631 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] 161c127926 Merge pull request #8702 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] de328db448 Merge pull request #8719 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] e3d1ee90c3 Merge pull request #6587
With AutoCraft's conflict resolution 8460bff5.
2026-12-03 22:27:58 +00:00
autocraft-bot[bot] 3138201a56 Merge pull request #8692 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] 0600244e11 Merge pull request #8662
With AutoCraft's conflict resolution a0a3c553.
2026-12-03 22:27:58 +00:00
autocraft-bot[bot] 3b0257ff33 Merge pull request #6943
With AutoCraft's conflict resolution edb53680.
2026-12-03 22:27:58 +00:00
autocraft-bot[bot] 1591f99189 Merge pull request #8691 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] 1ffd5f8d4a Merge pull request #8647
With AutoCraft's conflict resolution 849eb756.
2026-12-03 22:27:58 +00:00
autocraft-bot[bot] 3b2ce5cb83 Merge pull request #8718 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] e2f2fe1f09 Merge pull request #8678 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] cfae52c97d Merge pull request #8714 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] 0e47c8613c Merge pull request #8690 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] d7986fc26c Merge pull request #8710 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] 1812618f10 Merge pull request #8689 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] e7172b9a8a Merge pull request #8705 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] b211131dec Merge pull request #8681 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] bbc587e2a6 Merge pull request #8704 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] f1ad785403 Merge pull request #8675 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] e3653ada4b Merge pull request #8677 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] 167e479382 Merge pull request #8676 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] 81abc0d81b Merge pull request #8674 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] eb8a7e311c Merge pull request #8671 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] 040150d486 Merge pull request #8670 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] b7e49e84b3 Merge pull request #8666 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] 168e39e5a4 Merge pull request #8667 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] 0fe7ede07e Merge pull request #8664 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] 5b24de412e Merge pull request #8645 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] 5dad217316 Merge pull request #8641 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] 2ad2694407 Merge pull request #8284 2026-12-03 22:27:58 +00:00
Martin BallandClaude Opus 5.5 4622fef6ce Repin craft-libs to 5299d8d9 (windowless root support, IconPicker previews, CellGrid fix) (#8699)
* Repin craft-libs to 5299d8d9 (windowless root support, IconPicker previews, CellGrid fix)

craft-libs d73e274a -> 5299d8d9 (every craft-libs rev, craft-nightly and the
patches), egui 07c20531 -> 399fc6e0, winit 0dfcec0e -> 3fd7ae64, the revs
craft-libs main builds with. Cargo.lock updated for those packages only.

Adapt to the hosted unsaved-changes question: the dialog host takes
HostedUnsavedChangesDialog, not UnsavedChangesDialog.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

* fix(comments): selecting a comment card no longer opens its message for edit

craft-libs now hides a card's Reply button and reply box while one of its
messages is in the editor. focus_balloon opened the lead message's edit on
every selection, so Reply was never reachable. As in Word, selecting a card
selects it and its anchor; editing starts on a double click in a message or
the message menu's Edit, and Reply stays available.

Tests that typed straight after clicking a balloon now open the edit as the
card's Edit does (click_balloon); the reply test only selects the card.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

* fix(comments): a double click on the selected comment card opens its edit

Selecting a card no longer opens its message for edit (that hid Reply), so
craft-libs' CommentBalloons left no way to start an edit. A double click on
the selected card's own text now opens message 0 for editing, as in the
comments pane. Keyboard path (Enter/F2) is not added here.

Tests open the edit with that double click instead of setting state.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 22:27:58 +00:00
yoriswind 061985fb6b Test AutoSave format eligibility separately from opt-out 2026-12-03 14:16:27 -08:00
autocraft-bot[bot] b8334518b3 Merge main (af4cacc4) into the pull request 2026-12-03 22:15:26 +00:00
batistalucasv 2b612d51fa Layout: a centre tab moved to the next line starts with no room, as a right tab does
A centre or decimal tab that moves on to the next line with its text kept the width it had on the line before, so the shift of its text was worked out from that old width and the text was off its stop. Every tab whose text is pending now starts with no room.
2026-12-03 19:09:33 -03:00
batistalucasv 472399cb33 Layout: the automatic-space check reads a run's East Asian theme slot over the inherited named font (#8697) 2026-12-03 19:08:54 -03:00
yoriswind 25b86d2a1d Preserve the document AutoSave choice on manual Save 2026-12-03 13:52:05 -08:00
batistalucasv dd3dedddae Tests: cover mid-document TOC insert and single-step undo (#8385) 2026-12-03 18:47:31 -03:00
batistalucasv 04e04e8119 test(ui-egui): trim frames and window size in Link shortcut test (#8338) 2026-12-03 18:45:54 -03:00
batistalucasv e3749fc2d0 test(widgets): drive font_box with Catalog::global and action rows in keystroke-frame test (#8447) 2026-12-03 18:33:49 -03:00
batistalucasv 020eba42ff test(ui-egui): close Backstage via ui.backstage command in keytips test (#8498) 2026-12-03 18:13:29 -03:00
batistalucasv 1a339aebb4 Tests: trim duplicate terminal-paragraph compare checks (#8503) 2026-12-03 17:38:12 -03:00
batistalucasv 5d46607ec4 docs(ui-egui): clarify perf_probe edit-burst comment (#8510) 2026-12-03 17:33:23 -03:00
batistalucasv 456aa68148 Tests: exercise the 0.4 pt boundary step in fit_one_page_respects_step_pt (#8432) 2026-12-03 17:25:04 -03:00
batistalucasv 83ada40e06 Canvas test: verify Ctrl/⌘ press in the grey area is ignored 2026-12-03 17:17:31 -03:00
yoriswind b36fa16a15 Index ruler grid spans in one pass 2026-12-03 12:00:31 -08:00
yoriswind 04cd0ca6fd Enter visible equations across hidden deletions 2026-12-03 11:54:42 -08:00
batistalucasv 05cbdfd9ff layout: update RTL table margin comments (#8516) 2026-12-03 16:51:11 -03:00
batistalucasv e66ba81d3f Layout: use unkerned width in hyphenation fit check (#8617) 2026-12-03 16:44:47 -03:00
yoriswind 8633e63909 Review: format the middle paragraph regression cases 2026-12-03 11:42:51 -08:00
batistalucasv 8bf97aa275 Layout: drop the line-end kerning pair from settled line positions (#8617) 2026-12-03 16:40:56 -03:00
batistalucasv a2960ce55d test(formats,engine): cover shared-model conversion error propagation (#8523) 2026-12-03 16:39:43 -03:00
batistalucasv 48b211621d Tests: remove redundant Dictate icon shape check from stub ribbon test (#8615) 2026-12-03 16:37:59 -03:00
batistalucasv c39e70fc85 engine: remove duplicate German date-field integration tests (#8540) 2026-12-03 16:33:51 -03:00
batistalucasv 0a1d913690 engine: drop redundant turns_on branches and cover collapsed caret (#8658) 2026-12-03 16:32:01 -03:00
yoriswind 91a75c8103 Review: keep selection on surviving text after middle paragraph removal 2026-12-03 11:30:16 -08:00
batistalucasv c55e7a83e6 Layout: test a long word in a short at-least turned row (#8487) 2026-12-03 16:22:14 -03:00
batistalucasv 129b6ad2f9 xtask(wasm): check wasm-safe test targets and drop source-text test (#8579) 2026-12-03 16:18:01 -03:00
RickiNano fc3146206a Review: Accept/Reject All puts the caret before a removed last paragraph (#8500)
When Reject All (an inserted paragraph) or Accept All (a deleted one)
removed the last paragraph of a story or cell, the selection kept its
path until the final clamp, which moved it into the paragraph before
with the same offsets. A selection of "NEW" after "Keep this" became a
selection of "Kee", and typing replaced it.

Selection ends in the removed paragraph now go to the end of the
paragraph before it, as soon as remove_trailing_para removes it.
2026-12-03 20:17:53 +01:00
batistalucasv b682a1fd06 PDF export: tag header and footer link annotations with Link/OBJR (#8642) 2026-12-03 16:17:01 -03:00
batistalucasv 6bdd6769d1 Tests: retry transient Windows token-file timeout in control_server lifecycle test (#8556) 2026-12-03 16:09:40 -03:00
batistalucasv 6a6dfd7f58 Docs: restore ui.drag in control protocol reference (#8559) 2026-12-03 16:09:16 -03:00
batistalucasv 4c600213dc Tests: check nested group flattening in note separators (#8573)
Replace a_frame_shape_in_a_note_separator_reads_as_a_rectangle with
linked_nested_group_in_a_note_separator_is_flattened so the test checks
behaviour only blocks_from_shared provides (flattening a hyperlinked
nested group) rather than ShapeKind::Frame, which the serde convert
fallback now also handles.
2026-12-03 16:08:12 -03:00
autocraft-bot[bot] af4cacc45f Merge pull request #8637 2026-12-03 19:02:47 +00:00
autocraft-bot[bot] 8d75a12b48 Merge pull request #4207 2026-12-03 19:02:47 +00:00
autocraft-bot[bot] ba179cb3d1 Merge pull request #8643 2026-12-03 19:02:47 +00:00
Martin BallandClaude Opus 5.5 30458a8e0b Status bar: a sliver of the page above isn't the page in view (#7149 item 7) (#7154)
* viewed_page: #7149 item 7, a sliver of the page above is not the page in view

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

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

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 19:02:47 +00:00
autocraft-bot[bot] 6d27b1a4a1 Merge pull request #8644 2026-12-03 19:02:47 +00:00
autocraft-bot[bot] faf55fad76 Merge pull request #8629 2026-12-03 19:02:47 +00:00
batistalucasv 9d5789162f Layout: mark begins_section run-over case as inferred (#8569) 2026-12-03 16:01:11 -03:00
batistalucasv cdef8012e9 Tests: merge whole-paragraph mark compare checks into existing test (#8470) 2026-12-03 16:01:05 -03:00
batistalucasv 8bca61f529 docs(layout-parity): record turned text rule and Word evidence for at-least rows (#8486) 2026-12-03 16:00:58 -03:00
batistalucasv 4dd74c36d5 docs(layout): mention cell_frame in Joint::take_up doc comment
Fixes #8564
2026-12-03 15:59:36 -03:00
yoriswind 83381d344a Merge main and streamline hidden-deletion caret movement 2026-12-03 10:55:10 -08:00
batistalucasv 46050e5c4b Docs: document ui.move and pointer position parameters in the control protocol 2026-12-03 15:52:48 -03:00
autocraft-bot[bot] 6d2f0d7759 All three failing checks (ubuntu gate, Windows and macOS Print) fail on
All three failing checks (ubuntu gate, Windows and macOS Print) fail on one test, the_autosave_knob_sits_right_when_on_and_mirrors_right_to_left (chrome/tests.rs:812). Cause: the test sets session.path and autosave_path to fake a file saved here, then toggles file.autosave on, off and on again. Turning it off clears autosave_path, and turning it on again needs the file to count as read from disk (read_from == session.path, per autosave_switch_block). The test never set read_from, so the second 'on' returned the NotSavedHere refusal. A real save sets both fields (note_file_on_disk), so the test setup was wrong, not the code. Fix: the test now also sets a.read_from = Some(path); its assertions are unchanged. The failing test passes in the pod, cargo fmt --check is clean, and clippy on wordcraft-ui-egui --all-targets is clean apart from an existing unused-dependency warning (egui_extras). I did not run the full suite.
2026-12-03 18:36:52 +00:00
batistalucasv 4073aa4274 docs(layout-parity): record list-number kerning in status line (#8583) 2026-12-03 15:26:11 -03:00
yoriswind 95388461a7 Layout: import Pos in the grid kerning regression 2026-12-03 10:18:59 -08:00
batistalucasv 53b22e61f2 Layout: anchor space-before Top-and-Bottom band to first line's original top 2026-12-03 15:10:13 -03:00
batistalucasv f641b83a2f layout: filter Top-and-Bottom exclusions by applied space before 2026-12-03 15:08:49 -03:00
yoriswind 8544a588c1 test(table_resize): format the merged-row regression 2026-12-03 10:06:35 -08:00
yoriswind 9964e4e88c Layout: fit kerned characters into exact grid cells 2026-12-03 09:58:16 -08:00
autocraft-bot[bot] 49ef461bc3 Merge pull request #6634
With AutoCraft's conflict resolution b76731e9.
2026-12-03 17:57:56 +00:00
autocraft-bot[bot] 2bfc68964b Merge pull request #8636 2026-12-03 17:57:56 +00:00
batistalucasv ddb8fa164b layout: move ligature kerning pair to its last cluster
A ligature glyph sits on the head cluster, so Cluster::kern recorded the ligature's kerning pair with the following glyph on the head cluster rather than on the last cluster of the ligature. Move head.kern to the last cluster in split_ligature_advances so a forced character wrap inside the ligature does not subtract a pair that belongs after the whole ligature, and a line ending after the ligature drops that pair.

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

Resolved the only conflict, in markup_pdf_takes_the_track_changes_option_colours in crates/engine/src/tests.rs. The default branch already pins the document creation date in that test (2026-01-01, with an explanatory comment), so I kept its lines and dropped the PR's duplicate pin (2024-01-01). The PR's change is now redundant. No conflict markers remain. I did not build or run tests, and did not run cargo fmt --check, because the edit only removed the PR's side of the conflict and the markers.
2026-12-03 16:34:56 +00:00
batistalucasv 3a7a3b4b95 test(engine): cover first-character toggles on text boxes and column selections (#8589) 2026-12-03 12:50:18 -03:00
autocraft-bot[bot] 1ec83a1a2f Merge pull request #6578
With AutoCraft's conflict resolution 0de83145.
2026-12-03 15:10:05 +00:00
Mauro Mazzieri 11323ff0dd #7110: describe the rule, not measurements
The test's comment, fit_height's doc comment and the parity history row
state the rule the code implements; test logic and assertions unchanged.
2026-12-03 10:13:46 +01:00
autocraft-bot[bot] a6d1534889 Part 1: the Outline view fuzz in outline_level_changes_are_undoable (c
Part 1: the Outline view fuzz in `outline_level_changes_are_undoable` (crates/engine/src/tests.rs) now keeps the `Session::run` result instead of discarding it. It builds the registry once and asserts `!caught_panic(&reg, &r)`, with the command id, the junk input and the result in the failure message. The message format matches the one in `hostile_params_never_panic`. `cargo fmt --check` and `cargo clippy` on `wordcraft-engine` are clean. `outline_level_changes_are_undoable` and `caught_panic_flags_a_command_that_panics` both pass. I did not run the full engine test suite.
2026-12-03 05:35:02 +00:00
David MannandClaude Opus 5.5 e31df586db fix(automation): dialogs an agent opened keep its folders; agent_folders before the first call
A file dialog keeps the folders in force when it opened and handles its
answer inside them, so a path an agent typed into the fallback chooser can't
reach outside its folders on the later frame the answer arrives. Before any
call, agent_folders names the folders the next call will work in, the
roots given to mcp included.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 00:37:07 +01:00
yoriswind 9386f754f4 test(engine): qualify caret regression selection type 2026-12-02 15:24:09 -08:00
David MannandClaude Opus 5.5 865fcf21eb deps: pin craft-libs at storytold/craft-libs#4905's new head (test-only change there)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 00:08:46 +01:00
David MannandClaude Opus 5.5 a18747a686 feat(automation): agents in the open window through the ArtCraft Launcher's switch
While the launcher's switch names WordCraft, the shared agent link
(craft::automation::agents::AgentLink) serves the control channel on
loopback with an owner-only token and publishes agent-connection.json;
plain wordcraft-cli mcp finds the window through it with the shared live
client (Live), signs in with the challenge handshake, and otherwise follows
the closed-app choice. Everything agents do in the window reads and writes
only in the agent folders: their requests, saved screenshots, the frames
that play their input and the commands their keys fire. File > Options >
Agents is the shared Agents page. Adds the agent_folders tool; --connect
becomes a deprecated alias for one release; the screenshot tool reads the
framework's base64 reply.

Closes #8415.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 23:59:51 +01:00
David MannandClaude Opus 5.5 bbe04de28d deps: pin craft-libs at storytold/craft-libs#4905's head
The agent link's window client signs in with the challenge handshake
(ControlClient::connect_challenged). The head is d73e274a0 plus that commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 22:19:18 +01:00
autocraft-bot[bot] f670da8602 Part 1: in crates/layout/src/floats.rs, the re-placement condition is no
Part 1: in crates/layout/src/floats.rs, the re-placement condition is now `float.y < 0.0 && area.map_or(r.bottom(), |(_, b)| b) < y0 + lead - 0.5`. Floats without a wrap area (in front of or behind text) now need a negative offset and to sit above the pushed first line, like wrapping floats. A positive-offset label over a top-and-bottom picture is no longer moved down. fmt --check and clippy -D warnings are clean. In `cargo test -p wordcraft-layout`, 756 passed and 1 failed: the timing test a_megabyte_long_word_lays_out_quickly, which has no floats and failed again alone after 244 s. I think the sandbox is slow, but I didn't run it on the base commit. I didn't add a test for the label-over-picture case.
2026-12-02 20:00:12 +00:00
autocraft-bot[bot] b3302eeef3 Part 1: in a document protected as read only, comments only or forms, Re
Part 1: in a document protected as read only, comments only or forms, Replace All now keeps only the matches inside the editable regions, in every story. A placeholder repeated in a header, footer, footnote or text box, or in locked body text, is left alone instead of making the whole command fail. The editable matches are replaced as before. I added `editable_ranges` in cmd/protect.rs: exception ranges the author may edit for read only and comments, and the interiors of fillable controls for forms. `replace_all` in cmd/edit.rs filters each story's matches through it before the locked-content check and the replacement. I added the test `replace_all_in_a_protected_document_skips_protected_matches` in cmd/protect/tests.rs, with an editable body region and `[NAME]` in a header, a footnote and locked body text. I did not check that it fails without the fix. `cargo fmt --all --check` is clean. The six `replace_all` tests pass, including the new one. The full engine test run was 1215 passed and 2 failed. The failures are `page_down_and_up_never_stay_on_a_line_in_the_continuous_views` and `rerouting_many_pages_does_not_rescan_all_objects_per_connector`. Neither touches Replace All, and I did not re-run them on the base commit. `cargo clippy -p wordcraft-engine --all-targets -- -D warnings` stops on one existing needless-range-loop lint at cmd/table_draw.rs:768, which I did not touch. I did not run clippy without test targets. One behaviour change: matches in locked body text of a protected document are now skipped silently. Before, they made the whole command fail.
2026-12-02 19:34:24 +00:00
autocraft-bot[bot] 1b8c2047dd Made drop_direct_indents reachable from the text module (pub(in crate::c
Made drop_direct_indents reachable from the text module (pub(in crate::cmd) in para/format.rs, re-exported from para.rs) and called it, only when the level actually changes, in tab, indent_by_tab (line-start, style-numbered case) and back_tab in enter_tab.rs. Extended changing_a_list_level_drops_a_direct_indent with text.tab (caret at item start) and text.backTab cases comparing a dragged item to a fresh one. fmt and lib clippy are clean; the typing tests pass. The full engine suite timed out in this workspace, so I ran only the tests matching changing_a_list_level, tab and list, plus the typing tests. A preexisting needless_range_loop clippy error in a test in cmd/table_draw.rs (not my change) stops --all-targets clippy. The indent_by_tab path has no new test.
2026-12-02 19:25:01 +00:00
Muse f1e8793b7a tests(engine): pin document creation date in markup PDF colour test 2026-12-02 09:35:19 -06:00
Khawar Zamman Wani 5c41ef2f08 Merge PR branch head into rich-clipboard paste fix
# Conflicts:
#	crates/ui-egui/Cargo.toml
2026-12-02 15:41:14 +05:30
FredApps 1955eea91d Merge current main into browser-image paste branch 2026-12-02 08:50:20 +01:00
yoriswind a937df1bb7 fix(layout): keep visual caret out of omitted runs 2026-12-01 16:25:10 -08:00
yoriswind b6488c5773 fix(engine): skip hidden tracked deletions with the caret 2026-12-01 16:15:29 -08:00
MaheshDesu b95bfbbb37 test(ui): pin the exact painted cursor over the font size box (#7757)
Signed-off-by: MaheshDesu <mahesh.desu3@gmail.com>
2026-11-30 18:09:37 +05:30
MaheshDesu 3383d8a9f1 fix(ui): keep the ribbon font cursor visible on Windows (#7757)
Signed-off-by: MaheshDesu <mahesh.desu3@gmail.com>
2026-11-30 18:09:37 +05:30
MaheshDesu be96af974d test(ui): pin the ribbon font fields' Windows cursor (#7757)
Signed-off-by: MaheshDesu <mahesh.desu3@gmail.com>
2026-11-30 18:09:07 +05:30
batistalucasv 1342420920 test(comments): assert draft remains empty after clicking away 2026-11-30 01:50:11 -03:00
Khawar Zamman Wani 664980b32b Preserve rich clipboard content during ordinary paste 2026-11-30 09:14:12 +05:30
Khawar Zamman Wani 349556de8a Merge upstream main into clipboard paste fix 2026-11-30 09:13:40 +05:30
batistalucasv c984354a97 fix(ui): preserve selected recent symbol across cross-font load 2026-11-29 18:24:12 -03:00
batistalucasv a1dae5ad32 fix(ui): check pointer before command match in colors::current_of 2026-11-29 17:59:05 -03:00
batistalucasv e98df65d23 Symbol: double-clicking a recent symbol inserts it (#7947) 2026-11-29 16:54:00 -03:00
batistalucasv 654e1745f9 Format Shape: apply More Colors to solid fills and gradient stops (#7954) 2026-11-29 16:54:00 -03:00
FredApps 869160692f Merge origin/main into fix/fuzz-panics-autosave 2026-11-28 10:16:45 +07:00
554159685b fix(engine): resolve and reopen a comment's whole thread, replies included
review.resolveComment changed only the addressed comment's resolved flag, so
resolving a discussion left its replies open, and acting on a reply left its
parent and siblings unchanged.

The command now walks up to the thread root (cycle-safe, ignoring a missing
parent) and reuses the existing descendant walk, so the root, its replies and
replies to replies change together in one undo step. An omitted value still
toggles from the addressed comment's own state, so a card's Resolve or Reopen
button does what it says even in a file with mixed flags. Other discussions,
comment text and anchors are untouched.

Co-Authored-By: GPT-6.2 Astra <noreply@openai.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 10:52:10 +10:00
FredApps 13dc60f05c Restore picture paste when Ctrl+V has image+HTML and no plain text
The merge of main into this branch dropped the post-fill hook in
commands.rs that pastes a clipboard picture when edit.paste has no
plain text. fill() only auto-inserts a bitmap when the HTML looks like
a single image offer, so a browser image plus fallback HTML failed
mod_v_pastes_rich_only_clipboard_and_preserves_picture_routing.
2026-11-28 07:03:14 +07:00
FredApps 2813a0961d Merge origin/main into fix/2909-browser-image-paste 2026-11-28 05:04:48 +07: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
Khawar Zamman Wani ddeab752da Prefer browser image pixels when the clipboard also offers RTF 2026-11-24 20:45:48 +05:30
Khawar Zamman Wani 81ed00867e Preserve picture-only Paste during equation editing 2026-11-24 18:10:19 +05:30
Khawar Zamman Wani 473942d205 Prefer the bitmap when pasting a browser image (#2909) 2026-11-24 16:59:31 +05:30
dotCooCoo 4d1b530601 Language packs test: the refused reason is as wide as Install and fits the list once scrolled
The reason must be at least as wide as its row's Install button. The test
then scrolls the list until the reason is in view and checks that all of
it sits inside the list's visible area, below the Search field and above
the Close footer.
2026-11-24 00:09:38 -08: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
pakiat 64960989a1 Merge commit 'c369c3a20befef8742f8913128cacd79002435d6' into m/6943
# Conflicts:
#	docs/layout-parity.md
2026-11-23 07:41:22 +07: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
dotCooCoo 16160b1e4b Language packs test: the reason starts inside its row
In the Add a language picker, a row's bounds stop at the list's visible
edge, while its failure notice can run past that edge. On CI the Catalan
row ended at y 367 and its notice ran from 349 to 376, so the check that
the notice ends inside the row failed. The test now checks that the
notice starts inside the row and lies within the row's width.
2026-11-22 12:59:53 -08:00
dotCooCoo e414882ffe Merge main into fix/language-picker-row-error
# Conflicts:
#	crates/ui-egui/src/language_packs.rs
2026-11-22 07:44:19 -08:00
Mauro MazzieriandClaude Opus 5.5 ee3ec16a52 Merge main into fix/small-caps-spaces-and-line-height (#7062, #7063)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 18:52:40 +01:00
Mauro MazzieriandClaude Opus 5.5 aaecdd6313 Merge main into fix/picture-line-page-bottom (#7109)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 18:52:09 +01:00
Neil Cawse 509bfce556 Merge remote-tracking branch 'upstream/main' into fix/fonts-fallback-coverage 2026-11-21 17:07:02 +00:00
dotCooCoo 2c6d291c9b Language packs: American spelling in the picker row comment 2026-11-21 07:38:17 -08:00
dotCooCoo d750887f3c Language packs: a refused install's reason shows in its picker row
In Add a language, a row's failure notice (an agent's Install refused
while downloading is off, or a failed install) was added as a second
component under the row, beside the licence line. ListRow puts those
components on one line, so the notice got whatever width the licence
left, and a row with a short licence line, such as Dutch, showed no
notice at all. A row now has one component there: the licence, or a
notice with the failure and the licence.

The new test clicks Install as an agent on the Dutch and Catalan rows
and checks that the reason is inside that row.
2026-11-21 07:24:31 -08: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
Neil Cawse b9e2eaf05c Merge remote-tracking branch 'fork/fix/fonts-fallback-coverage' into fix/fonts-fallback-coverage 2026-11-20 21:12:18 +00:00
Neil Cawse 007970517b fonts: check circle fallback coverage, clear caches on rescan, and keep Supplemental Arrows-C text-style 2026-11-20 21:12:18 +00:00
mmazzieriandClaude Opus 5.5 1131c3120d layout: a page's last line of only pictures at multiple spacing fits while the pictures do (#7109)
With multiple spacing above single, a page's last line may let its leading run into the bottom
margin as long as its text fits (`fit_height`: baseline plus `text_desc`). A line holding only
pictures has nothing below them: they end at the bottom of the font's room and the spacing adds
its share below (`Breaker::measure`, `pictures_alone`). `text_desc` still held the font's
descent, so such a line had to fit a descent it does not have, and a picture Word keeps on the
page moved to the next.

`Line::content_desc` is how far below the baseline the line's content reaches: the text's
descent, or on a line of only pictures their own descent. `fit_height` uses it; `text_desc`
(the caret's extent) is unchanged.

Measured in Word (A4, Calibri 11 pt at 1.15, one text line then an inline picture of height H):
Word keeps H up to 698.6 pt in compatibility mode 11 and 698.2 pt in mode 15, WordCraft kept
697.1 and 696.7; with this change the ten reproducer files (H 696-699, both modes) paginate as
in Word. On 159 local DOC/DOCX files, a real report goes from 19 to Word's 18 pages from its
.doc, Word's .docx and another renderer's .docx; three other PDFs change bytes but render
identically, page by page; the rest are byte-identical.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 08:24:06 +01:00
mmazzieriandClaude Opus 5.5 82325753a8 Layout: small capitals at 80% of the size rounded to the half point, as in Word (#7062)
Word sets small capitals, and Small Caps spaces, at 80% of the run's size rounded to the half point (Times New Roman: 10 pt -> 8, 11 -> 9, 12 -> 9.5, 14 -> 11, 16 -> 13), as it does for superscript. With the exact 80% a 16 pt Small Caps heading was narrower than in Word.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 14:01:18 +01:00
mmazzieriandClaude Opus 5.5 048f21dc77 docs: layout parity for Small Caps spaces and line height (#7062, #7063)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 13:39:13 +01:00
mmazzieriandClaude Opus 5.5 f718a26338 Layout: Small Caps spaces at the small-caps size, Small Caps lines at the full height (#7062, #7063)
Word draws a space (U+0020) and an ideographic space (U+3000) in a Small Caps
run at the small-caps size, like a lowercase letter; a no-break space, the
other Unicode spaces, digits and punctuation keep the full size, and All Caps
wins over Small Caps (measured in Word for Microsoft 365, modes 14 and 15).
WordCraft kept the space at the full size, so Small Caps lines were wider and
broke earlier (#7062).

A small-caps piece is drawn at 80%, but its line is measured at the full size,
as in Word: a line of lowercase Small Caps was shorter than without Small Caps
(#7063).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 13:21:03 +01:00
jayzed80 f674177095 Layout: binary-search the run when checking East Asian font coverage (#6591) 2026-11-19 04:34:29 +00:00
jayzed80 cb0aeadd2f Merge remote-tracking branch 'upstream/main' into fix/autospace-eastasia-font-6591
# Conflicts:
#	crates/layout/src/para/grid.rs
#	docs/layout-parity.md
2026-11-18 23:35:02 +00:00
jayzed80 4e79e67534 Merge remote-tracking branch 'upstream/main' into HEAD
# Conflicts:
#	crates/layout/src/tests.rs
2026-11-18 21:15:56 +00:00
pakiat 0f83ea9cf4 Merge commit '6ef13b2cc8a60e6391d7a5b92459ec47598d58a9' into m/6943
# Conflicts:
#	docs/gaps.md
2026-11-18 22:32:56 +07:00
FredApps d789f82465 Merge remote-tracking branch 'origin/main' into pr-2340 2026-11-18 21:05:53 +07:00
FredApps 6da8a86a41 Merge remote-tracking branch 'origin/main' into fix/section-hex-numformat-and-cardinal-millions 2026-11-18 20:21:58 +07:00
Hamza a3758cd90c Merge remote-tracking branch 'origin/main' into reproducible-saved-dates
# Conflicts:
#	crates/engine/src/io_ext.rs
2026-11-18 15:32:14 +05:00
Neil Cawse 74345b2e25 fix(fonts): invalidate cached file coverage when a font is replaced in place 2026-11-18 03:47:59 +00:00
Neil Cawse 0759433433 Merge remote-tracking branch 'upstream/main' into fix/fonts-fallback-coverage 2026-11-18 03:44:40 +00:00
jayzed80 c158887d9a #6899: Compare clears a foreign del from an inserted paragraph's mark
A whole paragraph inserted by compare took only the compare's ins on its
mark, but kept a del the revised document's mark already carried (a
pending deletion by another author). On accept, resolve_para took the
deletion branch and removed or joined away the inserted paragraph,
losing the inserted break. mark_block now takes a mark-only step, and
the revised side clears del on every paragraph mark it stamps,
including inside table cells; run-level revisions are left alone.
2026-11-17 23:49:12 +00:00
pakiatandClaude Opus 5.5 0859a447b6 Tables: a first row's w:tblPrEx left border is the half border a table moves in by
From mode 15 Word moves a table in by half its first cell's left border. The
cell's own border comes first, then the first row's table property exceptions,
then the table's. Measured in Word for Windows: an 8 pt table border with a 2 pt
exception puts the text 1 pt in, inline and floating. Inline tables had the
same gap, so both use one helper now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 06:13:43 +07:00
pakiat df07115145 Merge commit '22a73d9f2d10de6ee52780ab4a6019b864d9c598' into m/6943
# Conflicts:
#	docs/gaps.md
2026-11-18 06:09:09 +07:00
pakiatandClaude Opus 5.5 a761f276d5 Tables: a floating table placed by an offset takes its indent before Word 2013, half its border from it
Measured in Word for Windows 16.0.20527: before Word 2013 layout a
floating table placed by an offset has its first cell's text at the
offset moved by w:tblInd (WordCraft ignored the indent); from Word 2013
its edge is at the offset moved in by half its left border (WordCraft
left out the half border) and w:tblInd doesn't move it. Moved below
another floating table, it keeps its distance from the text's edge the
same way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 21:49:39 +07:00
Neil Cawse fa3eb9f303 Merge remote-tracking branch 'upstream/main' into fix/fonts-fallback-coverage 2026-11-17 13:00:58 +00:00
Martin Ball d6e7695538 Merge branch 'main' into fix/autofit-stale-grid 2026-11-17 13:42:47 +01:00
Neil Cawse a5f3120d59 Merge remote-tracking branch 'upstream/main' into fix/fonts-fallback-coverage 2026-11-17 03:22:04 +00:00
Neil Cawse fadbfdf0e6 Merge remote-tracking branch 'upstream/main' into fix/fonts-fallback-coverage 2026-11-14 18:04:36 +00:00
jayzed80 104fa6133d Layout: no automatic space beside an ideograph its run's installed East Asian font lacks (#6591)
Word adds no autoSpaceDE/autoSpaceDN room when the run's w:eastAsia font
has no ideographs, though a substituted face draws them. A declared font
that isn't installed keeps the space.
2026-11-14 06:50:23 +00:00
jayzed80 b687f1cd6f Address review: keep separated link runs in separate Link elements (#6464) 2026-11-14 01:18:00 +00:00
jayzed80 50041c808c Address review: keep a re-placed float's x, and don't move a wrap area onto the first line (#6567)
A float placed again from a pushed-down first line takes only its new
vertical position, so its drawn rect and wrap area stay together across.
A wrapping float whose moved area would reach the first line stays where
it was: that line was laid out without it in the way.
2026-11-14 01:02:27 +00:00
jayzed80 c0c42caf95 Layout: measure sibling paragraph floats from a wrapped first line (#6567) 2026-11-14 00:13:46 +00:00
jayzed80 8f8bec4ad7 Tag PDF link annotations with Link and OBJR (#6464) 2026-11-13 23:04:30 +00:00
Neil Cawse 12a29586d0 Merge remote-tracking branch 'upstream/main' into fix/fonts-fallback-coverage 2026-11-13 22:55:33 +00:00
Neil Cawse ace0cc6a10 Merge remote-tracking branch 'upstream/main' into fix/fonts-fallback-coverage 2026-11-13 19:46:00 +00:00
Neil Cawse 832462d0cf Merge remote-tracking branch 'upstream/main' into fix/fonts-fallback-coverage 2026-11-13 19:00:46 +00:00
Fin Warman 925ec333cf Autofit tables take complete point-width rows over a stale grid
When an autofit table's stated width differs from its tblGrid total but
matches complete point-width rows (spans allowed), columns take the cell
widths.
2026-11-12 16:07:16 +00: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
Neil Cawse 02bcba5f71 Merge remote-tracking branch 'upstream/main' into fix/fonts-fallback-coverage 2026-11-11 18:35:52 +00:00
Neil Cawse 2d986748df test(fonts): use drop guards for temp files and dirs in fontdb tests 2026-11-11 02:17:33 +00:00
Neil Cawse c80709b51e Merge remote-tracking branch 'origin/main' into fix/fonts-fallback-coverage 2026-11-11 02:15:33 +00:00
Neil Cawse 78126b013a test(fonts): remove temporary TTC file before assertions 2026-11-09 22:39:06 +00:00
Neil Cawse d7ec5e2ed2 Merge remote-tracking branch 'origin/main' into fix/fonts-fallback-coverage 2026-11-09 22:38:15 +00:00
Neil Cawse d593088a31 refactor(fonts): share compact/MAX_FACES/MAX_RANGES in fallback_data and test sys.tried rescan 2026-11-09 14:21:05 +00:00
Neil Cawse 525a6a8f89 refactor(fonts): deduplicate TTC cmap reads, preserve coverage index across rescan, and test fallback skip/rescan 2026-11-08 13:34:26 +00:00
Neil Cawse 6102a64112 refactor(fonts): deduplicate coverage index sync and test >40 MiB TTC coverage 2026-11-08 13:34:26 +00:00
Neil Cawse 477bda7726 fonts: check family cmap coverage before loading fallback fonts and clear caches on rescan 2026-11-08 13:34:26 +00:00
Hamza 531a0d1f1d Merge remote-tracking branch 'origin/main' into reproducible-saved-dates
# Conflicts:
#	apps/wordcraft-cli/src/main.rs
#	crates/engine/src/cmd.rs
#	crates/engine/src/print.rs
2026-11-05 15:09:39 +05:00
Harrison Booth ae0f30fa23 Document emphasis round-trip test 2026-11-04 20:04:50 -06:00
Harrison Booth 55da823f01 Make emphasis dot test value explicit 2026-11-04 19:47:14 -06:00
Harrison Booth f7eadd7781 Resolve duplicate emphasis in DOCX fixture 2026-11-04 19:30:43 -06:00
Harrison Booth ecab532500 Merge latest main into East Asian emphasis marks 2026-11-04 19:24:24 -06:00
Dhruv 9cdc60b2c1 Home › Numbering: add the a. b. c. preset; picking another preset changes a numbered list instead of turning it off (#4281) 2026-11-04 10:30:53 -06:00
Dhruv 2973a2f4f3 A list item that changes level takes the new level's indents and drops a direct indent (#4287) 2026-11-04 10:30:11 -06:00
Dhruv 8e90f8f336 Replace All replaces in every story: headers, footers, footnotes, endnotes and text boxes (#3300) 2026-11-04 10:29:46 -06:00
Harrison Booth 1121b3146c Merge origin/main into DOCX emphasis branch 2026-11-04 07:59:32 -06:00
Harrison Booth 36a64b39c4 Merge origin/main into wc-docx-emphasis 2026-11-04 06:38:59 -06:00
Harrison Booth 64e9f2d24f DOCX: retain emphasis test assertions through save cycles 2026-11-04 06:38:52 -06:00
Harrison Booth 52773d2f7b Merge remote-tracking branch 'origin/main' into wc-harfrust 2026-11-03 22:04:02 -06:00
Harrison Booth 3ecc43c062 Merge remote-tracking branch 'origin/main' into wc-harfrust 2026-11-03 17:58:55 -06:00
Harrison Booth 2be939832b Document East Asian emphasis preservation 2026-11-03 17:20:16 -06:00
VoiceLessQ 3b73a84082 AutoSave: the switch shows a document opened from bytes as blocked
The title bar lifted NotSavedHere whatever read_from said, while set_autosave refused unless the document was read from its path, so the switch of a document opened from bytes looked available and a click did nothing. Both now use autosave_switch_block: the switch shows the block and offers Save As. file.autosave also puts a refusal on the status line, as other commands do, instead of returning early without it.
2026-11-03 17:51:02 -02:00
Hamza 2525eaee12 SOURCE_DATE_EPOCH: warn when it is set and unusable, and show it dates the file, not the edits in it 2026-11-03 17:39:39 +05:00
Hamza ed14477f19 A creation date the PDF writer cannot read is pinned too
`pdf_document` stood in for the date only when `core.created` was empty, but the
.docx reader takes that property as it finds it, so a file can arrive holding
something like `not-a-date`. `metadata` cannot put that in a PDF and falls back
to the clock, so two exports of one document differed although SOURCE_DATE_EPOCH
was set -- the one thing it is there to stop (noted in review).

The question asked is now the writer's own. `wordcraft_pdf::reads_as_date` wraps
the parser the writer uses, so the two cannot drift apart: whatever `metadata`
would reject is what gets stood in for. A date it accepts is still kept.

Also a flake in this test harness, which the added iterations made likely rather
than introduced: the temporary directory was named from the pid and `as_nanos`,
and `as_nanos` carries microsecond granularity on macOS, so two of these tests
starting in the same microsecond took the same directory and overwrote each
other's input. It takes a sequence number as well now, and `create_dir` rather
than `create_dir_all`, so a name that does repeat fails there instead of quietly
sharing. Eight consecutive runs of the file: 3 failures before, 0 after.
2026-11-02 15:51:32 +05:00
Harrison Booth 53e520e805 DOCX: merge main into East Asian emphasis marks 2026-10-30 13:46:38 -05:00
VoiceLessQ 1603a5f34f AutoSave: only an open that read a file records it
file.open with a null path only asks for the Open picker, and its
result has no alreadyOpen, so the check recorded the shown document's
path as read from disk: a document opened from bytes then passed the
AutoSave switch's check. The path must now be a string and alreadyOpen
false. A data value that isn't a string is ignored by the engine,
which reads the file from disk, so it no longer clears the record.
2026-10-29 16:25:01 -02:00
VoiceLessQ d5239891f6 AutoSave: switching it off holds for that document
The AutoSave preference is shared by all documents, but each keeps its
own go-ahead (the file it may write). Switching AutoSave off cleared
only the preference, so turning it on in another document brought it
back for the first one too, which then wrote its file with its switch
showing off. Switching off now also withdraws the document's go-ahead.
Turning it back on covers the same file again without a save, since
the document was read from or saved to it.
2026-10-29 15:30:43 -02:00
VoiceLessQ 9c7ec843b6 AutoSave: the switch covers only a file the document was read from
file.open with data only names the file (the bytes come with the call),
but the name becomes the document's path, and since #3307 the AutoSave
switch gave the go-ahead to write it. A control-channel caller could
open any bytes under the name of an existing .docx, and turning AutoSave
on then wrote over that file. The window now notes, per document, the
file it was read from or saved to, and the switch's go-ahead needs the
path to be that file. A document opened from bytes still gets AutoSave
after an explicit save.
2026-10-29 15:30:34 -02:00
VoiceLessQ 777fedb14a Engine tests: the fuzz also fails on a panic in a command another ran
Review of #4207. Commands run other commands through Session::run
(outline.promote runs para.promote), and the inner guard names the inner
command: "para.promote panicked: ...". run_junk only looked for the
fuzzed command's own id, so such a panic passed. caught_panic now takes
any registered command's id before " panicked: "; an error that only
echoes those words (developer.control quoting its input) still doesn't
count.
2026-10-29 14:23:50 -02:00
VoiceLessQ 02de1488cb Merge origin/main 2026-10-29 14:21:19 -02:00
Harrison Booth 01a6084673 DOCX: preserve East Asian emphasis marks 2026-10-29 08:00:54 -05:00
Harrison Booth a848e90b3a DOCX: preserve run grid and web-hidden properties 2026-10-29 07:34:21 -05:00
Hamza 77af00b4e5 Saving and exporting: SOURCE_DATE_EPOCH stands in for the clock
A saved document recorded the second it was saved in, and a PDF export
recorded the second it was exported in, so saving or exporting one document
twice gave different bytes although the content matched.

SOURCE_DATE_EPOCH stands in for the clock where no date is given, as the
reproducible-builds specification defines it. A value the document's date
format cannot hold is ignored rather than refusing the save. An existing
creation date is still kept, so only the parts that really are "now" move.

Rebased onto main, 785 commits on: engine's cmd/mod.rs is cmd.rs now, and
`stamp_save` moved to session/history.rs, so `saved_iso` is applied there.
Upstream has since added a `numeral` option to the PDF export, which is kept
alongside this PR's change to the document the exporter is given.
2026-10-28 20:29:14 +05:00
Harrison Booth 999f0c0973 Fonts: a run the shaper could not finish falls back to the cmap, run by run 2026-10-27 19:09:43 -05:00
Harrison Booth 6117f95e1c Merge origin/main into wc-harfrust 2026-10-27 19:07:31 -05:00
Harrison Booth 6c8a6bd6f7 Merge remote-tracking branch 'origin/main' into wc-merge-4582
# Conflicts:
#	crates/fonts/src/lib.rs
2026-10-27 14:27:11 -05:00
VoiceLessQ 9c05751014 Merge origin/main
Main split lib.rs and chrome.rs, so the AutoSave changes now live in app/files.rs, state.rs, tests.rs and chrome/tests.rs.
2026-10-27 16:39:42 -02:00
Harrison Booth fe2b22792d deps: harfrust 0.15 (Font, ShaperFont and Buffer replace FontRef, ShaperData and UnicodeBuffer) 2026-10-27 08:44:30 -05:00
VoiceLessQ 6d51d93bb6 AutoSave: a value that isn't true or false is an error (#3307)
`file.autosave` read `value` with as_bool and toggled when that gave nothing. Since the switch can now turn AutoSave on for a file only opened here, `{"value":"false"}` on such a file turned it on and gave AutoSave the go-ahead to rewrite it. A missing value still toggles; anything other than a bool is now refused, the way the focus ribbon and other ui commands already do it. Found in review.

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

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

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

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

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

Tests: making edit.repeat panic on null params fails the fuzz with
"edit.repeat panicked: mutation"; before this change the same mutation
passed.
2026-10-24 21:00:37 -01:00
Divyanshu Gupta 59e818424c fix(doc): handle start 0 list counters and preserve literal %0 placeholders 2026-10-16 07:31:55 +05:30
Divyanshu Gupta ab35bfa946 fix(doc): format hex number format as uppercase hex and support millions in cardinal text 2026-10-16 07:27:30 +05:30
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
ahutsunshin e3db9896fb security: use explicit u64 literal for 2 GB file size limit
Change '2 << 30' to '2u64 << 30'. While Rust's type inference handles the
comparison with meta.len() (u64), making the type explicit documents intent
and guards against potential debug-mode overflow traps if the constant is
ever increased past the i32 boundary.
2026-10-14 12:34:49 +08:00
229 changed files with 11907 additions and 5184 deletions
+1 -1
View File
@@ -73,7 +73,7 @@ WordCraft is a Rust word processor targeting Microsoft Word parity, for macOS, W
- `unsafe`: none; the workspace forbids it. Typing behaviour is pinned by `crates/engine/src/tests/typing.rs` and described in `docs/typing-parity.md`.
- Attribution: `ATTRIBUTION.md`, a row per asset file, checked by `cargo xtask assets`. Icons are our own SVG set in `crates/ui-egui/icons/` (draw new icons there); sample content is in `crates/engine/src/sample.rs` and `cmd/design.rs`.
- Fonts and language data come from other repositories as optional build inputs: craft-fonts through `CRAFT_FONTS_DIR`, and craft-i18n's `language-data/` through `CRAFT_I18N_DIR` (pinned by `craft-i18n.rev`; CI checks it out). Without craft-i18n the app builds with fallback spelling and no pattern hyphenation, so proofing tests need it. Proprietary font requests use installed fonts or the open substitutes in `crates/fonts/src/word.rs`. Layout tests use the fixed fonts in `assets/fonts/` ([docs/testing.md](docs/testing.md)).
- Run: `cargo run --release -p wordcraft -- --sample --control 7981` starts the app with a sample document and the control channel. It takes JSON lines on `127.0.0.1:7981`: authenticate once per connection with the token from `~/.config/wordcraft/control-key.local-7981` (macOS: `~/Library/Application Support/WordCraft/`), `{"id":1,"method":"auth","params":{"token":"…"}}`, then send requests without a token; methods are in `crates/ui-egui/src/control.rs`, docs in `docs/control-protocol.md` (Token). Headless screenshots: `cargo run --release -p wordcraft-ui-egui --example ui_shot -- script.jsonl`. CLI: `wordcraft-cli convert|run|commands|parity`. MCP: `wordcraft-cli mcp --automation-read-root DIR --automation-write-root DIR` (both required; `--connect` is refused until the app confines its control channel, #3695), see `docs/mcp.md`.
- Run: `cargo run --release -p wordcraft -- --sample --control 7981` starts the app with a sample document and the control channel. It takes JSON lines on `127.0.0.1:7981`: authenticate once per connection with the token from `~/.config/wordcraft/control-key.local-7981` (macOS: `~/Library/Application Support/WordCraft/`), `{"id":1,"method":"auth","params":{"token":"…"}}`, then send requests without a token; methods are in `crates/ui-egui/src/control.rs`, docs in `docs/control-protocol.md` (Token). Headless screenshots: `cargo run --release -p wordcraft-ui-egui --example ui_shot -- script.jsonl`. CLI: `wordcraft-cli convert|run|commands|parity`. MCP: plain `wordcraft-cli mcp` reaches the open window while ArtCraft Launcher › Settings › AI agents is on (`crates/ui-egui/src/agents.rs`, `crates/mcp/src/live.rs`); `--headless`, or the switch off, needs `--automation-read-root DIR --automation-write-root DIR`; see `docs/mcp.md`.
- Headless column ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): `cargo xtask parity` marks a catalog feature `headless: yes` only when its command is in the engine registry that `wordcraft-cli` and the MCP server load (never a `ui.*` id). A missing feature takes its `no`/`partial` value and `reach:` (`window`, `os` or `engine-gap`) from `HEADLESS` in `crates/engine/src/catalog.rs`, or reads `unknown`. When a command lands, delete its mark; `headless_marks_are_current` fails on a stale one.
- Notes and progress: `plan/` is an optional gitignored notebook. Committed: `ROADMAP.md` (progress log), `docs/gaps.md`, `docs/roadmap.md`, `docs/target-app-parity.md`, `docs/architecture.md` and the parity checklists.
- Contributor credits: `docs/contributors.md`.
Generated
+173 -131
View File
File diff suppressed because it is too large Load Diff
+55 -55
View File
@@ -13,7 +13,7 @@ run_slots = 3
test_threads = 4
[workspace.package]
version = "0.18.1"
version = "0.20.1"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
@@ -37,22 +37,22 @@ wordcraft-pdf = { path = "crates/pdf" }
# reads the ca-valencia pack), #589 (French elision suggestions first), #497 (flag-based
# compounding), #496 (review follow-ups, en-AU) and the merged #482–#490/#495 stack; the font
# store's `language-pack` kind is #486 (CP4.1).
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
wordcraft-engine = { path = "crates/engine" }
wordcraft-mcp = { path = "crates/mcp" }
wordcraft-zotero = { path = "crates/zotero" }
wordcraft-control-key = { path = "crates/control-key" }
wordcraft-ui-egui = { path = "crates/ui-egui" }
wordcraft-validate = { path = "crates/validate" }
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0", default-features = false }
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
craft = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0", default-features = false }
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c" }
# foundation
kurbo = { version = "0.13", features = ["serde"] }
@@ -75,7 +75,7 @@ regex-automata = { version = "0.4", default-features = false, features = ["std",
# text / rendering / formats
skrifa = "0.47"
harfrust = "0.13"
harfrust = "0.15"
# WOFF / WOFF2 web fonts added by the user (#582): pure Rust (MIT); its brotli and zlib decoders
# (brotli-decompressor, flate2) are already in the tree.
wuff = "0.2.9"
@@ -85,28 +85,28 @@ wuff = "0.2.9"
brotli-decompressor = "5"
vello_cpu = "0.2"
image = { version = "0.25", default-features = false }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0", default-features = false, features = ["write"] }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0", default-features = false, features = ["write"] }
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0", features = ["doc"] }
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0", features = ["text"] }
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0", features = ["flow"] }
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0", features = ["detect"] }
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0", features = ["doc"] }
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0", features = ["text"] }
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0", features = ["flow"] }
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0", features = ["detect"] }
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
# zlib streams (compressed metafile pictures in `.doc` drawings); already in the lock as a dependency of other crates.
miniz_oxide = "0.9"
cfb = "0.15"
@@ -174,27 +174,27 @@ debug = 0
# The framework's patches, which Cargo does not carry over to dependents: its vendored crates from craft-libs,
# and the egui and winit forks it builds with.
[patch.crates-io]
krilla = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
hayro = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
emath = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
egui = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c" }
hayro = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
emath = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
winit = { git = "https://github.com/storytold/winit.git", rev = "3fd7ae64762f82a73b78bd24f453f82c4291067d" }
+9 -2
View File
@@ -205,13 +205,17 @@ Web: `cd apps/wordcraft-web && trunk serve`, then open <http://127.0.0.1:8771/?s
WordCraft was designed to be driven by people *and* by AI agents.
With ArtCraft Launcher › Settings › AI agents on, AI apps reach the open WordCraft window through
the launcher's one `ArtCraft` entry: tool calls act in the window, and files go to the agent folder
(`Documents/ArtCraft/Agents/WordCraft`, or the folders in File › Options › Agents). Without the
launcher:
```sh
# headless documents; the agent reads only inside the first folder and writes only inside the second
claude mcp add wordcraft -- wordcraft-cli mcp --automation-read-root DIR --automation-write-root DIR
```
Both roots are required. Bridging an agent to the running app (`mcp --connect`) is refused until
the app confines its control channel to the same roots (#3695).
A headless server needs both roots.
Tools include `list_commands`, `execute`, `batch`, `type_text`, `select_text`, `inspect_document`,
`render_page` and `save_document`. Agents
@@ -386,9 +390,12 @@ emerge --ask app-office/wordcraft-bin
### FreeBSD
Prebuilt FreeBSD release archives target FreeBSD 15.1 or newer; FreeBSD 14.x is not supported by these builds.
| Build | File |
|---|---|
| x86_64 | `wordcraft-<ver>-freebsd-x86_64.tar.gz` |
| aarch64 | `wordcraft-<ver>-freebsd-aarch64.tar.gz` |
### Web (WebAssembly)
+4 -1
View File
File diff suppressed because one or more lines are too long
+182 -44
View File
@@ -54,16 +54,25 @@ USAGE:
wordcraft-cli commands [--json] list every command
wordcraft-cli parity [--markdown] feature-catalog parity
wordcraft-cli validate <file> [--json] structural integrity check (exit 0 pass, 1 fail, 2 incomplete, 3 usage/IO)
wordcraft-cli mcp --automation-read-root DIR --automation-write-root DIR [--author NAME]
MCP server on stdio, with a headless session.
Both roots are required: the agent's commands read
files (open, insert text or picture, mail-merge data,
templates…) only inside the read root and write them
(save, export, merge output…) only inside the write
root, links followed; the same folder may be both.
--connect HOST:PORT (bridge to the running app) is
refused until the app confines its control channel
(#3695, #5819).
wordcraft-cli mcp [--automation-read-root DIR --automation-write-root DIR] [--headless]
[--when-closed launch|headless|error] [--author NAME]
MCP server on stdio. While AI agents are on in
ArtCraft Launcher › Settings › AI agents, each tool
call goes to the open WordCraft window, working in
its agent folder (File › Options › Agents); while
WordCraft is closed, --when-closed or that page's
choice decides: open it, work without a window, or
ask to open it. Otherwise, and with --headless, a
headless session, which needs both roots: the
agent's commands read files (open, insert text or
picture, mail-merge data, templates…) only inside
the read root and write them (save, export, merge
output…) only inside the write root, links followed;
the same folder may be both. Given with AI agents
on, the roots replace the agent folder for headless
work. --author names the author of a headless
session's tracked changes and comments.
--connect HOST:PORT is deprecated and ignored.
wordcraft-cli zotero <command> <file> [--cmd 'id={json}' …] [--save OUT] [--trace] [--port P]
run a Zotero command on a document (Zotero must be
running): addEditCitation, addEditBibliography,
@@ -261,6 +270,17 @@ fn find_option_arg<'a>(args: &'a [String], name: &str) -> OptionArg<'a> {
}
}
/// `mcp --author NAME`: absent is the default author; a flag without a name, or given twice, is a
/// usage error, never an unnamed session or the next option taken as the name.
fn mcp_author(args: &[String]) -> Result<Option<String>, String> {
match find_option_arg(args, "--author") {
OptionArg::Absent => Ok(None),
OptionArg::Duplicate => Err("mcp: duplicate --author option".into()),
OptionArg::MissingValue => Err("mcp: --author requires a name".into()),
OptionArg::Value(name) => Ok(Some(name.to_string())),
}
}
fn parse_page_arg(command: &str, args: &[String]) -> Result<Option<u64>, String> {
match find_option_arg(args, "--page") {
OptionArg::Absent => Ok(None),
@@ -376,13 +396,86 @@ const VALIDATE_OPTIONS: &[OptionSpec] = &[OptionSpec { name: "--json", takes_val
const MCP_NEEDS_ROOTS: &str = "mcp: give both --automation-read-root DIR and --automation-write-root DIR: an agent's \
commands may read only inside the read root and write only inside the write root (the same folder may be both)";
/// Why `mcp --connect` is refused: the running app would not confine the agent's file access.
// lean: refused outright; allow it once the app confines its control channel and reports both roots.
const MCP_CONNECT_REFUSED: &str = "mcp: --connect is refused for now: the desktop app does not confine its control \
channel to automation roots yet (storytold/wordcraft#3695, #5819). Use the headless server: wordcraft-cli mcp \
--automation-read-root DIR --automation-write-root DIR";
/// Why `mcp` won't start while the suite's AI-MCP flag is on but the launcher's switch keeps agents
/// out of the window: without roots it would have no folders to work in.
const MCP_NEEDS_ROOTS_OR_AGENTS: &str = "mcp: give both --automation-read-root DIR and --automation-write-root DIR, or \
turn on AI agents in ArtCraft Launcher › Settings › AI agents to work in WordCraft's open window and its agent folder";
const MCP_OPTIONS: &[OptionSpec] = &[OptionSpec { name: "--connect", takes_value: true }, OptionSpec { name: "--author", takes_value: true }];
/// `--connect HOST:PORT`, from before plain `mcp` found the window by itself: kept for one release,
/// ignored with this note on stderr, then removed.
const MCP_CONNECT_DEPRECATED: &str = "wordcraft-cli: --connect is deprecated and will be removed in the next release: \
plain `wordcraft-cli mcp` finds the open WordCraft window by itself while AI agents are on in ArtCraft Launcher › \
Settings › AI agents. The address given is not used.";
const MCP_OPTIONS: &[OptionSpec] = &[
OptionSpec { name: "--headless", takes_value: false },
OptionSpec { name: "--when-closed", takes_value: true },
OptionSpec { name: "--author", takes_value: true },
];
/// Takes the deprecated `--connect` out of `args`, with its value (written apart, unless it is
/// another option, or as `--connect=…`): whether it was there.
fn take_connect(args: &mut Vec<String>) -> bool {
let mut found = false;
let mut i = 0;
while let Some(arg) = args.get(i) {
if arg == "--connect" {
found = true;
let with_value = args.get(i + 1).is_some_and(|v| !v.starts_with("--"));
args.drain(i..if with_value { i + 2 } else { i + 1 });
} else if arg.starts_with("--connect=") {
found = true;
args.remove(i);
} else {
i += 1;
}
}
found
}
/// The suite's AI-MCP flag and whether the ArtCraft Launcher's switch lets agents use WordCraft.
#[cfg(not(test))]
fn agents_state() -> (bool, bool) {
let flag = wordcraft_mcp::live::mcp_flag();
(flag, flag && wordcraft_mcp::live::agents_allowed_now())
}
/// Unit tests run `mcp` as without the suite's flag, whatever this machine's flags say; the plan
/// itself is tested for every combination (`mcp_plan`), and the binary's tests set the flag.
#[cfg(test)]
fn agents_state() -> (bool, bool) {
(false, false)
}
/// How `mcp` runs.
#[derive(Debug)]
enum McpPlan {
/// A headless session confined to both roots.
Headless(std::sync::Arc<wordcraft_engine::file_access::AutomationRoots>),
/// The open window while agents may use it, otherwise a headless session in the given roots
/// or the app's agent folder ([`wordcraft_mcp::Live`]).
Live(Option<std::sync::Arc<wordcraft_engine::file_access::AutomationRoots>>),
}
/// `mcp`'s plan. With `--headless`, or without the suite's AI-MCP flag (`flag`), a headless session
/// that needs both roots (shared rule 18). With the flag, the live client when the launcher's
/// switch lets agents in (`switch`) or both roots are given, so nothing it does is unconfined;
/// otherwise a refusal.
fn mcp_plan(
roots: Option<std::sync::Arc<wordcraft_engine::file_access::AutomationRoots>>,
headless: bool,
flag: bool,
switch: bool,
) -> Result<McpPlan, &'static str> {
let both = roots.clone().filter(|r| r.read_root().is_some() && r.write_root().is_some());
if headless || !flag {
return both.map(McpPlan::Headless).ok_or(MCP_NEEDS_ROOTS);
}
if switch || both.is_some() {
return Ok(McpPlan::Live(roots));
}
Err(MCP_NEEDS_ROOTS_OR_AGENTS)
}
const ZOTERO_OPTIONS: &[OptionSpec] = &[
OptionSpec { name: "--cmd", takes_value: true },
OptionSpec { name: "--save", takes_value: true },
@@ -563,6 +656,17 @@ fn run_source_paths(rest: &[String], script: Option<&script::Script>) -> (Option
(from_file, from_template)
}
/// Show a successful command's result, or its warning when results aren't printed.
fn report_run_result(id: &str, result: &Value, print: bool) -> Result<(), Failure> {
if print {
return write_stdout(|o| writeln!(o, "{id}: {result}"));
}
if let Some(warning) = result.get("warning").and_then(Value::as_str) {
let _ = writeln!(std::io::stderr().lock(), "wordcraft-cli: warning: {}", escape_text(warning, false));
}
Ok(())
}
/// Run the subcommand named by `args` (the command line after the program name). Files named
/// there are opened by their real names, which may not be valid Unicode.
fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
@@ -666,9 +770,7 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
let print = rest.iter().any(|a| a == "--print");
for (n, (id, params)) in script.iter().flat_map(|c| c.commands.iter()).enumerate() {
let r = s.run(id, params).map_err(|e| engine_error(format!("command {} ({id}): {e}", n + 1)))?;
if print {
write_stdout(|o| writeln!(o, "{id}: {r}"))?;
}
report_run_result(id, &r, print)?;
}
let mut i = 0;
while i < rest.len() {
@@ -681,9 +783,7 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
None => (spec.clone(), json!({})),
};
let r = s.run(&id, &params).map_err(|e| engine_error(format!("{id}: {e}")))?;
if print {
write_stdout(|o| writeln!(o, "{id}: {r}"))?;
}
report_run_result(&id, &r, print)?;
i += 2;
} else {
i += 1;
@@ -747,28 +847,7 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
}
}
"validate" => run_validate(file.as_deref(), &rest),
"mcp" => {
let (roots, rest) = automation_roots("mcp", &rest)?;
// Refused with or without a value, before the option check, so `--connect=…` gets this refusal rather than
// "unknown option": a bare trailing `--connect` must not slip past either.
if rest.iter().any(|a| a == "--connect" || a.starts_with("--connect=")) {
return Err(MCP_CONNECT_REFUSED.into());
}
validate_options("mcp", &rest, MCP_OPTIONS)?;
// Shared rule 18 (#7124): an agent entry point never runs unconfined.
let Some(roots) = roots.filter(|r| r.read_root().is_some() && r.write_root().is_some()) else {
return Err(MCP_NEEDS_ROOTS.into());
};
// Every thread of this process, not only the server's: nothing reaches past the roots.
wordcraft_engine::file_access::confine_process(roots.clone());
let show = |root: Option<&std::path::Path>| root.map_or_else(|| "none".to_string(), |r| r.display().to_string());
eprintln!("wordcraft-cli: files confined: read root {}, write root {}", show(roots.read_root()), show(roots.write_root()));
let backend: Box<dyn wordcraft_mcp::Backend> = Box::new(headless_mcp(roots, arg_value(&rest, "--author").as_deref())?);
let mut server = wordcraft_mcp::Server::new(backend);
let stdin = std::io::stdin();
// A client that closes our stdout has hung up: `serve` returns BrokenPipe and we end cleanly.
Ok(server.serve(stdin.lock(), std::io::stdout())?)
}
"mcp" => run_mcp(&rest),
"zotero" => {
validate_options("zotero", &rest, ZOTERO_OPTIONS)?;
let paths = positionals(&rest, ZOTERO_OPTIONS);
@@ -818,6 +897,60 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
}
}
/// `wordcraft-cli mcp`: serves MCP on stdin and stdout, headless or through the open window.
fn run_mcp(rest: &[String]) -> Result<(), Failure> {
let (roots, mut rest) = automation_roots("mcp", rest)?;
// Taken out before the option check, with or without a value, so it never reads as unknown.
if take_connect(&mut rest) {
eprintln!("{MCP_CONNECT_DEPRECATED}");
}
validate_options("mcp", &rest, MCP_OPTIONS)?;
let when_closed = match (rest.iter().any(|a| a == "--when-closed"), arg_value(&rest, "--when-closed")) {
(false, _) => None,
(true, value) => {
Some(value.as_deref().and_then(wordcraft_mcp::live::WhenAppClosed::parse).ok_or("mcp: --when-closed takes launch, headless or error")?)
}
};
let author = mcp_author(&rest)?;
let (flag, switch) = agents_state();
let show = |root: Option<&std::path::Path>| root.map_or_else(|| "none".to_string(), |r| r.display().to_string());
let backend: Box<dyn wordcraft_mcp::Backend> = match mcp_plan(roots, rest.iter().any(|a| a == "--headless"), flag, switch)? {
McpPlan::Headless(roots) => {
// Shared rule 18 (#7124): an agent entry point never runs unconfined. Every thread of this process,
// not only the server's: nothing reaches past the roots.
wordcraft_engine::file_access::confine_process(roots.clone());
eprintln!("wordcraft-cli: files confined: read root {}, write root {}", show(roots.read_root()), show(roots.write_root()));
Box::new(headless_mcp(roots, author.as_deref())?)
}
McpPlan::Live(roots) => {
let mut config = wordcraft_mcp::LiveConfig::installed()
.ok_or("mcp: can't find WordCraft's settings folder (no home folder; set WORDCRAFT_PROFILE_DIR)")?;
if let Some(roots) = &roots {
config.read_root = roots.read_root().map(std::path::Path::to_path_buf);
config.write_root = roots.write_root().map(std::path::Path::to_path_buf);
// Both roots given: every headless session works in them, so the whole process is confined to
// them. Calls to the window run in the app, inside its agent folders.
if config.read_root.is_some() && config.write_root.is_some() {
wordcraft_engine::file_access::confine_process(roots.clone());
}
}
config.when_closed = when_closed;
config.author = author;
config.launch = std::env::current_exe().ok().and_then(|exe| wordcraft_mcp::live::launcher(&exe));
eprintln!(
"wordcraft-cli: tool calls go to the open WordCraft window while AI agents are on in ArtCraft Launcher, otherwise to a headless session (read root {}, write root {}; none: WordCraft's agent folder)",
show(config.read_root.as_deref()),
show(config.write_root.as_deref())
);
Box::new(wordcraft_mcp::Live::new(config))
}
};
let mut server = wordcraft_mcp::Server::new(backend);
let stdin = std::io::stdin();
// A client that closes our stdout has hung up: `serve` returns BrokenPipe and we end cleanly.
Ok(server.serve(stdin.lock(), std::io::stdout())?)
}
/// At most 400 characters of `s`, for traces.
fn clip(s: &str) -> String {
match s.char_indices().nth(400) {
@@ -1063,6 +1196,11 @@ fn main() -> ExitCode {
eprintln!("wordcraft-cli: --launch-profile and --profile-root are the desktop app's Nightly bootstrap, not a CLI option");
return ExitCode::from(2);
}
// The engine logs this, but the command line installs no logger, and it is where a
// reproducible build runs.
if let Some(problem) = wordcraft_engine::cmd::source_date_epoch_problem() {
eprintln!("wordcraft-cli: warning: {problem}");
}
// Language packs installed in the suite's font store are used; `proof.installPack` installs
// only while the person has turned downloading on in the app.
wordcraft_engine::packs::use_font_store(false);
+118 -21
View File
@@ -38,7 +38,7 @@ fn validators_accept_only_the_documented_options() {
assert!(validate_options("run", &args(&["--cmd", "text.insert={}", "--cmd", "edit.undo", "--print"]), RUN_OPTIONS).is_ok());
assert!(validate_options("commands", &args(&["--json"]), COMMANDS_OPTIONS).is_ok());
assert!(validate_options("parity", &args(&["--markdown"]), PARITY_OPTIONS).is_ok());
assert!(validate_options("mcp", &args(&["--connect", "127.0.0.1:9000"]), MCP_OPTIONS).is_ok());
assert!(validate_options("mcp", &args(&["--headless", "--when-closed", "launch"]), MCP_OPTIONS).is_ok());
assert!(validate_options("render", &args(&["in.docx", "out.png", "--page"]), RENDER_OPTIONS).is_ok());
assert!(
validate_options(
@@ -326,18 +326,32 @@ fn every_agent_entry_point_refuses_to_start_without_both_roots() {
}
}
/// The desktop app doesn't confine its control channel to roots yet (#3695, #5819), so the bridge
/// to it is refused, with roots or without, before anything connects.
/// `mcp`'s plan never runs anything unconfined (shared rule 18): headless needs both roots, and
/// with the suite's AI-MCP flag the live client runs without them only while the launcher's switch
/// lets agents into the window, which confines them to its agent folder.
#[test]
fn mcp_connect_is_refused_until_the_app_confines_its_control_channel() {
let dir = std::env::temp_dir().to_string_lossy().into_owned();
for line in [
args(&["mcp", "--connect", "127.0.0.1:9"]),
args(&["mcp", "--connect", "127.0.0.1:9", "--author", "Claude"]),
args(&["mcp", "--connect", "127.0.0.1:9", "--automation-read-root", &dir, "--automation-write-root", &dir]),
] {
let e = run(&line).unwrap_err().to_string();
assert!(e.contains("--connect") && e.contains("#3695") && e.contains("#5819"), "{line:?}: {e}");
fn mcp_never_plans_an_unconfined_session() {
let scratch = Scratch::new("mcp-plan");
let root = |read: bool, write: bool| {
let (r, w) = (read.then_some(scratch.0.as_path()), write.then_some(scratch.0.as_path()));
wordcraft_engine::file_access::AutomationRoots::new(r, w).unwrap()
};
let both = || root(true, true);
// --headless, or no flag: both roots or nothing.
for (headless, flag, switch) in [(true, true, true), (true, false, false), (false, false, true), (false, false, false)] {
assert!(matches!(mcp_plan(both(), headless, flag, switch), Ok(McpPlan::Headless(_))));
for partial in [None, root(true, false), root(false, true)] {
assert_eq!(mcp_plan(partial, headless, flag, switch).unwrap_err(), MCP_NEEDS_ROOTS);
}
}
// The flag and the switch: the window, with or without roots.
for roots in [None, root(true, false), both()] {
assert!(matches!(mcp_plan(roots, false, true, true), Ok(McpPlan::Live(_))));
}
// The flag without the switch: only with both roots, which confine its headless sessions.
assert!(matches!(mcp_plan(both(), false, true, false), Ok(McpPlan::Live(Some(_)))));
for partial in [None, root(true, false), root(false, true)] {
assert_eq!(mcp_plan(partial, false, true, false).unwrap_err(), MCP_NEEDS_ROOTS_OR_AGENTS);
}
}
@@ -352,19 +366,38 @@ fn mcp_headless_session_takes_the_author_flag() {
assert_eq!(unnamed.session.author, wordcraft_mcp::Headless::default().session.author, "no flag keeps the default author");
}
/// `--connect` is refused whether or not it has a value, written apart or as `--connect=…`, even with both roots valid.
/// `mcp --author` without a name is refused, also when another option follows it, instead of
/// starting with the default author or that option as the name.
#[test]
fn mcp_connect_is_refused_without_a_value_too() {
let scratch = Scratch::new("connect-bare");
let dir = scratch.0.to_string_lossy().into_owned();
let roots = ["--automation-read-root", &dir, "--automation-write-root", &dir];
for tail in [vec!["--connect"], vec!["--connect", "--author", "Claude"], vec!["--connect=127.0.0.1:9"], vec!["--connect="]] {
let line = args(&[&["mcp"][..], &roots, &tail].concat());
let e = run(&line).unwrap_err().to_string();
assert!(e.contains("--connect") && e.contains("#3695") && e.contains("#5819"), "{line:?}: {e}");
fn mcp_author_needs_a_name() {
assert_eq!(mcp_author(&args(&["--headless", "--author", "Claude"])), Ok(Some("Claude".to_string())));
assert_eq!(mcp_author(&args(&["--headless"])), Ok(None));
for given in [vec!["--author"], vec!["--author", "--headless"], vec!["--author", "A", "--author", "B"]] {
assert!(mcp_author(&args(&given)).is_err(), "{given:?}");
}
}
/// The deprecated `--connect` is taken out with its value, whether it has one, written apart or as
/// `--connect=…`, and leaves the other options as they were.
#[test]
fn mcp_connect_is_taken_out_with_its_value() {
for (given, left) in [
(vec!["--connect", "127.0.0.1:9", "--author", "Claude"], vec!["--author", "Claude"]),
(vec!["--connect"], vec![]),
(vec!["--connect", "--author", "Claude"], vec!["--author", "Claude"]),
(vec!["--headless", "--connect=127.0.0.1:9"], vec!["--headless"]),
(vec!["--connect=", "--connect", "x"], vec![]),
] {
let mut rest = args(&given);
assert!(take_connect(&mut rest), "{given:?}");
assert_eq!(rest, args(&left), "{given:?}");
assert!(validate_options("mcp", &rest, MCP_OPTIONS).is_ok());
}
let mut rest = args(&["--author", "Claude"]);
assert!(!take_connect(&mut rest));
assert_eq!(rest, args(&["--author", "Claude"]));
}
#[test]
fn render_rejects_missing_or_invalid_page_and_scale() {
// Missing operands
@@ -710,6 +743,70 @@ fn script_reads_from_a_stream_and_caps_its_size() {
assert!(script::load_from(&b"{"[..], "-", None).is_err());
}
#[test]
fn run_result_warnings_use_stderr_without_print() {
use std::process::Command;
const CHILD_ARGS: &str = "WORDCRAFT_CLI_WARNING_TEST_ARGS";
const STORE: &str = "WORDCRAFT_CLI_WARNING_TEST_STORE";
const WARNING: &str = "added for this session only: couldn't store it";
if let Ok(argv) = std::env::var(CHILD_ARGS) {
let store = PathBuf::from(std::env::var_os(STORE).unwrap());
wordcraft_fonts::FontDb::global().load_user_fonts(&store);
run(&serde_json::from_str::<Vec<String>>(&argv).unwrap()).unwrap();
// Bypass the test harness summary so the parent sees only the same header and the CLI's
// output. Each child has its own font database and never configures a real user store.
std::process::exit(0);
}
let dir = script_dir("run-warnings");
let store = dir.join("not-a-directory");
std::fs::write(&store, b"blocked font store").unwrap();
// Like the engine's font.add fixture, rename the bundled JetBrains Mono family in memory
// so it is treated as a new face. No additional font asset is used.
let mut font = include_bytes!("../../../assets/fonts/JetBrainsMono-Regular.ttf").to_vec();
let utf16 = |name: &str| name.encode_utf16().flat_map(u16::to_be_bytes).collect::<Vec<u8>>();
for (old, new) in [(b"JetBrains Mono".to_vec(), b"Cli Fixture 42".to_vec()), (utf16("JetBrains Mono"), utf16("Cli Fixture 42"))] {
let mut start = 0;
while let Some(at) = font[start..].windows(old.len()).position(|bytes| bytes == old) {
let range = start + at..start + at + old.len();
start = range.end;
font[range].copy_from_slice(&new);
}
}
let path = dir.join("fixture.ttf");
std::fs::write(&path, font).unwrap();
let params = json!({"path": path.to_string_lossy()});
let spec = format!("font.add={params}");
let script = write_script(&dir, &json!({"commands": [{"command": "font.add", "params": params}]}).to_string());
let child = |argv: &[&str]| {
let out = Command::new(std::env::current_exe().unwrap())
.args(["--exact", "tests::run_result_warnings_use_stderr_without_print", "--nocapture"])
.env(CHILD_ARGS, json!(argv).to_string())
.env(STORE, &store)
.output()
.unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
(String::from_utf8(out.stdout).unwrap(), String::from_utf8(out.stderr).unwrap())
};
let (header, quiet_stderr) = child(&["run", "--cmd", "caret.docEnd"]);
assert!(quiet_stderr.is_empty(), "{quiet_stderr}");
for argv in [["run", "--cmd", &spec], ["run", "--script", &script]] {
let (stdout, stderr) = child(&argv);
assert_eq!(stdout, header);
assert!(stderr.starts_with(&format!("wordcraft-cli: warning: {WARNING}")), "{stderr}");
assert_eq!(stderr.lines().count(), 1, "{stderr}");
let (stdout, stderr) = child(&[argv[0], argv[1], argv[2], "--print"]);
assert!(stderr.is_empty(), "{stderr}");
let result = stdout.strip_prefix(&header).unwrap().strip_prefix("font.add: ").unwrap();
let result: Value = serde_json::from_str(result).unwrap();
let warning = result["warning"].as_str().unwrap();
assert!(warning.starts_with(WARNING), "{result}");
}
}
#[test]
fn script_commands_run_before_cmd_flags() {
let dir = script_dir("order");
+24
View File
@@ -37,3 +37,27 @@ fn run_saves_the_document_opened_last() {
let stdout = String::from_utf8_lossy(&listed.stdout);
assert_eq!(stdout.matches("\"id\"").count(), 1, "{stdout}");
}
struct TempFile(std::path::PathBuf);
impl Drop for TempFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
#[test]
fn failed_run_commands_still_exit_with_an_error() {
let script = TempFile(std::env::temp_dir().join(format!("wordcraft-cli-run-error-{}.json", std::process::id())));
std::fs::write(&script.0, r#"{"commands":["no.such.command"]}"#).unwrap();
let script_path = script.0.to_string_lossy();
let cases = [(["run", "--cmd", "no.such.command"], "no.such.command:"), (["run", "--script", &script_path], "command 1 (no.such.command):")];
for (args, expected) in cases {
let out = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).args(args).output().unwrap();
assert_eq!(out.status.code(), Some(1));
assert!(out.stdout.is_empty(), "{out:?}");
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(stderr.starts_with("wordcraft-cli: ") && stderr.contains(expected), "{stderr}");
assert!(!stderr.contains("wordcraft-cli: warning:"), "{stderr}");
}
}
+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;
+60 -9
View File
@@ -1,7 +1,9 @@
//! Shared rule 18 (#7124): `wordcraft-cli mcp` refuses to start without both
//! `--automation-read-root` and `--automation-write-root`, refuses `--connect` while the desktop
//! app doesn't confine its control channel (#3695, #5819), and with both roots refuses files
//! outside them, through the real binary.
//! `--automation-read-root` and `--automation-write-root` unless the ArtCraft Launcher's switch
//! lets agents into WordCraft's window (which confines them to its agent folder), takes the
//! deprecated `--connect` with a note, and with both roots refuses files outside them, through the
//! real binary. Each run gets its own suite flags, launcher folder and settings folder, so this
//! machine's own never count.
use std::io::Write;
use std::path::{Path, PathBuf};
@@ -48,11 +50,17 @@ fn s(p: &Path) -> String {
p.to_string_lossy().into_owned()
}
/// Run `wordcraft-cli mcp <args>`, send `lines` on stdin, then hang up.
/// Run `wordcraft-cli mcp <args>` without the suite's AI-MCP flag, send `lines` on stdin, then hang up.
fn mcp(args: &[String], lines: &[Value]) -> Output {
mcp_with(args, lines, &[("CRAFT_FLAGS", "-AI-MCP".into())])
}
/// [`mcp`] with these environment variables.
fn mcp_with(args: &[String], lines: &[Value], env: &[(&str, std::ffi::OsString)]) -> Output {
let mut child = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"))
.arg("mcp")
.args(args)
.envs(env.iter().map(|(k, v)| (*k, v)))
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
@@ -99,17 +107,60 @@ fn mcp_refuses_to_start_without_both_roots() {
assert!(reply.get("error").is_none(), "{reply}");
}
/// `--connect` is kept for one release: it says it is deprecated and is otherwise ignored, so a
/// client configuration that still has it keeps working, and it opens no way around the roots.
#[test]
fn mcp_connect_is_refused_until_the_app_confines_its_control_channel() {
fn mcp_connect_is_a_deprecated_alias_of_plain_mcp() {
let folders = Folders::new("connect");
let base = folders.0.clone();
let (read, write) = (s(&base.join("in")), s(&base.join("out")));
let why = ["--connect", "#3695", "#5819"];
refused_at_start(&["--connect".into(), "127.0.0.1:9".into()], &why);
refused_at_start(
let out = mcp(
&["--connect".into(), "127.0.0.1:9".into(), "--automation-read-root".into(), read, "--automation-write-root".into(), write],
&why,
&[serde_json::from_str(PING).unwrap()],
);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(out.status.success(), "stderr: {stderr}");
assert!(stderr.contains("--connect is deprecated"), "{stderr}");
let reply: Value = serde_json::from_slice(out.stdout.split(|b| *b == b'\n').next().unwrap()).unwrap();
assert_eq!(reply["id"], 1, "{reply}");
refused_at_start(&["--connect".into(), "127.0.0.1:9".into()], &["--connect is deprecated", "--automation-read-root"]);
}
/// With the suite's AI-MCP flag: while the launcher's switch keeps agents out, `mcp` still needs
/// both roots and says how to let agents in; once the launcher's list names WordCraft, plain `mcp`
/// starts without roots and follows the closed-app choice (here: ask to open WordCraft).
#[test]
fn with_the_flag_the_launcher_switch_lets_plain_mcp_start() {
let folders = Folders::new("switch");
let base = folders.0.clone();
let launcher = base.join("launcher");
let settings = base.join("settings");
std::fs::create_dir_all(&launcher).unwrap();
std::fs::create_dir_all(&settings).unwrap();
std::fs::write(settings.join("config.toml"), "schema_version = 1\n[integrations]\nwhenAppClosed = \"error\"\n").unwrap();
let env = [
("CRAFT_FLAGS", std::ffi::OsString::from("AI-MCP")),
("CRAFT_MCP_DIR", launcher.clone().into_os_string()),
("WORDCRAFT_PROFILE_DIR", settings.into_os_string()),
];
let ping: Value = serde_json::from_str(PING).unwrap();
let off = mcp_with(&[], std::slice::from_ref(&ping), &env);
let stderr = String::from_utf8_lossy(&off.stderr);
assert!(!off.status.success() && off.stdout.is_empty(), "started with the switch off: {stderr}");
assert!(stderr.contains("ArtCraft Launcher") && stderr.contains("--automation-read-root"), "{stderr}");
let cli = s(Path::new(env!("CARGO_BIN_EXE_wordcraft-cli")));
let list = json!({"version": 1, "apps": [{"id": "wordcraft", "name": "WordCraft", "command": cli, "args": ["mcp"]}]});
std::fs::write(launcher.join("apps.json"), list.to_string()).unwrap();
let on = mcp_with(&[], &[ping, tool(2, "list_documents", json!({}))], &env);
let stderr = String::from_utf8_lossy(&on.stderr);
assert!(on.status.success(), "stderr: {stderr}");
let replies: Vec<Value> =
String::from_utf8_lossy(&on.stdout).lines().filter(|l| !l.trim().is_empty()).map(|l| serde_json::from_str(l).unwrap()).collect();
assert!(replies.iter().any(|r| r["id"] == 1 && r.get("error").is_none()), "{replies:?}");
let call = replies.iter().find(|r| r["id"] == 2).expect("the tool call is answered");
assert_eq!(call["result"]["isError"], true, "{call}");
assert!(call.to_string().contains("isn't running"), "the closed-app choice answers: {call}");
}
/// `tools/call` request `id` for `name` with `arguments`.
@@ -0,0 +1,127 @@
//! Direct PDF exports use the saved timestamp without changing the source document.
use std::process::Command;
#[test]
fn direct_pdf_exports_use_the_pinned_epoch() {
check_creation_date("", "20261005140300");
}
#[test]
fn direct_pdf_exports_preserve_an_existing_creation_date() {
check_creation_date("2000-01-01T00:00:00Z", "20000101000000");
}
/// A .docx records `dcterms:created` as text and the reader takes it as it finds it, so a
/// document can arrive holding something that is not a date at all. The PDF writer cannot put
/// that in a document and fell back to the clock, so two exports of the same file differed even
/// with `SOURCE_DATE_EPOCH` set -- the one thing it is there to stop (noted in review).
#[test]
fn direct_pdf_exports_use_the_pinned_epoch_when_the_existing_date_is_unreadable() {
for created in ["not-a-date", "", " ", "2000-13-01T00:00:00Z", "2000-01-32T00:00:00Z", "99-01-01", "today"] {
check_creation_date(created, "20261005140300");
}
}
fn check_creation_date(created: &str, expected: &str) {
// A sequence number, not the clock alone: `as_nanos` carries microsecond granularity on
// macOS, so two of these tests starting in the same microsecond took the same directory,
// wrote each other's `input.json` and failed the preservation assertion below -- a flake in
// this harness, not in the export. `create_dir` rather than `create_dir_all` so that if a
// name ever does repeat it fails here instead of quietly sharing a directory again.
static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let seq = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let dir = std::env::temp_dir().join(format!("wordcraft-pdf-date-{}-{unique}-{seq}", std::process::id()));
std::fs::create_dir(&dir).unwrap_or_else(|e| panic!("{}: {e}", dir.display()));
let mut doc = wordcraft_doc::Document::from_text("Original reproducible PDF check.");
doc.core.created = created.into();
let input = dir.join("input.json");
let source = serde_json::to_vec(&doc).unwrap();
std::fs::write(&input, &source).unwrap();
for command in ["file.exportPdf", "file.printPdf"] {
let output = dir.join(format!("{command}.pdf"));
let params = serde_json::json!({"path": output});
let run = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"))
.arg("run")
.arg("--file")
.arg(&input)
.arg("--cmd")
.arg(format!("{command}={params}"))
.env("SOURCE_DATE_EPOCH", "1791208980")
.output()
.unwrap();
assert!(run.status.success(), "{command}: {}", String::from_utf8_lossy(&run.stderr));
let bytes = std::fs::read(output).unwrap();
let date = format!("/CreationDate(D:{expected}");
assert!(bytes.windows(date.len()).any(|part| part == date.as_bytes()), "{command} must use {expected}");
assert_eq!(std::fs::read(&input).unwrap(), source, "export must preserve its source file");
}
}
/// A fresh directory for one test's files.
fn scratch(name: &str) -> std::path::PathBuf {
let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let dir = std::env::temp_dir().join(format!("wordcraft-{name}-{}-{unique}", std::process::id()));
std::fs::create_dir(&dir).unwrap_or_else(|e| panic!("{}: {e}", dir.display()));
dir
}
fn cli(env: &str, cmds: &[String]) -> std::process::Output {
let mut run = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"));
run.arg("run").env("SOURCE_DATE_EPOCH", env);
for c in cmds {
run.arg("--cmd").arg(c);
}
run.output().unwrap()
}
/// The pinned date is the file's, not the edits': a comment and a tracked change made in the
/// same run keep the time they were made, so a pinned epoch cannot back-date them (noted in
/// review). Saved as flat XML, which holds both in plain text.
#[test]
fn a_pinned_epoch_dates_the_file_and_not_the_edits_in_it() {
let out = scratch("pinned-edits").join("edits.xml");
let before = wordcraft_engine::cmd::now_iso();
let run = cli(
"1791208980",
&[
r#"review.trackChanges={"value": true}"#.to_string(),
r#"text.insert={"text": "tracked"}"#.to_string(),
r#"review.newComment={"text": "note"}"#.to_string(),
format!("file.saveAs={}", serde_json::json!({"path": out})),
],
);
let after = wordcraft_engine::cmd::now_iso();
assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr));
let xml = std::fs::read_to_string(&out).unwrap();
assert!(xml.contains(r#"<dcterms:modified xsi:type="dcterms:W3CDTF">2026-10-05T14:03:00Z</dcterms:modified>"#), "the file's date is pinned");
let dates: Vec<&str> = xml.split(r#"w:date=""#).skip(1).filter_map(|rest| rest.split('"').next()).collect();
assert!(xml.contains("<w:ins ") && xml.contains("<w:comment "), "a tracked insertion and a comment were saved");
assert!(dates.len() >= 2, "both carry a date: {dates:?}");
for date in dates {
assert!((before.as_str()..=after.as_str()).contains(&date), "{date} is the clock's, between {before} and {after}");
}
}
/// A value that is set and cannot be used is said out loud, and the run still succeeds: the
/// files take the clock's date, as they would with the variable unset (noted in review).
#[test]
fn an_unusable_epoch_is_reported_on_stderr() {
let dir = scratch("epoch-warning");
let save = |name: &str| format!("file.exportPdf={}", serde_json::json!({"path": dir.join(name)}));
let run = cli("later", &[save("later.pdf")]);
assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr));
let stderr = String::from_utf8_lossy(&run.stderr);
assert!(stderr.contains(r#"warning: SOURCE_DATE_EPOCH="later" is not a whole number of seconds"#), "{stderr}");
let pdf = std::fs::read(dir.join("later.pdf")).unwrap();
let pinned = b"/CreationDate(D:20261005140300";
assert!(pdf.windows(b"/CreationDate(D:".len()).any(|w| w == b"/CreationDate(D:"), "the export has a creation date");
assert!(!pdf.windows(pinned.len()).any(|w| w == pinned), "and it is the clock's, not a pinned one");
for quiet in ["1791208980", ""] {
let run = cli(quiet, &[save("quiet.pdf")]);
assert!(run.status.success());
assert!(!String::from_utf8_lossy(&run.stderr).contains("SOURCE_DATE_EPOCH"), "{quiet:?} says nothing");
}
}
+1
View File
@@ -27,6 +27,7 @@ const POLL_MS: i32 = 16;
pub fn install(ctx: egui::Context) -> Receiver<ControlRequest> {
let (queue, requests) = channel::<ControlRequest>();
let request: Request = Rc::new(move |method, params| {
let params = super::page_params::control_params(&method, params);
let (control, reply) = ControlRequest::new(method, params);
if queue.send(control).is_err() {
return Box::pin(async { json!({"ok": false, "error": "the app is not running"}) });
+2
View File
@@ -23,6 +23,8 @@ mod prefs;
mod api;
#[cfg(target_arch = "wasm32")]
mod host;
#[cfg(any(target_arch = "wasm32", test))]
mod page_params;
#[cfg(target_arch = "wasm32")]
mod web;
+55
View File
@@ -0,0 +1,55 @@
use serde_json::Value;
pub(super) fn control_params(method: &str, mut params: Value) -> Value {
// The page helper asks for inline data. A screenshot without a path already returns it.
if method == "ui.screenshot"
&& let Some(fields) = params.as_object_mut()
&& !fields.contains_key("path")
&& fields.get("data") == Some(&Value::Bool(true))
{
fields.remove("data");
}
params
}
#[cfg(test)]
mod tests {
use craft::automation::screenshot::ScreenshotParams;
use serde_json::json;
use super::control_params;
#[test]
fn page_helper_requests_the_same_capture_as_a_direct_request() {
for (helper, direct) in
[(json!({"data": true}), json!({})), (json!({"data": true, "region": [10, 20, 100, 200]}), json!({"region": [10, 20, 100, 200]}))]
{
let params = control_params("ui.screenshot", helper);
assert_eq!(params, direct);
assert!(ScreenshotParams::from_params(&params).is_ok());
}
}
#[test]
fn page_helper_keeps_screenshot_validation() {
for (input, expected) in [
(json!({"data": true, "region": [100, 200, 10, 20]}), json!({"region": [100, 200, 10, 20]})),
(json!({"data": true, "viewport": "other"}), json!({"viewport": "other"})),
(json!({"data": true, "path": "capture.png"}), json!({"data": true, "path": "capture.png"})),
(json!({"data": true, "path": null}), json!({"data": true, "path": null})),
(json!({"data": false}), json!({"data": false})),
(json!({"data": "true"}), json!({"data": "true"})),
] {
let params = control_params("ui.screenshot", input);
assert_eq!(params, expected);
assert!(ScreenshotParams::from_params(&params).is_err());
}
}
#[test]
fn direct_requests_keep_their_parameters() {
for (method, params) in [("ui.screenshot", json!({"path": "capture.png"})), ("file.new", json!({"data": true}))] {
assert_eq!(control_params(method, params.clone()), params);
}
}
}
+1 -4
View File
@@ -36,6 +36,7 @@ craft = { workspace = true, features = [
"ui-app",
"dialogs",
"automation",
"automation-agents",
"gpu-startup",
"print",
"settings",
@@ -74,10 +75,6 @@ winit = { version = "0.30", default-features = false, features = ["x11", "waylan
x11-dl = "2.21"
xkbcommon-dl = { version = "0.4.2", features = ["x11"] }
# Name the window supplied by eframe's attachment hook on targets that otherwise use winit indirectly.
[target.'cfg(any(target_os = "macos", windows))'.dependencies]
winit = { version = "0.30", default-features = false }
[target.'cfg(windows)'.dependencies]
# The update helper: a copy of this program started with `--finish-update`
# (`craft::update::self_update::finish`).
+149 -17
View File
@@ -4,12 +4,14 @@
//! A connection authenticates once with the token (`docs/control-protocol.md`, Token). When no
//! token or token file is supplied, the app generates a token and writes it to
//! `<settings>/control-key.<instance>` (mode 0600) after the port is bound, and removes the file
//! when the window closes.
//! when the window closes. The server itself goes to the agent link for the run
//! (`AgentLink::from_launch`), so File › Options › Agents says the launch options manage it.
use std::net::TcpListener;
use std::path::{Path, PathBuf};
use std::sync::mpsc::Receiver;
use craft::automation::AutomationError;
use craft::automation::args::ControlOptions;
use craft::automation::control::ControlRequest;
use craft::automation::server::{Listening, serve};
@@ -24,11 +26,28 @@ pub struct Control {
}
impl Control {
/// The server, for the agent link to keep for the whole run (`AgentLink::from_launch`), and the
/// token file this run wrote, which the app removes when the window closes.
pub fn split(self) -> (Listening, TokenFile) {
(self.listening, TokenFile(self.created))
}
/// Stop accepting connections and remove the token file this run wrote, if any.
#[cfg(test)]
pub fn shut_down(self) {
let Self { listening, created } = self;
let (listening, file) = self.split();
drop(listening);
remove(created.as_deref());
file.remove();
}
}
/// The default token file a run wrote, if any; a token file the user supplied is never removed.
pub struct TokenFile(Option<PathBuf>);
impl TokenFile {
/// Removes the file this run wrote.
pub fn remove(self) {
remove(self.0.as_deref());
}
}
@@ -38,6 +57,22 @@ fn remove(path: Option<&Path>) {
}
}
/// Why starting the control server did not succeed.
enum StartError {
/// Windows external-tool timeout while creating or checking the owner-only token file.
TokenTimeout(String),
/// Any other bind, token, or accept-thread error.
Other(String),
}
impl StartError {
fn message(&self) -> &str {
match self {
Self::TokenTimeout(msg) | Self::Other(msg) => msg,
}
}
}
/// Bind `127.0.0.1:port`, settle the token and serve. `None` when the port cannot be bound or
/// the token cannot be set up (the control channel is off); a taken port leaves no token file.
///
@@ -45,35 +80,49 @@ fn remove(path: Option<&Path>) {
/// `port` in `settings`; a file left by a run that did not exit cleanly is replaced. Without a
/// settings folder a fresh token is generated and reported by the log.
pub fn start(options: &ControlOptions, port: u16, host: WindowHost, settings: Option<&Path>) -> Option<(Receiver<ControlRequest>, Control)> {
let listener = match TcpListener::bind(("127.0.0.1", port)) {
Ok(l) => l,
Err(e) => {
log::error!("control server failed to bind 127.0.0.1:{port}: {e}");
return None;
match start_with(options, port, host, settings, ControlOptions::server_token) {
Ok(started) => Some(started),
Err(err) => {
log::error!("{}", err.message());
None
}
};
}
}
fn start_with(
options: &ControlOptions,
port: u16,
host: WindowHost,
settings: Option<&Path>,
token_for: impl FnOnce(&ControlOptions) -> Result<String, AutomationError>,
) -> Result<(Receiver<ControlRequest>, Control), StartError> {
let listener =
TcpListener::bind(("127.0.0.1", port)).map_err(|e| StartError::Other(format!("control server failed to bind 127.0.0.1:{port}: {e}")))?;
let created = settings.filter(|_| options.token.is_none() && options.token_file.is_none()).map(|dir| wordcraft_control_key::key_path(dir, port));
// The port was free, so no other run owns a file left here.
remove(created.as_deref());
let effective = ControlOptions { token_file: created.clone().or_else(|| options.token_file.clone()), ..options.clone() };
let token = match effective.server_token() {
let token = match token_for(&effective) {
Ok(t) => t,
Err(e) => {
remove(created.as_deref());
log::error!("control server off: {e}");
return None;
let msg = format!("control server off: {e}");
return Err(if matches!(&e, AutomationError::Io(text) if text.contains("did not finish within ")) {
StartError::TokenTimeout(msg)
} else {
StartError::Other(msg)
});
}
};
let notice = effective.token_notice(&token);
match serve(listener, token, host) {
Ok((rx, listening)) => {
log::info!("control server listening on {}, {notice}", listening.addr);
Some((rx, Control { listening, created }))
Ok((rx, Control { listening, created }))
}
Err(e) => {
remove(created.as_deref());
log::error!("control server off: cannot start the accept thread ({e})");
None
Err(StartError::Other(format!("control server off: cannot start the accept thread ({e})")))
}
}
}
@@ -87,6 +136,41 @@ mod tests {
WindowHost::of(&egui::Context::default())
}
/// Attempts for `start_with` when Windows `owner_only` hits its 10 s external-tool limit on
/// a busy CI runner (#8556). Non-timeout failures stop on the first attempt.
const TOKEN_TIMEOUT_ATTEMPTS: usize = 3;
fn try_start_retrying_token_timeout(
options: &ControlOptions,
port: u16,
host: WindowHost,
settings: Option<&Path>,
mut token_for: impl FnMut(&ControlOptions) -> Result<String, AutomationError>,
) -> Result<(Receiver<ControlRequest>, Control), (usize, StartError)> {
let mut attempt = 1;
loop {
match start_with(options, port, host.clone(), settings, &mut token_for) {
Ok(started) => return Ok(started),
Err(StartError::TokenTimeout(msg)) if attempt < TOKEN_TIMEOUT_ATTEMPTS => {
log::warn!("retrying control server start after Windows token-file timeout ({attempt}/{TOKEN_TIMEOUT_ATTEMPTS}): {msg}");
attempt += 1;
}
Err(err) => return Err((attempt, err)),
}
}
}
fn start_retrying_token_timeout(
options: &ControlOptions,
port: u16,
host: WindowHost,
settings: Option<&Path>,
token_for: impl FnMut(&ControlOptions) -> Result<String, AutomationError>,
) -> (Receiver<ControlRequest>, Control) {
try_start_retrying_token_timeout(options, port, host, settings, token_for)
.unwrap_or_else(|(attempt, err)| panic!("control server start failed on attempt {attempt}: {}", err.message()))
}
#[test]
fn the_token_file_is_written_after_the_bind_and_removed_on_exit() {
let dir = std::env::temp_dir().join(format!("wordcraft-control-life-{}", std::process::id()));
@@ -101,7 +185,7 @@ mod tests {
drop(taken);
// Bound: the default file holds the token that opens the port.
let (_rx, control) = start(&options, 0, host(), Some(&dir)).unwrap();
let (_rx, control) = start_retrying_token_timeout(&options, 0, host(), Some(&dir), ControlOptions::server_token);
let path = control.created.clone().unwrap();
assert_eq!(path, wordcraft_control_key::key_path(&dir, 0));
let token = std::fs::read_to_string(&path).unwrap();
@@ -117,13 +201,61 @@ mod tests {
// A token file the user supplied stays.
let supplied = dir.join("supplied-token");
let options = ControlOptions { token_file: Some(supplied.clone()), ..ControlOptions::default() };
let (_rx, control) = start(&options, 0, host(), Some(&dir)).unwrap();
let (_rx, control) = start_retrying_token_timeout(&options, 0, host(), Some(&dir), ControlOptions::server_token);
assert!(control.created.is_none());
control.shut_down();
assert!(supplied.exists());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_transient_token_file_timeout_retries_while_other_errors_stop() {
let dir = std::env::temp_dir().join(format!("wordcraft-control-retry-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let options = ControlOptions::default();
// A Windows `owner_only` external-tool timeout retries and recovers on a later attempt.
let mut timeout_then_ok = 0usize;
let (_rx, control) = start_retrying_token_timeout(&options, 0, host(), Some(&dir), |effective| {
timeout_then_ok += 1;
if timeout_then_ok == 1 {
let path = effective.token_file.as_ref().unwrap();
Err(AutomationError::Io(format!(
"{}: cannot create the control token file for its owner only: powershell.exe did not finish within 10 s and was ended",
path.display()
)))
} else {
Ok(TOKEN.to_string())
}
});
assert_eq!(timeout_then_ok, 2);
control.shut_down();
// Repeated timeouts stop after `TOKEN_TIMEOUT_ATTEMPTS` instead of looping forever.
let mut exhausted = 0usize;
let Err((attempt, err)) = try_start_retrying_token_timeout(&options, 0, host(), Some(&dir), |_| {
exhausted += 1;
Err(AutomationError::Io("powershell.exe did not finish within 10 s and was ended".into()))
}) else {
panic!("exhausted timeouts must fail");
};
assert_eq!((attempt, exhausted), (TOKEN_TIMEOUT_ATTEMPTS, TOKEN_TIMEOUT_ATTEMPTS));
assert!(matches!(err, StartError::TokenTimeout(_)));
// Non-timeout failures stop on the first attempt.
let mut other = 0usize;
let Err((attempt, err)) = try_start_retrying_token_timeout(&options, 0, host(), Some(&dir), |_| {
other += 1;
Err(AutomationError::Io("permission denied".into()))
}) else {
panic!("non-timeout error must fail");
};
assert_eq!((attempt, other), (1, 1));
assert!(matches!(err, StartError::Other(msg) if msg.contains("permission denied")));
let _ = std::fs::remove_dir_all(&dir);
}
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
fn boot() -> (u16, Receiver<ControlRequest>, Control) {
-87
View File
@@ -1,87 +0,0 @@
//! Native parent windows for document-owned file pickers in windowless mode.
use std::collections::HashMap;
use std::num::NonZeroU64;
use std::sync::{Arc, Mutex, Weak};
use craft::dialogs::service::FilePanels;
use craft::platform::open::IntakeSender;
use craft::ui::dialog::DialogHost;
use eframe::{ViewportHooks, ViewportWindowKey};
use egui::{Context, RawInput, ViewportId};
use winit::window::Window;
use wordcraft_ui_egui::file_dialogs::{NativeWindowLookup, OwnerPanels, ParentLease};
use crate::drop_intake::ChildDrops;
/// The latest successful attachment for each viewport. The registry does not keep windows alive.
#[derive(Clone, Default)]
pub(crate) struct DocumentWindows(Arc<Mutex<HashMap<ViewportId, (ViewportWindowKey, Weak<Window>)>>>);
impl DocumentWindows {
pub(crate) fn hooks(&self, drops: IntakeSender) -> Arc<dyn ViewportHooks> {
Arc::new(DocumentHooks { windows: self.clone(), drops: ChildDrops(drops) })
}
}
struct DocumentHooks {
windows: DocumentWindows,
drops: ChildDrops,
}
impl ViewportHooks for DocumentHooks {
fn window_attached(&self, key: ViewportWindowKey, window: Weak<Window>) {
let mut attached = self.windows.0.lock().unwrap_or_else(|e| e.into_inner());
attached.insert(key.viewport_id(), (key, window));
}
fn window_detached(&self, key: ViewportWindowKey) {
let mut attached = self.windows.0.lock().unwrap_or_else(|e| e.into_inner());
if attached.get(&key.viewport_id()).is_some_and(|(current, _)| *current == key) {
attached.remove(&key.viewport_id());
}
}
fn raw_input(&self, ctx: &Context, raw: &mut RawInput) {
self.drops.raw_input(ctx, raw);
}
}
impl NativeWindowLookup for DocumentWindows {
fn incarnation(&self, viewport: ViewportId) -> Option<NonZeroU64> {
let attached = self.0.lock().unwrap_or_else(|e| e.into_inner());
let (key, weak) = attached.get(&viewport)?;
(weak.strong_count() > 0).then(|| key.incarnation())
}
}
impl OwnerPanels for DocumentWindows {
fn pump_parented(
&mut self,
viewport: ViewportId,
incarnation: NonZeroU64,
panels: &mut FilePanels,
host: &mut DialogHost,
) -> Option<ParentLease> {
// Upgrade only the exact live incarnation, on the event-loop thread. Never hold the
// registry lock across the pump (macOS can enter native dialog code here).
let parent = {
let attached = self.0.lock().unwrap_or_else(|e| e.into_inner());
let (key, weak) = attached.get(&viewport)?;
if key.incarnation() != incarnation {
return None;
}
weak.upgrade()?
};
panels.pump_with(host, Some(parent.as_ref()));
// rfd can use the copied handles on a later worker callback. The router retains this
// lease through backend completion even if the initiating document detached meanwhile.
Some(ParentLease::new(parent))
}
fn pump_unparented(&mut self, panels: &mut FilePanels, host: &mut DialogHost) {
// The router allows this only for an explicitly in-app request or an already launched
// operation with an empty native queue. It cannot open an unowned system dialog here.
panels.pump_with::<eframe::Frame>(host, None);
}
}
-111
View File
@@ -1,111 +0,0 @@
//! Route desktop drop events to WordCraft's existing file intake.
use std::path::Path;
use std::sync::Arc;
use craft::platform::open::{DroppedFile, IntakeSender};
use eframe::ViewportHooks;
use egui::{Context, RawInput, ViewportId};
/// The ordinary app input hook leaves files in `raw` for the runtime's own reading.
pub(crate) fn forward_app_input(sender: &IntakeSender, raw: &RawInput) {
sender.dropped(
raw.dropped_files
.iter()
.map(|file| {
dropped_path(file.path()).unwrap_or_else(|| DroppedFile { path: None, name: String::new(), bytes: file.bytes().ok().map(Arc::from) })
})
.collect(),
);
}
fn dropped_path(path: &Path) -> Option<DroppedFile> {
if path.as_os_str().is_empty() {
return None;
}
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
Some(DroppedFile { path: Some(path.to_path_buf()), name, bytes: None })
}
/// Immediate child input in the windowless trial.
pub(crate) struct ChildDrops(pub(crate) IntakeSender);
impl ViewportHooks for ChildDrops {
fn raw_input(&self, _ctx: &Context, raw: &mut RawInput) {
// Immediate viewports skip App::raw_input_hook. The regular ROOT input still goes there.
// Consume this child batch so no later hook or pass feeds it again. Native OS drops carry
// paths: pass those through without reading the files on the event loop.
if raw.viewport_id != ViewportId::ROOT && !raw.dropped_files.is_empty() {
self.0.dropped(raw.dropped_files.drain(..).filter_map(|file| dropped_path(file.path())).collect());
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
use craft::host::Wake;
use craft::platform::open::{FileIntake, Intake};
#[derive(Debug)]
struct NativeDrop(PathBuf);
impl egui::DroppedFile for NativeDrop {
fn path(&self) -> &Path {
&self.0
}
fn bytes(&self) -> Result<Vec<u8>, String> {
panic!("the raw-input hook must not read native dropped files");
}
}
fn raw_drops(viewport_id: ViewportId, paths: &[PathBuf]) -> RawInput {
RawInput {
viewport_id,
dropped_files: paths.iter().map(|path| Arc::new(NativeDrop(path.clone())) as egui::DroppedFileHandle).collect(),
..Default::default()
}
}
#[test]
fn child_drop_enters_intake_once_in_drop_order() {
let (intake, sender) = FileIntake::new(Wake::none());
let hooks = ChildDrops(sender.clone());
let ctx = Context::default();
let child = ViewportId::from_hash_of("document");
let paths = [std::env::temp_dir().join("second.docx"), std::env::temp_dir().join("first.docx")];
let mut raw = raw_drops(child, &paths);
// The immediate child goes through the viewport hook, not the App hook.
hooks.raw_input(&ctx, &mut raw);
let batches = intake.take();
let [Intake::Dropped { files }] = batches.as_slice() else { panic!("expected one child drop batch, got {batches:?}") };
assert!(files.iter().map(|file| file.path.as_ref()).eq(paths.iter().map(Some)));
// A replay of this input, or another input path seeing it, cannot send it again.
hooks.raw_input(&ctx, &mut raw);
forward_app_input(&sender, &raw);
assert!(intake.take().is_empty());
}
#[test]
fn root_drop_still_reaches_intake_only_from_app_input() {
let (intake, sender) = FileIntake::new(Wake::none());
let hooks = ChildDrops(sender.clone());
let ctx = Context::default();
let path = std::env::temp_dir().join("document.docx");
let mut raw = raw_drops(ViewportId::ROOT, std::slice::from_ref(&path));
// Pinned eframe calls both hooks on ROOT, in this order.
hooks.raw_input(&ctx, &mut raw);
assert!(intake.take().is_empty());
forward_app_input(&sender, &raw);
let batches = intake.take();
let [Intake::Dropped { files }] = batches.as_slice() else { panic!("expected one root drop batch, got {batches:?}") };
assert!(matches!(files.as_slice(), [file] if file.path.as_ref() == Some(&path)));
assert!(matches!(raw.dropped_files.as_slice(), [file] if file.path() == path.as_path()));
}
}
+207 -117
View File
@@ -19,8 +19,6 @@ mod build_channel;
mod build_flavor;
mod control_server;
mod default_apps;
mod document_panels;
mod drop_intake;
mod launch_profile;
#[cfg(target_os = "macos")]
mod native_menu;
@@ -29,7 +27,6 @@ mod prefs;
mod process_identity;
mod profile_root;
mod region;
mod startup_mode;
use std::path::PathBuf;
use std::sync::{Arc, Mutex, OnceLock};
@@ -43,12 +40,12 @@ use craft::platform::appearance::SystemReader;
use craft::platform::clipboard::{Clipboard, ClipboardImage, SystemClipboard};
use craft::platform::default_app::{DefaultApp, DefaultAppError};
use craft::platform::logs::{self, LogNames, crash};
use craft::platform::open::{FileIntake, IntakeSender};
use craft::platform::open::{DroppedFile, FileIntake, IntakeSender};
use craft::print::spool::Spool;
use craft::settings::SharedSettings;
use craft::ui::InstallSpec;
use craft::ui::runtime::windows::{WindowAction, WindowHost};
use craft::ui::shell::embed::{self, CloseDecision};
use craft::ui::shell::embed;
use craft::window::restore::{self, Store};
use craft::window::system::SystemWindows;
use wordcraft_engine::Session;
@@ -63,8 +60,6 @@ struct App {
native_menu: Option<craft::menu::NativeMenu>,
/// The native panels behind the file service the app reaches through `Host::files`.
panels: FilePanels,
/// Native parent windows for the owned picker route, populated only in windowless mode.
document_windows: document_panels::DocumentWindows,
/// Feeds the files dropped on the window into the app's intake (`Services::intake`), the one
/// queue the OS's requests are read from.
drops: IntakeSender,
@@ -72,8 +67,8 @@ struct App {
settings: SharedSettings<Prefs>,
/// The print spool, a handle on the one in the app's services: jobs being sent finish first.
spool: Spool,
/// The control server, when `--control` started one; it removes the token file it made.
control: Option<control_server::Control>,
/// The token file `--control` wrote, removed at exit; its server runs in the agent link.
control: Option<control_server::TokenFile>,
/// The app binary's last step as the app leaves, run once at the end of `finish` (a Nightly
/// quit ends the process inside AppKit's terminate, after eframe's `on_exit`).
exit: Option<Box<dyn FnOnce()>>,
@@ -91,35 +86,19 @@ impl App {
/// One frame's logic: what the OS asked, the app, its file dialogs, then the root window's close
/// path. Without `frame` (a test over no window) the dialogs have no parent window.
fn logic_pass(&mut self, ctx: &egui::Context, frame: Option<&eframe::Frame>) {
// Validate native incarnations before WordApp logic can settle an available answer.
// A final Quit from a previous pass takes priority over launching any new pick.
if self.app.quit_requested {
self.app.quiesce_native_file_panels();
}
self.app.pump_owned_picks(ctx, &mut self.document_windows);
self.app.logic(ctx);
#[cfg(target_os = "macos")]
if let Some(menu) = &mut self.native_menu {
native_menu::update(menu, &mut self.app, ctx);
}
// Once the document guards have settled Quit, not even this pass's last pump can open
// another picker. Keep the event loop and display alive for handles already in use.
if self.app.quit_requested {
self.app.quiesce_native_file_panels();
}
self.pump_file_panels(ctx, frame);
if self.app.quit_requested && !self.app.printing.busy() && !self.app.native_file_panels_open() {
self.panels.pump_with(self.app.dialog_host_mut(), frame);
// A quit that waits for nothing (the documents are answered for) closes the root window.
if self.app.quit_requested && !self.app.printing.busy() {
WindowHost::of(ctx).act(egui::ViewportId::ROOT, WindowAction::Close);
}
// A platform close can be accepted without setting quit_requested (e.g. no unsaved work).
// Shut off new launches only when that final close is accepted, not before a Save prompt.
embed::logic(ctx, || {
let decision = self.app.close_decision();
if matches!(decision, CloseDecision::Close) {
self.app.quiesce_native_file_panels();
}
decision
});
// The decision holds the close while a Save Changes prompt is open; a closure over
// `close_requested` would ask again on every frame of the prompt.
embed::logic(ctx, || self.app.close_decision());
}
/// One pass of the root window's UI.
@@ -128,12 +107,7 @@ impl App {
embed::before_ui(ui.ctx(), frame);
}
self.app.ui(ui);
self.pump_file_panels(ui.ctx(), frame);
}
fn pump_file_panels(&mut self, ctx: &egui::Context, frame: Option<&eframe::Frame>) {
self.panels.pump_with(self.app.dialog_host_mut(), frame);
self.app.pump_owned_picks(ctx, &mut self.document_windows);
}
/// Everything that must happen before the process ends, whichever way the window closes.
@@ -144,8 +118,8 @@ impl App {
if let Err(e) = self.settings.lock().flush() {
log::warn!("preferences: {e}");
}
if let Some(control) = self.control.take() {
control.shut_down();
if let Some(file) = self.control.take() {
file.remove();
}
if !launch_profile::current().is_nightly() {
self.app.start_pending_update();
@@ -160,7 +134,11 @@ impl eframe::App for App {
/// Hands the app what the runtime gathered since the last frame (fired commands) and the
/// runtime the input the app gives back, before any pass of the frame runs.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
drop_intake::forward_app_input(&self.drops, raw);
// Once per frame, before any pass; the files stay in `raw` for the runtime's own reading.
let files = dropped_files(raw);
if !files.is_empty() {
self.drops.dropped(files);
}
self.before_input(ctx);
}
fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
@@ -174,6 +152,36 @@ impl eframe::App for App {
}
}
/// Files dropped on a document window. eframe hands `raw_input_hook` only the root's and deferred
/// viewports' input, and document windows are immediate viewports (every one under the windowless
/// root), so their drops come through this hook. It runs first and takes the batch, so nothing reads
/// it twice.
struct ChildDrops(IntakeSender);
impl eframe::ViewportHooks for ChildDrops {
fn raw_input(&self, _ctx: &egui::Context, raw: &mut egui::RawInput) {
if raw.viewport_id != egui::ViewportId::ROOT && !raw.dropped_files.is_empty() {
self.0.dropped(dropped_files(raw));
raw.dropped_files.clear();
}
}
}
/// The files dropped in this frame's input, as the intake carries them: a file with a path by its
/// path, a file without one by its bytes.
fn dropped_files(raw: &egui::RawInput) -> Vec<DroppedFile> {
raw.dropped_files
.iter()
.map(|file| {
let path = Some(file.path().to_path_buf()).filter(|p| !p.as_os_str().is_empty());
let name = path.as_ref().and_then(|p| p.file_name()).map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
// A file without a path (the web) carries its bytes; one that cannot be read is dropped as empty.
let bytes = if path.is_none() { file.bytes().ok().map(std::sync::Arc::from) } else { None };
DroppedFile { path, name, bytes }
})
.collect()
}
/// Whether the window runs through XWayland (X11) rather than native Wayland, and the log line
/// saying why. `WORDCRAFT_WAYLAND` wins (`0`, `false`, `no` or `off` asks for X11, any other value
/// for Wayland), then File › Options › Advanced › Linux display server (#2184). Automatic is X11
@@ -470,6 +478,46 @@ fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
Some(launch_profile::passthrough_args(early.passthrough_args, had_separator))
}
/// Runs the app with the windowless root when `windowless` is set, and with the visible root when it is not. eframe
/// refuses a windowless root on a session that cannot run it before it calls the creator, which then stays in its
/// cell for a retry with the visible root: the app always starts.
fn run_with_visible_root_fallback(
creator: eframe::AppCreator<'static>,
windowless: Arc<std::sync::atomic::AtomicBool>,
mut options: eframe::NativeOptions,
) -> eframe::Result {
use std::sync::atomic::Ordering::Relaxed;
let creator = std::rc::Rc::new(std::cell::RefCell::new(Some(creator)));
let name = wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity());
let run = |options: eframe::NativeOptions| {
let creator = creator.clone();
eframe::run_native(
name,
options,
Box::new(move |cc| match creator.borrow_mut().take() {
Some(create) => create(cc),
None => Err("the app was already created".into()),
}),
)
};
let on = windowless.load(Relaxed);
// The clone keeps no event-loop hook, which only the X11 start sets and that start is windowed.
let mut visible_root = on.then(|| options.clone());
if on {
options.root_viewport_mode = eframe::RootViewportMode::Windowless;
}
let result = run(options);
if let Err(eframe::Error::UnsupportedConfiguration(reason)) = &result
&& let Some(options) = visible_root.take()
&& creator.borrow().is_some()
{
log::warn!("windowless root unavailable ({reason}); starting with a visible root window");
windowless.store(false, Relaxed);
return run(options);
}
result
}
/// Parses the command line, installs logging and the panic hook, restores preferences and window
/// geometry, opens requested documents or the Start screen, starts the control server when
/// asked, and runs the eframe event loop.
@@ -623,17 +671,25 @@ fn main() -> eframe::Result {
Some(_) => wordcraft_ui_egui::os_window::app_id().to_string(),
None => std::env::var("FLATPAK_ID").ok().filter(|id| !id.is_empty()).unwrap_or_else(|| wordcraft_ui_egui::os_window::APP_ID.to_string()),
};
let mut viewport = egui::ViewportBuilder::default()
.with_title(wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity()))
.with_app_id(app_id)
.with_inner_size([1440.0, 920.0])
.with_min_inner_size(wordcraft_ui_egui::window_geometry::MIN_SIZE)
.with_drag_and_drop(true)
.with_fullsize_content_view(true)
.with_titlebar_shown(false)
.with_title_shown(false);
let mut options = eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_title(wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity()))
.with_app_id(app_id)
.with_inner_size([1440.0, 920.0])
.with_min_inner_size(wordcraft_ui_egui::window_geometry::MIN_SIZE)
.with_drag_and_drop(true)
.with_fullsize_content_view(true)
.with_titlebar_shown(false)
.with_title_shown(false),
..Default::default()
};
if let Some(icon) = app_icon() {
viewport = viewport.with_icon(icon);
options.viewport = options.viewport.with_icon(icon);
}
// Before eframe creates the wgpu instance: the backends, power preference, shader compiler and
// the GPU that drives the screen (#603, #2652, #5199).
if let eframe::egui_wgpu::WgpuSetup::CreateNew(setup) = &mut options.wgpu_options.wgpu_setup {
craft::gpu::configure(setup);
}
prefs::load_user_fonts();
// Where the root window was last, kept beside the settings; in memory when preferences are off.
@@ -652,18 +708,16 @@ fn main() -> eframe::Result {
let display_server = settings.lock().get().display_server;
let (x11, why) = uses_x11(display_server, |name| std::env::var_os(name), x11_libraries);
log::info!("{why}");
if x11 {
options.event_loop_builder = Some(Box::new(|b| {
use winit::platform::x11::EventLoopBuilderExtX11;
b.with_x11();
}));
}
x11
};
#[cfg(not(all(unix, not(target_os = "macos"))))]
let x11 = false;
// The windowless root by default; windowed when rolled back, or when winit will open X11 or
// XWayland, which its bootstrap doesn't support (`startup_mode`).
#[cfg(all(unix, not(target_os = "macos")))]
let winit_x11 = startup_mode::winit_picks_x11(x11, |name| std::env::var_os(name));
#[cfg(not(all(unix, not(target_os = "macos"))))]
let winit_x11 = false;
let first_mode = startup_mode::first_mode(std::env::var_os(startup_mode::ROLLBACK_VAR).as_deref(), winit_x11);
log::info!("root: {first_mode:?} first");
// What the OS asks of a running app arrives here; its wake repaints once the window exists.
let repaint: Arc<OnceLock<egui::Context>> = Arc::new(OnceLock::new());
let (intake, sender) = FileIntake::new(Wake::new({
@@ -674,39 +728,10 @@ fn main() -> eframe::Result {
}
}
}));
let drops = intake.sender();
// Each start's options, from scratch: a fallback start gets the plain windowed ones.
let hook_drops = drops.clone();
let document_windows = document_panels::DocumentWindows::default();
let hook_windows = document_windows.clone();
let native_options = move |mode: eframe::RootViewportMode| {
let mut options = eframe::NativeOptions {
root_viewport_mode: mode,
// A refused start must return here, on the thread whose event loop the fallback reuses.
run_and_return: true,
viewport: viewport.clone(),
..Default::default()
};
// Before eframe creates the wgpu instance: the backends, power preference, shader compiler
// and the GPU that drives the screen (#603, #2652, #5199).
if let eframe::egui_wgpu::WgpuSetup::CreateNew(setup) = &mut options.wgpu_options.wgpu_setup {
craft::gpu::configure(setup);
}
// Read only when the first start builds the event loop; a fallback reuses that loop.
#[cfg(all(unix, not(target_os = "macos")))]
if x11 {
options.event_loop_builder = Some(Box::new(|b| {
use winit::platform::x11::EventLoopBuilderExtX11;
b.with_x11();
}));
}
if mode == eframe::RootViewportMode::Windowless {
options.viewport_hooks = Some(hook_windows.hooks(hook_drops.clone()));
}
options
};
// Registered before the event loop starts, so it catches the Finder event that launched us as
// well as later ones. Lives until the event loop returns.
let drops = intake.sender();
options.viewport_hooks = Some(Arc::new(ChildDrops(drops.clone())));
#[cfg(target_os = "macos")]
let _apple_events = craft::platform::open::apple_events::install(sender);
#[cfg(not(target_os = "macos"))]
@@ -736,10 +761,12 @@ fn main() -> eframe::Result {
let noticed_for_exit = unclean_notice_shown.clone();
let noticed_in_window = unclean_notice_shown.clone();
let exit_settings = settings.clone();
// Everything a start hands the app, used by the one creator that runs (`startup_mode::run`).
let create_app = move |cc: &eframe::CreationContext<'_>,
mode: eframe::RootViewportMode|
-> Result<Box<dyn eframe::App>, Box<dyn std::error::Error + Send + Sync>> {
// The root window is never shown (ADR 0001): eframe runs a windowless root and every document is a child
// window. X11, XWayland and BSD on X11 cannot, so they keep the visible root (the ADR's amendment). The mode
// is read by the app creator, which runs once the mode is settled.
let windowless = Arc::new(std::sync::atomic::AtomicBool::new(!x11));
let windowless_in_app = windowless.clone();
let creator: eframe::AppCreator<'static> = Box::new(move |cc| {
let ctx = cc.egui_ctx.clone();
let _ = repaint.set(ctx.clone());
let wake = {
@@ -758,11 +785,15 @@ fn main() -> eframe::Result {
.build(),
);
let shell = ShellInfo::current().backend(if x11 { Backend::X11 } else { Backend::from_env() });
let spec = InstallSpec::new(shell, Arc::new(SystemWindows))
let mut spec = InstallSpec::new(shell, Arc::new(SystemWindows))
.app_id(wordcraft_ui_egui::os_window::app_id())
.system(SystemReader::start(wake))
.clipboard(Clipboard::new(SystemClipboard::new().decoder(decode_png)))
.placement(placement);
// The runtime and eframe must agree on the root.
if windowless_in_app.load(std::sync::atomic::Ordering::Relaxed) {
spec = spec.windowless_root();
}
// PLAN: assumed `wordcraft_ui_egui::ui_fonts` re-exports sh.A10's `app::fonts::ui_fonts` (`mod app` is private; app-hub/shell-w11).
embed::install(&ctx, spec, &wordcraft_ui_egui::ui_fonts(lang)).map_err(|e| format!("the runtime could not be installed: {e}"))?;
// The system region picks the new document's paper, the units and the decimal
@@ -779,11 +810,6 @@ fn main() -> eframe::Result {
}
let spool = Spool::new(host.jobs_shared().clone());
let mut app = WordApp::new(session, services(spool.clone(), intake, nightly)).with_host(host).with_settings(settings.clone());
let windowless = mode == eframe::RootViewportMode::Windowless;
app.enable_windowless_trial(windowless);
if windowless {
app.set_native_window_lookup(Some(Arc::new(document_windows.clone())));
}
// Drawn by the processor (WARP, llvmpipe; #2221), animations that follow the system stop.
if let Some(state) = &cc.wgpu_render_state {
let info = state.adapter.get_info();
@@ -832,13 +858,41 @@ fn main() -> eframe::Result {
log::warn!("local recovery unavailable: {e}");
}
}
// Agents in the open window: while the ArtCraft Launcher's switch (Settings › AI agents)
// names WordCraft, the agent link serves them and publishes where, so `wordcraft-cli mcp`
// finds the window. `--control` runs its own server for the whole run instead. Allow
// Agent Control off (File › Options › Agents) refuses both. A Nightly window serves none.
let mut control_server = None;
if !nightly
&& let Some(port) = control.port
&& let Some((rx, started)) = control_server::start(&control, port, WindowHost::of(&ctx), wordcraft_control_key::settings_dir().as_deref())
{
app = app.with_control(ControlChannel::new(rx));
control_server = Some(started);
if !nightly {
let settings_dir = wordcraft_control_key::settings_dir();
// A file a crashed launch left behind names a port nothing serves; before this
// launch's own listener, so it doesn't keep it.
if let Some(dir) = &settings_dir {
craft::automation::agents::remove_stale_connection(dir);
}
let allow = settings.lock().get().integrations.allow_agent_control;
let launched = match control.port {
Some(port) if !allow => {
complain(format_args!("File › Options › Agents › Allow Agent Control is off: not listening on port {port}"));
None
}
Some(port) => control_server::start(&control, port, WindowHost::of(&ctx), settings_dir.as_deref()),
None => None,
};
let link = match launched {
Some((rx, started)) => {
app = app.with_control(ControlChannel::new(rx));
let (listening, token_file) = started.split();
control_server = Some(token_file);
craft::automation::agents::AgentLink::from_launch(listening)
}
None => craft::automation::agents::AgentLink::new(settings_dir, format!("WordCraft {}", env!("CARGO_PKG_VERSION"))),
};
let switch = craft::automation::agents::AgentSwitch::watch(wordcraft_ui_egui::agents::LAUNCHER_APP_ID, {
let ctx = ctx.clone();
move || ctx.request_repaint()
});
app = app.with_agents(wordcraft_ui_egui::agents::Agents::new(link, switch));
}
// Nothing to open (no files, no sample, no control channel driving the editor): start
// on File › Home, as Word does (#766), unless the Start screen option is off. Files
@@ -871,7 +925,6 @@ fn main() -> eframe::Result {
native_menu: native_menu::install(&ctx, &app),
app,
panels,
document_windows,
drops,
settings,
spool,
@@ -880,17 +933,8 @@ fn main() -> eframe::Result {
nightly_session::finish_once(&session_for_exit, noticed_for_exit.load(std::sync::atomic::Ordering::Relaxed));
})),
}))
};
let result = startup_mode::run(first_mode, create_app, |mode, inputs| {
eframe::run_native(
wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity()),
native_options(mode),
Box::new(move |cc| {
let create = inputs.take().ok_or("the app was already created")?;
create(cc, mode)
}),
)
});
let result = run_with_visible_root_fallback(creator, windowless, options);
// The exit hook has run; this is the no-op fallback for a start that created no window.
nightly_session::finish_once(&nightly_watch, unclean_notice_shown.load(std::sync::atomic::Ordering::Relaxed));
// The app is dropped by now: whatever it saved on the way out is in the store.
@@ -1054,7 +1098,6 @@ mod launch_arg_tests {
#[cfg(test)]
mod smoke {
use super::*;
use craft::platform::open::DroppedFile;
use craft::ui::testing::Frames;
use serde_json::json;
@@ -1102,7 +1145,6 @@ mod smoke {
native_menu: None,
app,
panels,
document_windows: Default::default(),
drops,
settings,
spool,
@@ -1257,6 +1299,54 @@ mod smoke {
assert!(run.app.app.dialog_host_mut().is_empty(), "Escape dismisses About");
assert_eq!(run.app.app.session.doc.plain_text(wordcraft_doc::StoryRef::Body), before);
}
/// With a modal dialog open, Quit stays enabled and ⌘Q / menu Quit still run `ui.quit`:
/// a clean document quits and a modified one opens Save Changes (#8792).
#[cfg(target_os = "macos")]
#[test]
fn native_quit_works_while_a_modal_dialog_is_open() {
use craft::menu::{ItemRole, NativeMenu};
let mut clean = Run::new();
let fake = native_menu::FakeBackend::default();
let synced = fake.synced.clone();
let events = fake.events.clone();
let dispatch_cell = fake.dispatch.clone();
clean.app.native_menu = Some(NativeMenu::new(Box::new(fake)));
clean.app.app.run("ui.dialog", json!({"name": "about"})).unwrap();
clean.settle();
assert!(clean.app.app.dialog_host_mut().shows_modal());
let quit = {
let bars = synced.borrow();
let bar = bars.last().unwrap();
let about = bar.items().into_iter().find(|item| item.role == Some(ItemRole::About)).unwrap();
let quit = bar.items().into_iter().find(|item| item.role == Some(ItemRole::Quit)).unwrap();
assert!(!about.enabled, "About is greyed while About is open");
assert!(quit.enabled, "Quit stays enabled while About is open");
quit.clone()
};
let dispatch = dispatch_cell.borrow().as_ref().unwrap().clone();
let cmd_q = quit.shortcut.unwrap();
events.borrow_mut().push(dispatch.chosen(&quit.command, Some(&cmd_q), quit.layout_shortcut, true, cmd_q.mods, None));
clean.settle();
assert!(clean.app.app.quit_requested, "Cmd+Q quits a clean document while About is open");
let mut dirty = Run::new();
let fake = native_menu::FakeBackend::default();
let events = fake.events.clone();
let dispatch_cell = fake.dispatch.clone();
dirty.app.native_menu = Some(NativeMenu::new(Box::new(fake)));
dirty.app.app.run("text.insert", json!({"text": "unsaved"})).unwrap();
dirty.app.app.run("ui.dialog", json!({"name": "paragraph"})).unwrap();
dirty.settle();
assert!(dirty.app.app.dialog_host_mut().shows_modal());
let dispatch = dispatch_cell.borrow().as_ref().unwrap().clone();
events.borrow_mut().push(dispatch.chosen(&quit.command, Some(&cmd_q), quit.layout_shortcut, false, Default::default(), None));
dirty.settle();
assert!(!dirty.app.app.quit_requested, "Quit asks Save Changes first for a modified document");
dirty.app.app.run("ui.saveChanges", json!({"answer": "dontSave"})).unwrap();
assert!(dirty.app.app.quit_requested, "Don't Save completes the quit");
}
}
#[cfg(test)]
+87 -5
View File
@@ -1,18 +1,27 @@
//! The macOS application menu uses the same About dialog as File › About.
use craft::menu::{CommandRef, Gate, Item, ItemRole, Layout, LayoutOptions, Menu, MenuBar, MenuRole, NativeMenu, mac_layout};
use craft::menu::{CommandRef, Gate, Item, ItemRole, Layout, LayoutOptions, Menu, MenuBar, MenuRole, ModalRules, NativeMenu, mac_layout};
use serde_json::json;
use wordcraft_ui_egui::{WordApp, i18n};
const APP_NAME: &str = "WordCraft";
const ABOUT: &str = "About WordCraft";
const QUIT: &str = "Quit WordCraft";
/// The application menu, with `tr` the translation of an English string.
pub(super) fn layout(tr: &dyn Fn(&'static str) -> String) -> Layout {
let about = Item::new(CommandRef::with_params("ui.dialog", json!({"name": "about"})), tr(ABOUT)).role(ItemRole::About);
let bar = MenuBar::new(vec![Menu::new(APP_NAME, vec![about.into()]).role(MenuRole::App)]);
// Without its own Quit `mac_layout` adds one whose click only closes the root window: it must ask about every document.
let quit = Item::new(CommandRef::new("ui.quit"), tr(QUIT)).role(ItemRole::Quit);
let bar = MenuBar::new(vec![Menu::new(APP_NAME, vec![about.into(), quit.into()]).role(MenuRole::App)]);
// `mac_layout` words About as the template; WordCraft's catalogs translate the whole label.
let label = |s: &'static str| tr(if s == "About {app}" { ABOUT } else { s });
let label = |s: &'static str| {
tr(match s {
"About {app}" => ABOUT,
"Quit {app}" => QUIT,
s => s,
})
};
let mut layout = mac_layout(&bar, &LayoutOptions::new(APP_NAME).label(&label));
// WordCraft's document menus live in its ribbon; keep only the application menu.
layout.bar.menus.retain(|menu| menu.role == MenuRole::App);
@@ -27,15 +36,24 @@ fn layout_in(lang: i18n::Lang) -> Layout {
layout(&|s| i18n::tr(lang, s).to_owned())
}
/// Commands that still run from the application menu while a modal dialog is open: `ui.quit` asks
/// about unsaved documents through `WordApp::quit`, matching the built-in Quit item and the Dock.
fn modal_rules() -> ModalRules {
ModalRules::default().in_dialogs(["ui.quit"])
}
pub(super) fn install(ctx: &egui::Context, app: &WordApp) -> Option<NativeMenu> {
let menu = craft::menu::mac::install(ctx, &layout_in(lang(app)).bar);
if menu.is_none() {
let mut menu = craft::menu::mac::install(ctx, &layout_in(lang(app)).bar);
if let Some(menu) = &mut menu {
menu.set_modal_rules(modal_rules());
} else {
log::warn!("the WordCraft application menu could not be installed");
}
menu
}
pub(super) fn update(menu: &mut NativeMenu, app: &mut WordApp, ctx: &egui::Context) {
menu.set_modal_rules(modal_rules());
menu.set_gate(Gate::default().modal(app.dialog_host_mut().shows_modal()));
for command in menu.take_clicks(ctx) {
if let Err(error) = app.run(&command.id, command.params) {
@@ -49,6 +67,29 @@ pub(super) fn update(menu: &mut NativeMenu, app: &mut WordApp, ctx: &egui::Conte
}
}
#[cfg(test)]
#[derive(Default)]
pub(super) struct FakeBackend {
pub(super) synced: std::rc::Rc<std::cell::RefCell<Vec<MenuBar>>>,
pub(super) events: std::rc::Rc<std::cell::RefCell<Vec<craft::menu::Event>>>,
pub(super) dispatch: std::rc::Rc<std::cell::RefCell<Option<craft::menu::Dispatch>>>,
}
#[cfg(test)]
impl craft::menu::Backend for FakeBackend {
fn sync(&mut self, bar: &MenuBar) {
self.synced.borrow_mut().push(bar.clone());
}
fn attach(&mut self, dispatch: craft::menu::Dispatch) {
*self.dispatch.borrow_mut() = Some(dispatch);
}
fn drain(&mut self) -> Vec<craft::menu::Event> {
std::mem::take(&mut *self.events.borrow_mut())
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -61,4 +102,45 @@ mod tests {
let about = layout.bar.items().into_iter().find(|item| item.role == Some(ItemRole::About)).unwrap();
assert_eq!(about.label, "Über WordCraft");
}
/// ⌘Q and the menu's Quit run `ui.quit`, which asks about unsaved documents; craft's built-in Quit only closes the root window (#8709).
#[test]
fn quit_runs_the_command_that_asks_about_documents() {
let layout = layout(&|s| s.to_owned());
let quit = layout.bar.items().into_iter().find(|item| item.role == Some(ItemRole::Quit)).unwrap();
assert_eq!(quit.command.id, "ui.quit");
}
/// Quit stays enabled while a modal dialog is open, and both a menu click and ⌘Q pass the gate (#8792).
#[test]
fn quit_stays_enabled_and_runs_under_modal_rules() {
let fake = FakeBackend::default();
let synced = fake.synced.clone();
let events = fake.events.clone();
let dispatch_cell = fake.dispatch.clone();
let mut menu = NativeMenu::new(Box::new(fake));
menu.set_modal_rules(modal_rules());
menu.set_gate(Gate::default().modal(true));
let ctx = egui::Context::default();
menu.sync_with("en", || layout(&|s| s.to_owned()));
let bar = synced.borrow();
let last = bar.last().unwrap();
let about = last.items().into_iter().find(|item| item.role == Some(ItemRole::About)).unwrap().clone();
let quit = last.items().into_iter().find(|item| item.role == Some(ItemRole::Quit)).unwrap().clone();
drop(bar);
assert!(!about.enabled, "About is greyed while a modal dialog is open");
assert!(quit.enabled, "Quit stays enabled while a modal dialog is open");
let dispatch = dispatch_cell.borrow().as_ref().unwrap().clone();
let cmd_q = quit.shortcut.unwrap();
events.borrow_mut().extend([
dispatch.chosen(&about.command, about.shortcut.as_ref(), about.layout_shortcut, false, Default::default(), None),
dispatch.chosen(&quit.command, Some(&cmd_q), quit.layout_shortcut, false, Default::default(), None),
dispatch.chosen(&quit.command, Some(&cmd_q), quit.layout_shortcut, true, cmd_q.mods, None),
]);
menu.poll(&ctx);
assert_eq!(menu.take_clicks(&ctx), vec![quit.command.clone(), quit.command]);
}
}
-172
View File
@@ -1,172 +0,0 @@
//! Which root WordCraft starts with, and the one fallback to normal windows.
//!
//! The windowless root is the default. `WORDCRAFT_WINDOWLESS_TRIAL=0` (exactly `0`) rolls back to
//! a windowed root; any other value, or none, keeps the default. On Linux and the BSDs the
//! windowless bootstrap supports only native Wayland, so a start whose event loop winit will open
//! on X11 or XWayland starts windowed from the outset and never retries ([`winit_picks_x11`]).
//!
//! Everything else is decided by eframe, from the display it actually connected to: its windowless
//! bootstrap returns [`eframe::Error::UnsupportedConfiguration`] for an X11 display handle (and,
//! on macOS and Windows, for a renderer bootstrap it cannot use) before it calls the app creator
//! and before any root window exists. With `run_and_return` that error comes back out of
//! `run_native`, the thread's event loop stays cached, and a second `run_native` on this thread
//! reuses it. [`run`] then starts once more with normal windows, only when the creator has not
//! started. Every other error, a second `UnsupportedConfiguration`, and any error after the
//! creator started (including a document window whose surface cannot be attached later, which
//! eframe reports per document) is returned unchanged.
//!
//! Source-only caveat: on a native Wayland display eframe's logical root takes the launcher's
//! activation token before the renderer starts, so a fallback window there may open without it.
use std::cell::RefCell;
use std::rc::Rc;
use eframe::RootViewportMode;
/// The variable that rolls the windowless root back to a windowed one, with the value `0`.
pub(crate) const ROLLBACK_VAR: &str = "WORDCRAFT_WINDOWLESS_TRIAL";
/// The root mode of the first start: windowed when rolled back or when winit opens X11.
pub(crate) fn first_mode(rollback: Option<&std::ffi::OsStr>, x11: bool) -> RootViewportMode {
if x11 || rollback.is_some_and(|v| v == "0") { RootViewportMode::Windowed } else { RootViewportMode::Windowless }
}
/// Whether winit's event loop opens on X11 (XWayland included): forced by the app, or unforced
/// with no Wayland display and an X server. Mirrors the pinned winit's choice exactly: empty and
/// non-Unicode values count as unset, and Wayland wins over `DISPLAY` when unforced. Neither set
/// means winit fails to start at all, which no mode changes.
#[cfg(all(unix, not(target_os = "macos")))]
pub(crate) fn winit_picks_x11(forced_x11: bool, env: impl Fn(&str) -> Option<std::ffi::OsString>) -> bool {
let set = |name: &str| env(name).is_some_and(|v| v.to_str().is_some_and(|v| !v.is_empty()));
forced_x11 || (!set("WAYLAND_DISPLAY") && !set("WAYLAND_SOCKET") && set("DISPLAY"))
}
/// The app's one-shot startup inputs, shared by every start but taken by one app creator only.
pub(crate) struct OneShot<T>(Rc<RefCell<Option<T>>>);
impl<T> Clone for OneShot<T> {
fn clone(&self) -> Self {
Self(Rc::clone(&self.0))
}
}
impl<T> OneShot<T> {
/// The inputs, for the app creator that runs; `None` once any creator has taken them.
pub(crate) fn take(&self) -> Option<T> {
self.0.borrow_mut().take()
}
fn untouched(&self) -> bool {
self.0.borrow().is_some()
}
}
/// Starts the app in `first` mode through `launch`, and once more with normal windows when a
/// windowless start was refused as unsupported before its app creator took `inputs`.
pub(crate) fn run<T>(first: RootViewportMode, inputs: T, mut launch: impl FnMut(RootViewportMode, OneShot<T>) -> eframe::Result) -> eframe::Result {
let inputs = OneShot(Rc::new(RefCell::new(Some(inputs))));
match launch(first, inputs.clone()) {
Err(eframe::Error::UnsupportedConfiguration(reason)) if first == RootViewportMode::Windowless && inputs.untouched() => {
log::warn!("windowless start unsupported here ({reason}); opening normal windows instead");
launch(RootViewportMode::Windowed, inputs)
}
other => other,
}
}
#[cfg(test)]
mod tests {
use super::*;
use RootViewportMode::{Windowed, Windowless};
fn unsupported() -> eframe::Result {
Err(eframe::Error::UnsupportedConfiguration("windowless root: X11".into()))
}
/// Runs the real policy with scripted starts; each step sees whether it may create the app and
/// returns that start's result. Returns the modes started, the modes that created the app, and
/// the result.
fn script(first: RootViewportMode, mut steps: Vec<(bool, eframe::Result)>) -> (Vec<RootViewportMode>, Vec<RootViewportMode>, eframe::Result) {
steps.reverse();
let mut started = Vec::new();
let mut created = Vec::new();
let result = run(first, "inputs", |mode, inputs| {
started.push(mode);
let (creates, result) = steps.pop().unwrap_or((false, Ok(())));
if creates && inputs.take().is_some() {
created.push(mode);
}
result
});
(started, created, result)
}
#[test]
fn an_unsupported_windowless_bootstrap_starts_once_more_with_windows() {
let (started, created, result) = script(Windowless, vec![(false, unsupported()), (true, Ok(()))]);
assert_eq!(started, [Windowless, Windowed]);
assert_eq!(created, [Windowed], "the inputs reach the windowed start's creator, once");
assert!(result.is_ok());
}
#[test]
fn the_windowed_start_is_the_last_one() {
let (started, created, result) = script(Windowless, vec![(false, unsupported()), (false, unsupported())]);
assert_eq!(started, [Windowless, Windowed]);
assert!(created.is_empty());
assert!(matches!(result, Err(eframe::Error::UnsupportedConfiguration(_))));
}
#[test]
fn a_windowed_start_is_never_retried() {
let (started, _, result) = script(first_mode(None, true), vec![(false, unsupported())]);
assert_eq!(started, [Windowed], "X11 starts windowed, once");
assert!(matches!(result, Err(eframe::Error::UnsupportedConfiguration(_))));
}
#[test]
fn other_errors_come_back_unchanged() {
let (started, _, result) = script(Windowless, vec![(false, Err(eframe::Error::AppCreation("no runtime".into())))]);
assert_eq!(started, [Windowless]);
assert!(matches!(result, Err(eframe::Error::AppCreation(e)) if e.to_string() == "no runtime"));
}
#[test]
fn nothing_starts_again_once_the_app_creator_ran() {
let (started, created, result) = script(Windowless, vec![(true, unsupported())]);
assert_eq!((started, created), (vec![Windowless], vec![Windowless]));
assert!(matches!(result, Err(eframe::Error::UnsupportedConfiguration(_))));
}
#[test]
fn only_exactly_zero_rolls_back() {
let var = |v: &str| Some(std::ffi::OsString::from(v));
assert_eq!(first_mode(var("0").as_deref(), false), Windowed);
for value in [None, var("1"), var(""), var("off"), var(" 0")] {
assert_eq!(first_mode(value.as_deref(), false), Windowless, "{value:?}");
}
}
/// The pinned winit opens Wayland whenever a Wayland display is named and the app forces
/// nothing, even with `DISPLAY` set; X11 only when forced or with no Wayland display.
#[cfg(all(unix, not(target_os = "macos")))]
#[test]
fn x11_is_what_winit_opens_not_what_the_session_says() {
use std::os::unix::ffi::OsStringExt;
let picks = |forced, vars: &[(&str, &str)]| {
winit_picks_x11(forced, |name| vars.iter().find(|(k, _)| *k == name).map(|(_, v)| std::ffi::OsString::from(v)))
};
let both = [("DISPLAY", ":0"), ("WAYLAND_DISPLAY", "wayland-0")];
assert!(picks(true, &both), "forced XWayland");
assert!(!picks(false, &both), "unforced, Wayland wins");
assert!(!picks(false, &[("DISPLAY", ":0"), ("WAYLAND_SOCKET", "3")]));
assert!(picks(false, &[("DISPLAY", ":0"), ("WAYLAND_DISPLAY", "")]), "an empty Wayland display is unset");
assert!(!picks(false, &[]));
let non_unicode = |name: &str| match name {
"DISPLAY" => Some(":0".into()),
"WAYLAND_DISPLAY" => Some(std::ffi::OsString::from_vec(b"w\xe9".to_vec())),
_ => None,
};
assert!(winit_picks_x11(false, non_unicode), "winit reads a non-Unicode Wayland display as unset");
}
}
+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() };
+24 -1
View File
@@ -23,7 +23,8 @@ mod para_props;
mod table_props;
pub use char_props::{
CharProps, CombineBrackets, DEFAULT_FONT_SIZE, EastAsianLayout, EmphasisMark, Highlight, Ligatures, NumChange, PropChange, Underline, VertAlign,
CharProps, CombineBrackets, DEFAULT_FONT_SIZE, EastAsianLayout, EmphasisMark, Highlight, Ligatures, NumChange, PropChange, ThemeFont, Underline,
VertAlign,
};
pub use color::{Rgb, TextColor};
pub use para_props::{
@@ -200,4 +201,26 @@ mod tests {
assert_eq!(changed.sym_font.as_deref(), Some("Wingdings"));
assert_eq!(p.cleared().sym_font.as_deref(), Some("Wingdings"));
}
#[test]
fn named_east_asian_font_replaces_theme_slot_and_minus_round_trips() {
let mut base = CharProps { font_ea: Some("Times New Roman".into()), font_ea_theme: Some(ThemeFont::MinorEastAsia), ..Default::default() };
let named = CharProps { font_ea: Some("SimSun".into()), ..Default::default() };
base.overlay(&named);
assert_eq!(base.font_ea.as_deref(), Some("SimSun"));
assert_eq!(base.font_ea_theme, None);
// Changing only `font_ea` while keeping `font_ea_theme` preserves the slot across minus/overlay.
let themed_base = CharProps { font_ea: Some("SimSun".into()), font_ea_theme: Some(ThemeFont::MinorEastAsia), ..Default::default() };
let run = CharProps { font_ea: Some("MS Mincho".into()), ..themed_base.clone() };
let mut back = themed_base.clone();
back.overlay(&run.clone().minus(&themed_base));
assert_eq!(back, run);
// Clearing `font_ea_theme` while keeping the same `font_ea` preserves `font_ea` in the patch.
let cleared_slot = CharProps { font_ea_theme: None, ..themed_base.clone() };
let mut back_cleared = themed_base.clone();
back_cleared.overlay(&cleared_slot.clone().minus(&themed_base));
assert_eq!(back_cleared, cleared_slot);
}
}
+76 -2
View File
@@ -329,6 +329,10 @@ pub struct CharProps {
/// inherit, then `font`.
#[serde(skip_serializing_if = "Option::is_none")]
pub font_ea: Option<String>,
/// The theme font slot of the East Asian font (`w:rFonts/@w:eastAsiaTheme`: `minorEastAsia`,
/// `majorEastAsia`…), taking precedence over `font_ea` when set.
#[serde(skip_serializing_if = "Option::is_none")]
pub font_ea_theme: Option<ThemeFont>,
/// Complex-script size, points (`w:szCs`). `None` leaves the inherited value unchanged.
#[serde(skip_serializing_if = "Option::is_none")]
pub size_cs: Option<f32>,
@@ -450,6 +454,62 @@ impl CombineBrackets {
}
}
/// A theme font slot in `w:rFonts` (`ST_Theme`, ECMA-376 §17.18.96).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ThemeFont {
MajorEastAsia,
MajorBidi,
MajorAscii,
MajorHAnsi,
MinorEastAsia,
MinorBidi,
MinorAscii,
MinorHAnsi,
}
impl ThemeFont {
const ALL: [ThemeFont; 8] = [
ThemeFont::MajorEastAsia,
ThemeFont::MajorBidi,
ThemeFont::MajorAscii,
ThemeFont::MajorHAnsi,
ThemeFont::MinorEastAsia,
ThemeFont::MinorBidi,
ThemeFont::MinorAscii,
ThemeFont::MinorHAnsi,
];
/// The OOXML `ST_Theme` value.
pub fn as_str(self) -> &'static str {
match self {
ThemeFont::MajorEastAsia => "majorEastAsia",
ThemeFont::MajorBidi => "majorBidi",
ThemeFont::MajorAscii => "majorAscii",
ThemeFont::MajorHAnsi => "majorHAnsi",
ThemeFont::MinorEastAsia => "minorEastAsia",
ThemeFont::MinorBidi => "minorBidi",
ThemeFont::MinorAscii => "minorAscii",
ThemeFont::MinorHAnsi => "minorHAnsi",
}
}
/// Parse an OOXML `ST_Theme` value (`None` for any value outside the schema).
pub fn parse(s: &str) -> Option<ThemeFont> {
ThemeFont::ALL.into_iter().find(|t| t.as_str() == s)
}
/// Whether this slot picks the theme's major (heading) font rather than minor (body).
pub fn is_major(self) -> bool {
matches!(self, ThemeFont::MajorEastAsia | ThemeFont::MajorBidi | ThemeFont::MajorAscii | ThemeFont::MajorHAnsi)
}
/// Whether this is one of the Latin theme slots (`ascii` / `hAnsi`).
pub fn is_latin(self) -> bool {
matches!(self, ThemeFont::MajorAscii | ThemeFont::MajorHAnsi | ThemeFont::MinorAscii | ThemeFont::MinorHAnsi)
}
}
/// A tracked formatting change (ECMA-376 §17.13.5: `w:rPrChange`, `w:pPrChange`,
/// `w:tblPrChange`, `w:trPrChange`, `w:tcPrChange`, `w:sectPrChange`): the properties as they
/// were before the change, and the revision (author, date) that made it.
@@ -509,7 +569,16 @@ impl CharProps {
}
fn minus_script_style(&mut self, base: &CharProps) {
drop_same_fields!(self, base; cs, font_cs, font_ea, size_cs, bold_cs, italic_cs, lang_bidi, lang_ea, east_asian_layout);
// A theme slot stays while its named font does; a same font stays when its slot differs.
let keep = self.font_ea_theme;
let ea = self.font_ea.clone();
drop_same_fields!(self, base; cs, font_cs, font_ea, font_ea_theme, size_cs, bold_cs, italic_cs, lang_bidi, lang_ea, east_asian_layout);
if self.font_ea.is_none() && keep != base.font_ea_theme {
self.font_ea = ea;
}
if self.font_ea.is_some() {
self.font_ea_theme = keep;
}
}
fn minus_document_marks(&mut self, base: &CharProps) {
@@ -540,7 +609,12 @@ impl CharProps {
}
fn overlay_script_style(&mut self, patch: &CharProps) {
overlay_fields!(self, patch; cs, font_cs, font_ea, size_cs, bold_cs, italic_cs, lang_bidi, lang_ea, east_asian_layout);
// A named East Asian font without a theme slot replaces the slot too: Word gives the slot
// precedence over the named font, so keeping it would hide the font just chosen.
if patch.font_ea.is_some() && patch.font_ea_theme.is_none() {
self.font_ea_theme = None;
}
overlay_fields!(self, patch; cs, font_cs, font_ea, font_ea_theme, size_cs, bold_cs, italic_cs, lang_bidi, lang_ea, east_asian_layout);
}
fn overlay_document_marks(&mut self, patch: &CharProps) {
+6 -1
View File
@@ -4,7 +4,7 @@
use serde::{Deserialize, Serialize};
use crate::props::{
Align, Border, Borders, CharProps, Highlight, LineSpacing, NumRef, ParaProps, Rgb, TabAlign, TabStop, TextColor, Underline, VertAlign,
Align, Border, Borders, CharProps, Highlight, LineSpacing, NumRef, ParaProps, Rgb, TabAlign, TabStop, TextColor, ThemeFont, Underline, VertAlign,
};
use crate::styles::{StyleKind, StyleSheet};
@@ -71,6 +71,10 @@ pub struct ResolvedChar {
/// East Asian font (Chinese, Japanese and Korean text), when one is set.
#[serde(skip_serializing_if = "Option::is_none")]
pub font_ea: Option<String>,
/// Theme font slot for the East Asian font (`w:eastAsiaTheme`), taking precedence over
/// `font_ea` when set.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub font_ea_theme: Option<ThemeFont>,
pub size_cs: f32,
pub bold_cs: bool,
pub italic_cs: bool,
@@ -117,6 +121,7 @@ impl ResolvedChar {
cs: c.cs.unwrap_or(false),
font_cs: c.font_cs.clone().or_else(|| c.font.clone()).unwrap_or_else(|| crate::styles::BODY_FONT.to_string()),
font_ea: c.font_ea.clone(),
font_ea_theme: c.font_ea_theme,
size_cs: c.size_cs.or(c.size).unwrap_or(crate::props::DEFAULT_FONT_SIZE).clamp(1.0, 1638.0),
// A run marked complex script (`w:cs`) is bold and italic only by `w:bCs` and `w:iCs`:
// Word draws Thai with `<w:b/><w:cs/>` and no `w:bCs` upright and plain (measured in
+22 -3
View File
@@ -296,6 +296,7 @@ impl NumFormat {
use crate::cjk_numbers as cjk;
match self {
NumFormat::DecimalZero => format!("{n:02}"),
NumFormat::Hex => format!("{n:X}"),
NumFormat::ThaiNumbers => thai_digits(n),
NumFormat::UpperRoman => roman(n).to_uppercase(),
NumFormat::LowerRoman => roman(n),
@@ -341,7 +342,6 @@ impl NumFormat {
NumFormat::Chosung => cjk::chosung(n),
NumFormat::Decimal
| NumFormat::DecimalHalfWidth
| NumFormat::Hex
| NumFormat::VietnameseCounting
| NumFormat::Hebrew1
| NumFormat::Hebrew2
@@ -496,13 +496,21 @@ pub fn cardinal_text(n: u32) -> String {
let h = format!("{} hundred", words(n / 100));
if n.is_multiple_of(100) { h } else { format!("{h} {}", words(n % 100)) }
}
_ => {
1_000..=999_999 => {
let th = format!("{} thousand", words(n / 1000));
if n.is_multiple_of(1000) { th } else { format!("{th} {}", words(n % 1000)) }
}
1_000_000..=999_999_999 => {
let m = format!("{} million", words(n / 1_000_000));
if n.is_multiple_of(1_000_000) { m } else { format!("{m} {}", words(n % 1_000_000)) }
}
_ => {
let b = format!("{} billion", words(n / 1_000_000_000));
if n.is_multiple_of(1_000_000_000) { b } else { format!("{b} {}", words(n % 1_000_000_000)) }
}
}
}
capitalize(&words(n.min(999_999)))
capitalize(&words(n))
}
/// English ordinal words (`Twenty-First`).
@@ -1004,6 +1012,17 @@ mod tests {
assert_eq!(NumFormat::from_ooxml("klingon"), NumFormat::Decimal, "unknown formats are decimal");
}
#[test]
fn hex_and_large_number_text() {
assert_eq!(NumFormat::Hex.format(10), "A");
assert_eq!(NumFormat::Hex.format(15), "F");
assert_eq!(NumFormat::Hex.format(16), "10");
assert_eq!(NumFormat::Hex.format(255), "FF");
assert_eq!(NumFormat::CardinalText.format(1_000_000), "One Million");
assert_eq!(NumFormat::OrdinalText.format(1_000_000), "One Millionth");
assert_eq!(NumFormat::CardinalText.format(2_000_000_000), "Two Billion");
}
/// #5757: Thai numbers are the decimal number in Thai digits, every digit, at any length.
#[test]
fn thai_numbers_use_thai_digits() {
+36 -16
View File
@@ -1330,6 +1330,8 @@ fn hinted_east_asian_or_cs_font_does_not_replace_the_latin_font() {
assert_eq!((ea.font.as_str(), ea.font_ea.as_deref()), ("Times New Roman", Some("宋体")));
let cs = d.styles.resolve_char(p.props.style.as_deref(), &p.runs[1].props);
assert_eq!((cs.font.as_str(), cs.font_cs.as_str()), ("Times New Roman", "Arial"));
assert_eq!(ea.font_ea_theme, None, "named w:eastAsia replaces Heading2's w:eastAsiaTheme");
assert_eq!(cs.font_ea_theme, Some(wordcraft_doc::props::ThemeFont::MajorEastAsia));
}
#[test]
@@ -2444,33 +2446,51 @@ fn note_separators_and_continuation_notice_round_trip() {
check(&wordcraft_docx::read(&out).unwrap());
}
/// A picture frame shape in a footnote or endnote separator opens as the same shape kind as it does
/// in the body, instead of failing the whole document. (The test name dates from when the body
/// opened this shape as a rectangle.)
/// A hyperlinked nested group in a footnote or endnote separator is flattened through the block
/// mapping just as it is in the document body.
#[test]
fn a_frame_shape_in_a_note_separator_reads_as_a_rectangle() {
let frame = r#"<w:r><w:drawing><wp:inline><wp:extent cx="508000" cy="381000"/><wp:docPr id="1" name="F"/><a:graphic><a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"><wps:wsp><wps:spPr><a:prstGeom prst="frame"/></wps:spPr><wps:bodyPr/></wps:wsp></a:graphicData></a:graphic></wp:inline></w:drawing></w:r>"#;
fn linked_nested_group_in_a_note_separator_is_flattened() {
let inner = r#"<wpg:grpSp><wpg:cNvPr id="3" name="Inner"><a:hlinkClick r:id="rId9"/></wpg:cNvPr><wpg:cNvGrpSpPr/><wpg:grpSpPr><a:xfrm><a:off x="635000" y="0"/><a:ext cx="635000" cy="635000"/><a:chOff x="0" y="0"/><a:chExt cx="635000" cy="635000"/></a:xfrm></wpg:grpSpPr><wps:wsp><wps:cNvPr id="4" name="Frame"/><wps:cNvSpPr/><wps:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="635000" cy="635000"/></a:xfrm><a:prstGeom prst="frame"/></wps:spPr><wps:bodyPr/></wps:wsp></wpg:grpSp>"#;
let group = format!(
r#"<w:r><w:drawing><wp:inline><wp:extent cx="1270000" cy="635000"/><wp:docPr id="1" name="Outer"/><a:graphic><a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup"><wpg:wgp><wpg:cNvGrpSpPr/><wpg:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="1270000" cy="635000"/><a:chOff x="0" y="0"/><a:chExt cx="1270000" cy="635000"/></a:xfrm></wpg:grpSpPr>{inner}</wpg:wgp></a:graphicData></a:graphic></wp:inline></w:drawing></w:r>"#
);
let notes = |root: &str, item: &str| {
format!(r#"<w:{root} {W_NS}><w:{item} w:type="separator" w:id="-1"><w:p>{frame}<w:r><w:separator/></w:r></w:p></w:{item}></w:{root}>"#)
format!(r#"<w:{root} {W_NS}><w:{item} w:type="separator" w:id="-1"><w:p>{group}<w:r><w:separator/></w:r></w:p></w:{item}></w:{root}>"#)
};
let footnotes = notes("footnotes", "footnote");
let endnotes = notes("endnotes", "endnote");
let link_rels = rels(&[("rId9", "hyperlink", "https://example.com/")]);
let bytes = docx(
&format!("<w:p>{frame}</w:p>"),
&[("rId1", "footnotes", "footnotes.xml"), ("rId2", "endnotes", "endnotes.xml")],
&[("word/footnotes.xml", &footnotes), ("word/endnotes.xml", &endnotes)],
&format!("<w:p>{group}</w:p>"),
&[("rId1", "footnotes", "footnotes.xml"), ("rId2", "endnotes", "endnotes.xml"), ("rId9", "hyperlink", "https://example.com/")],
&[
("word/footnotes.xml", &footnotes),
("word/_rels/footnotes.xml.rels", &link_rels),
("word/endnotes.xml", &endnotes),
("word/_rels/endnotes.xml.rels", &link_rels),
],
);
let d = wordcraft_docx::read(&bytes).unwrap();
let shapes = |p: &Paragraph| -> Vec<(ShapeKind, f32)> {
p.objects.iter().filter_map(|o| if let InlineObject::Shape { kind, w, .. } = o { Some((*kind, *w)) } else { None }).collect()
let flattened = |p: &Paragraph| -> Vec<(f32, f32, ShapeKind, f32)> {
let Some(children) = p.objects.iter().find_map(|o| match o {
InlineObject::Group { children, .. } => Some(children),
_ => None,
}) else {
panic!("{:?}", p.objects);
};
children
.iter()
.map(|c| match &c.obj {
InlineObject::Shape { kind, w, .. } => (c.x, c.y, *kind, *w),
other => panic!("{other:?}"),
})
.collect()
};
let in_body = shapes(d.body[0].as_para().unwrap());
assert_eq!(in_body.len(), 1, "{in_body:?}");
assert_eq!(in_body[0].1, 40.0);
assert_eq!(in_body[0].0, ShapeKind::Frame);
let in_body = flattened(d.body[0].as_para().unwrap());
assert_eq!(in_body, [(50.0, 0.0, ShapeKind::Frame, 50.0)]);
for separators in [&d.footnote_separators, &d.endnote_separators] {
let sep = separators.separator.as_ref().unwrap()[0].as_para().unwrap();
assert_eq!(shapes(sep), in_body);
assert_eq!(flattened(sep), in_body);
}
}
+1
View File
@@ -132,6 +132,7 @@ fn every_char_prop_round_trips() {
cs: Some(true),
font_cs: Some("B Nazanin".into()),
font_ea: Some("宋体".into()),
font_ea_theme: Some(wordcraft_doc::props::ThemeFont::MinorEastAsia),
size_cs: Some(13.0),
bold_cs: Some(false),
italic_cs: Some(true),
+78
View File
@@ -93,6 +93,84 @@ fn run_and_style_snap_to_grid_and_web_hidden_survive_two_saves() {
}
}
/// Keeps run and style emphasis values intact across repeated DOCX saves.
#[test]
fn run_and_style_emphasis_marks_survive_two_saves() {
use wordcraft_doc::props::EmphasisMark;
let styles = r#"
<w:style w:type="character" w:styleId="Dot"><w:rPr><w:em w:val="dot"/></w:rPr></w:style>
<w:style w:type="character" w:styleId="Comma"><w:rPr><w:em w:val="comma"/></w:rPr></w:style>
<w:style w:type="character" w:styleId="Circle"><w:rPr><w:em w:val="circle"/></w:rPr></w:style>
<w:style w:type="character" w:styleId="UnderDot"><w:rPr><w:em w:val="underDot"/></w:rPr></w:style>
<w:style w:type="character" w:styleId="NoMark"><w:rPr><w:em w:val="none"/></w:rPr></w:style>
"#;
let body = r#"
<w:p>
<w:r><w:rPr><w:rStyle w:val="Dot"/></w:rPr><w:t>default dot</w:t></w:r>
<w:r><w:rPr><w:rStyle w:val="Comma"/></w:rPr><w:t>comma</w:t></w:r>
<w:r><w:rPr><w:rStyle w:val="Circle"/></w:rPr><w:t>circle</w:t></w:r>
<w:r><w:rPr><w:rStyle w:val="UnderDot"/></w:rPr><w:t>under dot</w:t></w:r>
<w:r><w:rPr><w:rStyle w:val="Dot"/><w:em w:val="none"/></w:rPr><w:t>explicit none</w:t></w:r>
<w:r><w:rPr><w:rStyle w:val="NoMark"/></w:rPr><w:t>style none</w:t></w:r>
<w:r><w:rPr><w:em w:val="dot"/></w:rPr><w:t>run dot</w:t></w:r>
<w:r><w:rPr><w:em w:val="comma"/></w:rPr><w:t>run comma</w:t></w:r>
<w:r><w:rPr><w:em w:val="circle"/></w:rPr><w:t>run circle</w:t></w:r>
<w:r><w:rPr><w:em w:val="underDot"/></w:rPr><w:t>run under dot</w:t></w:r>
<w:r><w:rPr><w:em w:val="none"/></w:rPr><w:t>run none</w:t></w:r>
<w:r><w:t>inherit absent</w:t></w:r>
</w:p>
"#;
let mut doc = wordcraft_docx::read(&docx(body, styles)).unwrap();
let expected_styles = [
("Dot", Some(EmphasisMark::Dot)),
("Comma", Some(EmphasisMark::Comma)),
("Circle", Some(EmphasisMark::Circle)),
("UnderDot", Some(EmphasisMark::UnderDot)),
("NoMark", Some(EmphasisMark::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),
];
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();
let style_xml = part(&out, "word/styles.xml");
for value in ["dot", "comma", "circle", "underDot", "none"] {
assert!(style_xml.contains(&format!(r#"<w:em w:val="{value}"/>"#)), "pass {pass}: {style_xml}");
}
let document_xml = part(&out, "word/document.xml");
assert!(document_xml.contains(r#"<w:em w:val="none"/>"#), "pass {pass}: {document_xml}");
assert!(document_xml.contains("default dot"));
doc = wordcraft_docx::read(&out).unwrap();
assert_state(&doc, &format!("pass {pass}"));
}
}
#[test]
fn style_paragraph_and_run_changes_keep_independent_authors() {
let styles = r#"
+109 -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);
@@ -580,11 +581,65 @@ pub fn now_unix() -> u64 {
}
}
/// ISO-8601 timestamp (UTC, seconds).
/// ISO-8601 timestamp (UTC, seconds): the clock, for an event that happened now -- a comment, a
/// tracked change, a version. Not for what a saved or exported file records: see [`saved_iso`].
pub fn now_iso() -> String {
iso_from_unix_secs(now_unix())
}
/// The timestamp a saved or exported file records (its created and modified properties):
/// `SOURCE_DATE_EPOCH` when it holds a non-negative whole number of seconds, else the clock. With
/// it set, separate conversions of unchanged input can produce the same bytes. Repeated saves
/// of one session still advance the document revision
/// (<https://reproducible-builds.org/specs/source-date-epoch/>).
///
/// The clock stays in [`now_iso`]: an editing event's time is not the file's, and pinning it would
/// misdate comments and tracked changes.
///
/// A value that is set but not one of those is ignored with a warning, so a build that meant to
/// pin its dates hears that it did not.
pub fn saved_iso() -> String {
let raw = std::env::var("SOURCE_DATE_EPOCH").ok();
if let Some(problem) = epoch_problem(raw.as_deref()) {
log::warn!("{problem}");
}
iso_from_unix_secs(pinned_or(|_| raw.clone(), now_unix))
}
/// Why `SOURCE_DATE_EPOCH` is set and still not used, for a caller with no logger to say so (the
/// command line). `None` when it is unset, empty, or a value [`saved_iso`] takes.
pub fn source_date_epoch_problem() -> Option<String> {
epoch_problem(std::env::var("SOURCE_DATE_EPOCH").ok().as_deref())
}
/// An empty value counts as unset, as a CI file's `SOURCE_DATE_EPOCH=` with nothing after it
/// means; anything else that does not pin a date is worth a warning.
fn epoch_problem(value: Option<&str>) -> Option<String> {
let v = value?;
if v.trim().is_empty() || pinned(v).is_some() {
return None;
}
Some(format!(
"SOURCE_DATE_EPOCH={v:?} is not a whole number of seconds from 1970 to 9999-12-31, so saved and exported files take the clock's date"
))
}
/// The seconds a `SOURCE_DATE_EPOCH` value pins, if it pins any.
fn pinned(v: &str) -> Option<u64> {
v.trim().parse::<u64>().ok().filter(|secs| *secs <= LAST_DATE)
}
/// [`saved_iso`]'s choice, with the environment and the clock given so a test can show which wins.
pub(crate) fn pinned_or(get: impl Fn(&str) -> Option<String>, clock: impl Fn() -> u64) -> u64 {
get("SOURCE_DATE_EPOCH").as_deref().and_then(pinned).unwrap_or_else(clock)
}
/// The last date a document can record, as Unix seconds: 9999-12-31T23:59:59Z. A year runs to
/// four digits in `xsd:dateTime`, which is what a .docx core property holds, so a value past this
/// would be written as something no reader accepts -- `292277026596-12-04T15:30:07Z` for
/// `i64::MAX`. Such a value is left to the clock, as a malformed one is.
const LAST_DATE: u64 = 253_402_300_799;
/// The local time zone's offset from UTC in seconds (east positive) at `unix`, daylight saving
/// included: the system's zone, or the browser's on the web. 0 (UTC) when it can't be found.
pub fn local_offset_secs(unix: u64) -> i64 {
@@ -735,3 +790,56 @@ mod iso_tests {
let _ = (civil_from_days(i64::MAX), civil_from_days(i64::MIN));
}
}
#[cfg(test)]
mod saved_time_tests {
use super::{epoch_problem, iso_from_unix_secs, pinned_or};
/// What a saved or exported file records: `SOURCE_DATE_EPOCH` when it holds a non-negative
/// whole number of seconds, the clock whenever it does not. The environment and the clock are
/// given here rather than set, so no test changes this process's environment -- that is
/// `unsafe` under edition 2024 and would reach every test beside it.
#[test]
fn a_pinned_epoch_is_preferred_and_the_clock_answers_otherwise() {
let env = |v: Option<&'static str>| move |_: &str| v.map(str::to_owned);
let clock = || 1_000_000;
assert_eq!(pinned_or(env(Some("1791208980")), clock), 1_791_208_980, "the variable wins");
assert_eq!(pinned_or(env(Some("0")), clock), 0, "the epoch itself counts");
assert_eq!(pinned_or(env(Some(" 1791208980 ")), clock), 1_791_208_980, "spaces around it are allowed");
// The last date a document can write is honoured; past it the year would not fit
// `xsd:dateTime` and the clock answers instead.
assert_eq!(pinned_or(env(Some("253402300799")), clock), 253_402_300_799);
assert_eq!(iso_from_unix_secs(253_402_300_799), "9999-12-31T23:59:59Z");
for ignored in [
None,
Some(""),
Some(" "),
Some("-1"),
Some("later"),
Some("1791208980.5"),
Some("99999999999999999999"),
Some("253402300800"),
Some("9223372036854775807"),
] {
assert_eq!(pinned_or(env(ignored), clock), 1_000_000, "{ignored:?} leaves it to the clock");
}
// Only that variable is read.
assert_eq!(pinned_or(|name: &str| (name == "TZ").then(|| "1791208980".to_owned()), clock), 1_000_000);
// And it reaches the stamp as that instant, not as something near it.
assert_eq!(iso_from_unix_secs(pinned_or(env(Some("1791208980")), clock)), "2026-10-05T14:03:00Z");
}
/// A value that is set and still ignored is reported, so a build that meant to pin its dates
/// hears that it did not (noted in review). Unset and empty say nothing: an empty value is
/// how a CI file leaves the variable off.
#[test]
fn a_set_but_unusable_epoch_is_reported_and_nothing_else_is() {
for quiet in [None, Some(""), Some(" "), Some("0"), Some("1791208980"), Some(" 1791208980 "), Some("253402300799")] {
assert_eq!(epoch_problem(quiet), None, "{quiet:?}");
}
for loud in ["later", "-1", "1791208980.5", "1e9", "253402300800", "99999999999999999999"] {
let problem = epoch_problem(Some(loud)).unwrap_or_else(|| panic!("{loud:?} should be reported"));
assert!(problem.contains(&format!("{loud:?}")) && problem.contains("clock"), "{problem}");
}
}
}
+225 -44
View File
@@ -2,8 +2,9 @@
use serde_json::Value;
use wordcraft_doc::math_edit::MathPos;
use wordcraft_doc::para::OBJ;
use wordcraft_doc::{InlineObject, Pos, StoryRef};
use wordcraft_doc::para::{NBSP, OBJ};
use wordcraft_doc::props::TextDirection;
use wordcraft_doc::{InlineObject, Paragraph, Path, Pos, StoryRef};
use wordcraft_layout::ViewMode;
use super::{parse_pos, sel_result};
@@ -53,7 +54,10 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("caret.set", "Set Caret", "Navigation", set)
.params(r#"{"pos": Pos, "extend"?: bool} | {"page": n, "x": pt, "y": pt}"#)
.pure(),
CommandSpec::new("select.all", "Select All", "Home › Editing › Select", select_all).key("Mod+A").pure(),
CommandSpec::new("select.all", "Select All", "Home › Editing › Select", select_all)
.key("Mod+A")
.params(r#"{"whole"?: bool (default true: select the whole story; false: grow through the cell, row and table first)}"#)
.pure(),
CommandSpec::new("select.range", "Select Range", "Navigation", select_range).params(r#"{"anchor": Pos, "focus": Pos}"#).pure(),
CommandSpec::new("select.word", "Select Word", "Navigation", select_word).pure(),
CommandSpec::new("select.sentence", "Select Sentence", "Navigation", select_sentence).pure(),
@@ -110,7 +114,49 @@ fn bidi_para(s: &Session) -> bool {
/// Left/Right: with a selection and no Shift, collapse to its edge.
fn lr(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
if !extend(v) && !s.sel.is_collapsed() {
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();
// The left edge of a selection in right-to-left text is its logical end.
let to_start = is_left != rtl_para(s);
@@ -121,26 +167,33 @@ fn lr(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
if bidi_para(s) {
return visual_lr(s, v, is_left);
}
if !extend(v)
let from = s.sel.focus.clone();
// Equation entry and the grapheme step start at the same visible edge.
let hidden = s.layout_hides_deleted(from.story);
let edge = logical_edge(s, &from, is_left, hidden);
if !ext
&& !s.math_left
&& let Some(r) = into_equation(s, is_left)
&& let Some(r) = into_equation(s, &from, edge, is_left, hidden)
{
return r;
}
mv(s, v, if is_left { left } else { right })
s.goal_x = None;
let to = step_from_edge(s, &from, edge, is_left);
apply(s, to, ext);
sel_result(s)
}
/// Left/Right onto an equation opens it, at its end from the right and at its start from the
/// left, as in Word (#4138). Leaving it puts the caret on the far side, so the same arrow then
/// moves on instead of going back in. A caret.left/right that itself left an equation (sent
/// while editing one) moves on too.
fn into_equation(s: &mut Session, is_left: bool) -> Option<CmdResult> {
let f = s.sel.focus.clone();
let off = if is_left { f.off.checked_sub(OBJ.len_utf8())? } else { f.off };
if !matches!(s.doc.para_at(&f)?.object_at(off), Some(InlineObject::Equation { .. })) {
fn into_equation(s: &mut Session, from: &Pos, edge: usize, is_left: bool, hidden: wordcraft_layout::HideDeleted) -> Option<CmdResult> {
let off = if is_left { edge.checked_sub(OBJ.len_utf8())? } else { edge };
let para = s.doc.para_at(from)?;
if !matches!(para.object_at(off), Some(InlineObject::Equation { .. })) || (hidden.any() && hidden.hides(&s.doc, para.props_of_char(off).del)) {
return None;
}
s.sel = Selection::caret(Pos { off, ..f });
s.sel = Selection::caret(Pos { off, ..from.clone() });
s.goal_x = None;
s.pending = None;
Some(super::equation::edit_at(s, (!is_left).then(MathPos::default)))
@@ -159,63 +212,187 @@ fn visual_lr(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
Some(wordcraft_layout::VisualStep::Edge { start, stop, last_line, rtl }) => {
let at = |off| Pos { off, ..from.clone() };
if is_left != rtl {
match s.doc.para_at(&from) {
Some(para) if start > 0 => at(para.prev_boundary(start)),
_ => left(s, &at(0)),
}
logical_step(s, &at(start), true)
} else if !last_line {
at(stop)
} else {
let len = s.doc.para_at(&from).map_or(stop, |p| p.len());
right(s, &at(len))
logical_step(s, &at(len), false)
}
}
None if is_left => left(s, &from),
None => right(s, &from),
None => logical_step(s, &from, is_left),
};
apply(s, to, ext);
sel_result(s)
}
fn left(s: &mut Session, p: &Pos) -> Pos {
if let Some(para) = s.doc.para_at(p)
&& p.off > 0
{
return Pos { off: para.prev_boundary(p.off), ..p.clone() };
/// Find the run containing `byte` from the nearer end of `para`.
fn run_at_byte(para: &Paragraph, byte: usize) -> Option<(usize, std::ops::Range<usize>)> {
if byte >= para.len() {
return None;
}
match s.doc.prev_para(p.story, &p.path) {
Some(q) => {
let off = s.doc.para(p.story, &q).map(|x| x.len()).unwrap_or(0);
Pos { story: p.story, path: q, off }
}
None => p.clone(),
if byte < para.len() / 2 {
para.run_ranges().enumerate().find_map(|(i, (range, _))| range.contains(&byte).then_some((i, range)))
} else {
let mut end = para.len();
para.runs.iter().enumerate().rev().find_map(|(i, run)| {
let start = end.saturating_sub(run.len);
let range = start..end;
end = start;
range.contains(&byte).then_some((i, range))
})
}
}
fn right(s: &mut Session, p: &Pos) -> Pos {
if let Some(para) = s.doc.para_at(p)
&& p.off < para.len()
/// The two ends of a hidden deletion share a caret position. Cross the hidden
/// span before taking the normal grapheme step, including adjacent deletions.
fn hidden_deletion_edge(para: &Paragraph, off: usize, is_left: bool, hides: impl Fn(Option<u32>) -> bool) -> usize {
// At a run boundary, inspect the byte on the side the caret is moving toward.
let Some(byte) = off.checked_sub(usize::from(is_left)) else { return off };
let Some((i, range)) = run_at_byte(para, byte) else { return off };
if !hides(para.runs[i].props.del) {
return off;
}
if is_left {
range.start - para.runs[..i].iter().rev().take_while(|run| hides(run.props.del)).map(|run| run.len).sum::<usize>()
} else {
range.end + para.runs[i + 1..].iter().take_while(|run| hides(run.props.del)).map(|run| run.len).sum::<usize>()
}
}
fn logical_edge(s: &Session, from: &Pos, is_left: bool, hidden: wordcraft_layout::HideDeleted) -> usize {
if hidden.any()
&& let Some(para) = s.doc.para_at(from)
{
return Pos { off: para.next_boundary(p.off), ..p.clone() };
return hidden_deletion_edge(para, from.off, is_left, |del| hidden.hides(&s.doc, del));
}
match s.doc.next_para(p.story, &p.path) {
Some(q) => Pos { story: p.story, path: q, off: 0 },
None => p.clone(),
from.off
}
fn logical_step(s: &Session, from: &Pos, is_left: bool) -> Pos {
let edge = logical_edge(s, from, is_left, s.layout_hides_deleted(from.story));
step_from_edge(s, from, edge, is_left)
}
fn step_from_edge(s: &Session, from: &Pos, edge: usize, is_left: bool) -> Pos {
if let Some(para) = s.doc.para_at(from) {
if is_left && edge > 0 {
return Pos { off: para.prev_boundary(edge), ..from.clone() };
}
if !is_left && edge < para.len() {
return Pos { off: para.next_boundary(edge), ..from.clone() };
}
}
step_to_neighbor(s, from, is_left, !s.view.show_markup)
}
fn step_to_neighbor(s: &Session, from: &Pos, is_left: bool, skip_deleted: bool) -> Pos {
let story = from.story;
let neighbor = if is_left { s.doc.prev_para(story, &from.path) } else { s.doc.next_para(story, &from.path) };
let Some(mut path) = neighbor else { return from.clone() };
// Layout collapses a wholly deleted paragraph in No Markup. A surviving mark still gives
// even a paragraph without visible text a caret stop.
let deleted = |path: &Path| s.doc.para(story, path).is_some_and(|p| p.mark.del.is_some() && p.runs.iter().all(|r| r.props.del.is_some()));
if skip_deleted && deleted(&path) {
// Get the story's paths once for the rest of the walk, even across many deleted paragraphs.
let paths = s.doc.para_paths(story);
let Ok(i) = paths.binary_search(&path) else { return from.clone() };
let stop = if is_left { paths[..i].iter().rev().find(|p| !deleted(p)) } else { paths[i + 1..].iter().find(|p| !deleted(p)) };
let Some(stop) = stop else { return from.clone() };
path = stop.clone();
}
let off = if is_left { s.doc.para(story, &path).map_or(0, Paragraph::len) } else { 0 };
Pos { story, path, off }
}
fn visible_word_start(para: &Paragraph, off: usize) -> Option<usize> {
let off = para.clamp(off);
let byte = off.checked_sub(1)?;
let (i, range) = run_at_byte(para, byte)?;
let mut idx = off;
let mut seen_word = false;
let mut seen_visible = false;
let mut end = range.end;
for run in para.runs[..=i].iter().rev() {
let start = end.saturating_sub(run.len);
let range_end = end.min(off);
end = start;
if run.props.del.is_some() {
continue;
}
let Some(slice) = para.text.get(start..range_end) else { continue };
for (rel, c) in slice.char_indices().rev() {
seen_visible = true;
if wordcraft_doc::bidi::is_word_char(c) {
seen_word = true;
idx = start + rel;
} else if seen_word {
return Some(idx);
} else {
idx = start + rel;
}
}
}
seen_visible.then_some(idx)
}
fn visible_word_end(para: &Paragraph, off: usize) -> Option<usize> {
let off = para.clamp(off);
let (i, range) = run_at_byte(para, off)?;
let mut first_word = None;
let mut in_space = false;
let mut last_end = None;
let mut run_start = range.start;
for run in &para.runs[i..] {
let run_end = run_start.saturating_add(run.len);
let start = run_start.max(off);
run_start = run_end;
if run.props.del.is_some() {
continue;
}
let Some(slice) = para.text.get(start..run_end) else { continue };
for (rel, c) in slice.char_indices() {
let abs = start + rel;
last_end = Some(abs + c.len_utf8());
let is_first = first_word.is_none();
let fw = *first_word.get_or_insert_with(|| wordcraft_doc::bidi::is_word_char(c) && c != '\'');
let w = wordcraft_doc::bidi::is_word_char(c);
if c == ' ' || c == NBSP {
in_space = true;
continue;
}
if in_space || (fw && !w) || (!fw && !is_first) {
return Some(abs);
}
}
}
last_end
}
fn word_left(s: &mut Session, p: &Pos) -> Pos {
match s.doc.para_at(p) {
Some(para) if p.off > 0 => Pos { off: para.word_start(p.off), ..p.clone() },
_ => left(s, p),
if let Some(para) = s.doc.para_at(p) {
if !s.view.show_markup {
if let Some(off) = visible_word_start(para, p.off) {
return Pos { off, ..p.clone() };
}
} else if p.off > 0 {
return Pos { off: para.word_start(p.off), ..p.clone() };
}
}
step_to_neighbor(s, p, true, false)
}
fn word_right(s: &mut Session, p: &Pos) -> Pos {
match s.doc.para_at(p) {
Some(para) if p.off < para.len() => Pos { off: para.word_end(p.off), ..p.clone() },
_ => right(s, p),
if let Some(para) = s.doc.para_at(p) {
if !s.view.show_markup {
if let Some(off) = visible_word_end(para, p.off) {
return Pos { off, ..p.clone() };
}
} else if p.off < para.len() {
return Pos { off: para.word_end(p.off), ..p.clone() };
}
}
step_to_neighbor(s, p, false, false)
}
fn para_up(s: &mut Session, p: &Pos) -> Pos {
@@ -239,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();
@@ -345,7 +526,7 @@ fn select_all(s: &mut Session, v: &Value) -> CmdResult {
s.column_mode = false;
return sel_result(s);
}
if !p::bool(v, "whole").unwrap_or(false)
if !p::bool(v, "whole").unwrap_or(true)
&& let Some(r) = super::table::grow_select_all(s)
{
return r;
+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.
+7
View File
@@ -521,6 +521,13 @@ fn place(s: &mut Session, layout: &DocLayout, obj: InlineObject, page: usize, (x
float.y = y - origin.y;
}
para.touch();
if !on_page && let Some(offset) = super::objects::shifted_float_offset(s, &at, page, y, origin.y) {
super::objects::edit_obj(s, &at, |o| {
if let Some(float) = o.float_mut() {
float.y = offset;
}
})?;
}
Ok(at)
}
+39 -10
View File
@@ -161,7 +161,7 @@ pub fn specs() -> Vec<CommandSpec> {
.params(r#"{"tab"?: "find|replace|goto" (default replace)}"#)
.pure(),
CommandSpec::new("edit.replaceAll", "Replace All", "Home › Editing › Replace", replace_all)
.params(r#"{"text": string, "with": string (^p ^t ^& ^c …; \\1 with wildcards; with regex also $1 ${n} ${name} $0 $$ \\1 \\n (paragraph mark) \\t), …options of edit.find} (with AutoFormat's smart quotes on, a " or ' typed in `with` goes in curly by the character before it, as typing does, except with regex or special: false (taken as written); ^034 and ^039 stay straight; a match that already reads so, curled the same kind, is left and not counted)"#),
.params(r#"{"text": string, "with": string (^p ^t ^& ^c …; \\1 with wildcards; with regex also $1 ${n} ${name} $0 $$ \\1 \\n (paragraph mark) \\t), …options of edit.find} (with AutoFormat's smart quotes on, a " or ' typed in `with` goes in curly by the character before it, as typing does, except with regex or special: false (taken as written); ^034 and ^039 stay straight; a match that already reads so, curled the same kind, is left and not counted); replaces in the main text, headers, footers, footnotes, endnotes and text boxes, wherever the caret is"#),
CommandSpec::new("edit.goto", "Go To", "Home › Editing › Find", goto)
.key("Mod+Alt+G / F5")
.params(r#"{"page"?: n, "pageBy"?: int (pages forward, negative back, from the caret's page), "bookmark"?: string (selects its text), "paragraph"?: n}; none opens Find and Replace on its Go To tab"#)
@@ -827,16 +827,46 @@ fn replace(s: &mut Session, v: &Value) -> CmdResult {
Ok(json!({"replaced": replaced, "remaining": search(s, story)?.len(), "selected": selected}))
}
/// Every match replaced, last first so earlier positions stay valid (one undo step). A `\r` in
/// the replacement (`^p`) splits the paragraph.
/// 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> {
s.doc.shown_stories()
}
/// Every match in every story replaced (wherever the caret is), last first so earlier positions
/// stay valid (one undo step). A `\r` in the replacement (`^p`) splits the paragraph. Locked
/// content in any story stops it before anything changes.
fn replace_all(s: &mut Session, v: &Value) -> CmdResult {
need_query(s, v)?;
read_opts(s, v);
let story = s.sel.focus.story;
// Matches already curled as the replacement would curl them are left and not counted (#7307).
let results: Vec<Found> = search_matches(s, story, true, true)?.into_iter().filter(|f| !f.keep).collect();
let n = results.len();
super::controls::check_deletions(s, story, results.iter().map(|f| (&f.a, &f.b)))?;
let mut found = Vec::new();
// A protected document only lets the editable regions change: matches elsewhere (in a header,
// say) stay as they are, so they don't make the whole command fail.
let editable = super::protect::editable_ranges(s);
for story in replace_stories(s) {
// Matches already curled as the replacement would curl them are left and not counted (#7307).
let mut results: Vec<Found> = search_matches(s, story, true, true)?.into_iter().filter(|f| !f.keep).collect();
if let Some(ranges) = &editable {
results.retain(|f| ranges.iter().any(|(from, to)| f.a.story == from.story && f.a >= *from && f.b <= *to));
}
if results.is_empty() {
continue;
}
super::controls::check_deletions(s, story, results.iter().map(|f| (&f.a, &f.b)))?;
found.push(results);
}
let n: usize = found.iter().map(Vec::len).sum();
// The main text comes last, so under Track Changes the caret ends where it did before.
for results in found.into_iter().rev() {
replace_found(s, results)?;
}
s.status = format!("All done. We made {n} replacements.");
Ok(json!({"replaced": n}))
}
/// Replace the matches of one story, last first.
fn replace_found(s: &mut Session, results: Vec<Found>) -> Result<(), CmdError> {
for Found { a, b, rep, .. } in results.into_iter().rev() {
let with = rep.unwrap_or_default();
if s.doc.settings.track_changes {
@@ -857,8 +887,7 @@ fn replace_all(s: &mut Session, v: &Value) -> CmdResult {
}
}
}
s.status = format!("All done. We made {n} replacements.");
Ok(json!({"replaced": n}))
Ok(())
}
fn goto(s: &mut Session, v: &Value) -> CmdResult {
+1 -1
View File
@@ -145,7 +145,7 @@ pub fn specs() -> Vec<CommandSpec> {
sel_result(s)
})
.key("Mod+W / Mod+F4")
.params(r#"{"force"?: bool (desktop app's control channel and MCP bridge only: without it a document with unsaved changes is an error and stays open; with it the changes are discarded. Headless sessions never ask; file.closeDocument closes a document there)}"#)
.params(r#"{"save"?: bool (desktop app's control channel and MCP bridge only: save the shown document, then close it; it does not apply to a background `doc`, which needs force or its own save first), "force"?: bool (desktop app's control channel and MCP bridge only: without save or force a document with unsaved changes is an error and stays open; with force the changes are discarded. Headless sessions never ask; file.closeDocument closes a document there)}"#)
.pure(),
CommandSpec::new("file.closeDocument", "Close Document", "Agents", close_document)
.params(r#"{"id"?: n (an open document, see view.switchWindows; default the active one), "force"?: bool (discard unsaved changes; without it a document with unsaved changes is an error and stays open)} → {"closed": id, "active": id, "documents": [{"id", "title", "path", "dirty", "active"}]}; closing the last document leaves a new blank one"#)
+23 -5
View File
@@ -1,12 +1,13 @@
//! Character formatting (Home › Font).
use std::collections::HashMap;
use std::sync::{Arc, PoisonError};
use serde_json::{Value, json};
use wordcraft_doc::eq::{EncloseShape, EncloseStyle, Enclosure};
use wordcraft_doc::props::{Border, CharProps, Highlight, Rgb, TextColor, Underline, VertAlign};
use wordcraft_doc::resolve::ResolvedChar;
use wordcraft_doc::{InlineObject, PartKind, Pos, RevisionKind, StoryRef};
use wordcraft_doc::{Document, InlineObject, PartKind, Pos, RevisionKind, StoryRef};
use super::sel_result;
use super::tools::{is_turkic, lower_char, upper_char};
@@ -352,11 +353,14 @@ fn resolved(s: &Session) -> Vec<ResolvedChar> {
out
}
/// Whether a toggle without a `value` turns its format on. A selection follows its first character
/// in document order, as Word does: one that starts formatted loses the format, all of it (#6516).
/// Whether a toggle without a `value` turns its format on. A selection (including a selected
/// text box or a non-empty column block, whose `sel` is non-collapsed) follows its first
/// character in document order, as Word does: one that starts formatted loses the format, all of
/// it (#6516). A collapsed caret (including an empty column block) requires the whole word to
/// carry the format before toggling it off.
fn turns_on(s: &Session, has: impl Fn(&ResolvedChar) -> bool) -> bool {
let chars = resolved(s);
if !s.sel.is_collapsed() || selected_text_box(s).is_some() || column_rows(s).is_some() {
if !s.sel.is_collapsed() {
return !chars.first().is_some_and(has);
}
!chars.iter().all(has)
@@ -424,6 +428,7 @@ fn font(s: &mut Session, v: &Value) -> CmdResult {
}
if let Some(n) = &ea {
c.font_ea = Some(n.clone());
c.font_ea_theme = None;
}
})
}
@@ -951,6 +956,19 @@ pub fn state(s: &Session) -> Value {
(*cached_state(s)).clone()
}
/// The common East Asian family shown by the font controls. If a slot has no face, keep
/// showing the named font. Resolve each theme slot once even for a selection with many runs.
fn selection_east_asian_font<'a>(doc: &'a Document, runs: &'a [ResolvedChar]) -> Option<&'a str> {
let mut themes = HashMap::new();
let mut fonts = runs.iter().map(|run| {
run.font_ea_theme
.and_then(|slot| *themes.entry(slot).or_insert_with(|| wordcraft_layout::para::east_asian_font(doc, run)))
.or(run.font_ea.as_deref())
});
let first = fonts.next().flatten()?;
fonts.all(|font| font == Some(first)).then_some(first)
}
fn compute_state(s: &Session) -> Value {
let all = resolved(s);
let first = all.first().cloned();
@@ -971,7 +989,7 @@ fn compute_state(s: &Session) -> Value {
json!({
"font": font,
"fontShownAs": shown_as,
"fontEastAsia": same(&|r| json!(r.font_ea)),
"fontEastAsia": selection_east_asian_font(&s.doc, &all),
"size": same(&|r| json!(r.size)),
"bold": all.iter().all(shown_bold),
"italic": all.iter().all(shown_italic),
+3 -3
View File
@@ -16,8 +16,8 @@ mod objects;
pub(crate) use header_footer::saved_copy;
use header_footer::{create_hf, edit_hf, header_footer, new_empty_headers, strip_headers};
pub use items::{
DropCapState, default_date_picture, drop_cap_state, format_date, format_date_at, format_date_at_in, format_date_in, format_date_parts,
format_date_parts_in,
DropCapState, default_date_picture, default_time_picture, drop_cap_state, format_date, format_date_at, format_date_at_in, format_date_in,
format_date_parts, format_date_parts_in,
};
use items::{cover_page, date_time, drop_cap, drop_cap_off, field, page_number, symbol};
use links::{bookmark, delete_bookmark, link, link_targets};
@@ -56,7 +56,7 @@ pub fn specs() -> Vec<CommandSpec> {
.then_some("text boxes can't go inside a text box")
}),
CommandSpec::new("insert.link", "Link", "Insert › Links", link).key("Mod+K").params(
r#"{"url": string} | {"bookmark": name} | {"heading": block (see link.targets)} | {"top": true}, "text"?: string (Place in This Document: a bookmark, a heading or the top of the document)"#,
r#"{"url": string} | {"bookmark": name} | {"heading": block (see link.targets)} | {"top": true}, "text"?: string (Place in This Document: a bookmark, a heading or the top of the document); for every target, the result has a "warning" when a selection keeps its own text instead of "text""#,
),
CommandSpec::new("link.targets", "Link", "Insert › Links", link_targets).pure(),
CommandSpec::new("insert.removeLink", "Remove Hyperlink", "Insert › Links", |s, _| super::format::apply(s, &|c| {
+34
View File
@@ -218,6 +218,8 @@ struct DateNames {
days_short: [&'static str; 7],
/// The picture of a `DATE` field without `\@`.
default: &'static str,
/// The picture of a `TIME` field without `\@`.
default_time: &'static str,
}
const ENGLISH: DateNames = DateNames {
@@ -226,6 +228,7 @@ const ENGLISH: DateNames = DateNames {
days: ["Thursday", "Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday"],
days_short: ["Thu", "Fri", "Sat", "Sun", "Mon", "Tue", "Wed"],
default: "M/d/yyyy",
default_time: "h:mm am/pm",
};
/// Portuguese (observed in Word for Mac with a pt-BR document): lower-case names, `MMM` = `out`,
@@ -236,6 +239,7 @@ const PORTUGUESE: DateNames = DateNames {
days: ["quinta-feira", "sexta-feira", "sábado", "domingo", "segunda-feira", "terça-feira", "quarta-feira"],
days_short: ["qui", "sex", "sáb", "dom", "seg", "ter", "qua"],
default: "dd/MM/yyyy",
default_time: "h:mm am/pm",
};
/// German (Word's Windows NLS forms): `MMMM` = `März`, `MMM` = `Mrz`, `ddd` = `Fr` (two
@@ -246,6 +250,7 @@ const GERMAN: DateNames = DateNames {
days: ["Donnerstag", "Freitag", "Samstag", "Sonntag", "Montag", "Dienstag", "Mittwoch"],
days_short: ["Do", "Fr", "Sa", "So", "Mo", "Di", "Mi"],
default: "dd.MM.yyyy",
default_time: "HH:mm",
};
/// Austrian Standard German: January is `Jänner`, abbreviated `Jän` (Österreichisches
@@ -256,6 +261,7 @@ const GERMAN_AUSTRIA: DateNames = DateNames {
days: ["Donnerstag", "Freitag", "Samstag", "Sonntag", "Montag", "Dienstag", "Mittwoch"],
days_short: ["Do", "Fr", "Sa", "So", "Mo", "Di", "Mi"],
default: "dd.MM.yyyy",
default_time: "HH:mm",
};
/// Choose month and weekday names from the language tag: the primary subtag picks the language,
@@ -279,6 +285,12 @@ pub fn default_date_picture(lang: Option<&str>) -> &'static str {
date_names(lang).default
}
/// The picture Word gives a `TIME` field that has no `\@` switch, in the field's language: German
/// shows the 24-hour clock (#8562).
pub fn default_time_picture(lang: Option<&str>) -> &'static str {
date_names(lang).default_time
}
/// Format a date and time with a Word picture; `days_since` (days since 1970-01-01) gives the weekday.
pub fn format_date_parts(fmt: &str, y: i64, m: usize, d: u32, hms: (u32, u32, u32), days_since: i64) -> String {
format_date_parts_in(fmt, None, y, m, d, hms, days_since)
@@ -622,6 +634,28 @@ mod date_time_locale_tests {
assert_eq!(default_date_picture(Some("de-CH")), "dd.MM.yyyy");
}
/// A `TIME` field without `\@` shows the 24-hour clock in a German document and the 12-hour
/// clock in an English one (#8562).
#[test]
fn bare_time_field_follows_the_document_language() {
let refreshed = |lang: &str| {
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("review.language", &json!({"lang": lang, "default": true})).unwrap();
s.run("insert.field", &json!({"instr": "TIME", "result": "stale"})).unwrap();
crate::cmd::references::refresh_date_fields(&mut s.doc);
let path = s.doc.para_paths(StoryRef::Body).remove(0);
let p = s.doc.para(StoryRef::Body, &path).unwrap();
let result = p.objects.iter().find_map(|o| if let InlineObject::Field { result, .. } = o { Some(result.clone()) } else { None });
result.expect("a TIME field")
};
for lang in ["de-DE", "de-AT", "de-CH"] {
let time = refreshed(lang);
assert!(time != "stale" && !time.contains("AM") && !time.contains("PM"), "{lang}: {time}");
}
let time = refreshed("en-US");
assert!(time.contains("AM") || time.contains("PM"), "en-US: {time}");
}
/// Windows NLS short forms: two-letter weekdays (`Mo`, `Di`…) and `Mrz` for March, with no
/// trailing full stop (#7146).
#[test]
+10
View File
@@ -75,11 +75,21 @@ pub(super) fn link(s: &mut Session, v: &Value) -> CmdResult {
s.sel = Selection::caret(end);
s.pending = Some(CharProps::default());
} else {
// A Text to display that differs from the selection but can't retype it is not applied:
// the caller is told so rather than left to think it was (#8541).
let kept = p::str(v, "text").is_some_and(|t| !t.is_empty() && one_line_selection(s) != Some(t) && s.selected_text() != t);
let (a, b) = s.sel.ordered();
s.doc.format_range(&a, &b, &|c| {
c.link = Some(url.clone());
c.style = style.clone();
})?;
if kept {
const KEPT: &str = "Text to display was not applied: the selection is linked with its own text.";
s.status = KEPT.into();
let mut out = sel_result(s)?;
out["warning"] = json!(KEPT);
return Ok(out);
}
}
sel_result(s)
}
+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
View File
@@ -908,4 +908,29 @@ mod tests {
let spec = s.registry.get(TEXT).unwrap();
assert!(spec.mutates, "view.markdownSourceText mutates session and dirty state");
}
/// Verifies entering and applying Markdown Source keep the document intact and report errors
/// when Markdown conversion fails.
#[test]
fn failed_markdown_conversion_keeps_document_and_reports_error() {
let mut s = session(SAMPLE);
s.md_file = FileText::default();
let err = wordcraft_formats::with_shared_conversion_error("bridge failed", || s.run(TOGGLE, &json!({}))).unwrap_err();
assert!(err.to_string().contains("bridge failed"), "{err}");
assert!(s.md_source.is_none());
for skip in [1, 2] {
let err = wordcraft_formats::with_shared_conversion_error_after(skip, "bridge failed", || s.run(TOGGLE, &json!({}))).unwrap_err();
assert!(err.to_string().contains("bridge failed"), "skip={skip}: {err}");
assert!(s.md_source.is_none());
}
let mut s = session(SAMPLE);
s.run(TOGGLE, &json!({})).unwrap();
let before = body_text(&s);
set_text(&mut s, "# Replaced\n");
wordcraft_formats::with_shared_conversion_error("bridge failed", || apply(&mut s));
assert_eq!(body_text(&s), before, "failed apply leaves the document intact");
assert!(s.status.contains("bridge failed"), "{}", s.status);
}
}
+1 -1
View File
@@ -21,7 +21,7 @@ mod shape;
mod specs;
pub use arrange::moves_with_text;
pub(crate) use arrange::{anchor_paragraph, nearest_line};
pub(crate) use arrange::{anchor_paragraph, nearest_line, shifted_float_offset};
#[cfg(test)]
use group::ungroup;
pub use picture::{OriginalSize, PictureLook, cropped_original_size, fit_size, original_size};
+30 -1
View File
@@ -212,9 +212,29 @@ fn move_object_once(s: &mut Session, pos: &Pos, page: usize, x: f32, y: f32, (w,
f.x = (x - origin.x).clamp(-MAX_OFFSET, MAX_OFFSET);
f.y = (y - origin.y).clamp(-MAX_OFFSET, MAX_OFFSET);
})?;
if let Some(offset) = shifted_float_offset(s, &at, page, y, origin.y) {
edit_float(s, &at, |f| f.y = offset.clamp(-MAX_OFFSET, MAX_OFFSET))?;
}
Ok(at)
}
/// A page-to-paragraph conversion can make a float move from the unpushed paragraph top to
/// the pushed first line. Once layout has resolved that choice, offset from the origin it used.
/// Leave other layout effects, such as wrapping settlement or a change of page, to the caller.
pub(crate) fn shifted_float_offset(s: &mut Session, at: &Pos, page: usize, y: f32, old_origin: f32) -> Option<f32> {
let offset = y - old_origin;
if offset >= 0.0
|| at.story != StoryRef::Body
|| at.path.depth() != 0
|| (!s.view.read_mode && !matches!(s.view.mode, wordcraft_layout::ViewMode::Print | wordcraft_layout::ViewMode::Read))
{
return None;
}
s.touch();
let hit = s.layout().object(at, page)?;
(hit.page == page && hit.origin.y > old_origin + 0.01 && (hit.rect.y - hit.origin.y - offset).abs() < 0.01).then_some(y - hit.origin.y)
}
/// Turn the selected floating object's alignment (left, centred, …) into an offset from its
/// column / paragraph that keeps it where it is, so it can be moved by an offset.
pub(super) fn unalign(s: &mut Session) -> Result<(), CmdError> {
@@ -245,6 +265,12 @@ pub(super) fn unalign(s: &mut Session) -> Result<(), CmdError> {
f.y = oy.clamp(-MAX_OFFSET, MAX_OFFSET);
}
})?;
if float.v_align.is_some()
&& float.v_rel != Anchor::Page
&& let Some(offset) = shifted_float_offset(s, &pos, hit.page, hit.rect.y, hit.origin.y)
{
edit_float(s, &pos, |f| f.y = offset.clamp(-MAX_OFFSET, MAX_OFFSET))?;
}
Ok(())
}
@@ -268,11 +294,14 @@ pub(super) fn move_with_text(s: &mut Session, with_text: bool) -> CmdResult {
let hit = s.layout().object(&pos, s.page_hint).ok_or_else(|| CmdError::Failed("the object isn't laid out".into()))?;
// Paragraph offsets start at the paragraph's top (the hit's origin), page offsets at the page's.
let y = if with_text { hit.rect.y - hit.origin.y } else { hit.rect.y };
let o = edit_float(s, &pos, |f| {
let mut o = edit_float(s, &pos, |f| {
f.v_rel = if with_text { Anchor::Paragraph } else { Anchor::Page };
f.v_align = None;
f.y = y.clamp(-MAX_OFFSET, MAX_OFFSET);
})?;
if with_text && let Some(offset) = shifted_float_offset(s, &pos, hit.page, hit.rect.y, hit.origin.y) {
o = edit_float(s, &pos, |f| f.y = offset.clamp(-MAX_OFFSET, MAX_OFFSET))?;
}
Ok(json!({"object": serde_json::to_value(o).unwrap_or(Value::Null)}))
}
+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.
+6 -1
View File
@@ -18,6 +18,7 @@ mod styles;
mod tabs_borders;
mod tools;
pub(super) use format::drop_direct_indents;
use format::{align, asian_typography, cur, direction, line_spacing, ls, set_align, set_props, tog};
pub use format::{cur as selection_para, fmt, indent, outdent};
pub use lists::{ListButtons, list_buttons, manage_list, touch_all};
@@ -166,13 +167,17 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("para.heading3", "Heading 3", "Home › Styles", |s, _| apply_style(s, &json!({"style": "Heading3"}))).key("Mod+Alt+3"),
CommandSpec::new("para.bullets", "Bullets", "Home › Paragraph", |s, v| list(s, v, ListKind::Bullet)).params(r#"{"kind"?: "bullet" | single char, "off"?: bool}"#).key("Mod+Shift+L"),
CommandSpec::new("para.numbering", "Numbering", "Home › Paragraph", |s, v| list(s, v, ListKind::Numbered))
.params(r#"{"kind"?: "numbered|numberedParen|upperLetter|lowerLetter|lowerRoman|outline", "off"?: bool}"#),
.params(r#"{"kind"?: "numbered|numberedParen|outline|upperLetter|lowerLetter|lowerLetterDot|lowerRoman", "off"?: bool}"#),
CommandSpec::new("para.multilevel", "Multilevel List", "Home › Paragraph", |s, v| list(s, v, ListKind::Legal)).params(r#"{"kind"?: "legal|outline"}"#),
CommandSpec::new("para.listLevel", "Change List Level", "Home › Paragraph › Bullets", |s, v| {
let lvl = p::u64(v, "level").unwrap_or(0).min(8) as u8;
fmt(s, &|p| {
if let Some(n) = p.numbering.as_mut() {
let moved = n.level != lvl;
n.level = lvl;
if moved {
format::drop_direct_indents(p);
}
}
})
})
+24 -2
View File
@@ -163,6 +163,16 @@ pub(super) fn set_props(s: &mut Session, v: &Value) -> CmdResult {
sel_result(s)
}
/// A list item that moves to another level takes that level's indents: a direct indent (a ruler
/// drag, a pasted block, a Word file's `w:ind`) would otherwise win over them and leave the item
/// out of line with its level (#4287).
pub(in crate::cmd) fn drop_direct_indents(p: &mut ParaProps) {
p.indent_left = None;
p.indent_first = None;
p.indent_left_chars = None;
p.indent_first_chars = None;
}
pub fn indent(s: &mut Session, _: &Value) -> CmdResult {
let a = s.sel.ordered().0;
let paths = crate::cmd::selected_paths(s);
@@ -174,7 +184,13 @@ pub fn indent(s: &mut Session, _: &Value) -> CmdResult {
};
let para = s.doc.para_mut(a.story, &path)?;
match num {
Some(n) => para.props.numbering = Some(NumRef { num: n.num, level: n.level.saturating_add(1).min(8) }),
Some(n) => {
let level = n.level.saturating_add(1).min(8);
para.props.numbering = Some(NumRef { num: n.num, level });
if level != n.level {
drop_direct_indents(&mut para.props);
}
}
None => {
para.props.indent_left = Some(((left / tab).floor() + 1.0) * tab);
para.props.cancel_char_indents(true, false, false);
@@ -196,7 +212,13 @@ pub fn outdent(s: &mut Session, _: &Value) -> CmdResult {
};
let para = s.doc.para_mut(a.story, &path)?;
match num {
Some(n) => para.props.numbering = Some(NumRef { num: n.num, level: n.level.saturating_sub(1) }),
Some(n) => {
let level = n.level.saturating_sub(1);
para.props.numbering = Some(NumRef { num: n.num, level });
if level != n.level {
drop_direct_indents(&mut para.props);
}
}
None => {
para.props.indent_left = Some((((left / tab).ceil() - 1.0) * tab).max(0.0));
para.props.cancel_char_indents(true, false, false);
+17 -6
View File
@@ -13,13 +13,24 @@ pub(super) fn list(s: &mut Session, v: &Value, default: ListKind) -> CmdResult {
.map(|p| s.doc.para(a.story, p).and_then(|x| s.doc.styles.resolve_para(&x.props).numbering).filter(|n| n.num != 0))
.collect();
let same_kind = |n: &NumRef| {
s.doc.numbering.level(n.num, n.level).is_some_and(|l| {
let want = wordcraft_doc::numbering::levels_for(kind);
want.get(usize::from(n.level)).is_some_and(|w| {
let want = wordcraft_doc::numbering::levels_for(kind);
// Is the list's level `i` (with this list's own overrides) the preset's level `i`?
let level_is = |i: u8, with_text: bool| match (s.doc.numbering.level(n.num, i), want.get(usize::from(i))) {
(Some(l), Some(w)) => {
(w.format == wordcraft_doc::section::NumFormat::Bullet) == (l.format == wordcraft_doc::section::NumFormat::Bullet)
&& (p::str(v, "kind").is_none() || w.text == l.text)
})
})
// A named preset is the same one only in its number style and text: "1." and "A." are
// both `%1.`, so picking one over the other changes the list, not switches it off (#4281).
&& (!with_text || (w.text == l.text && w.format == l.format))
}
_ => false,
};
let named = p::str(v, "kind").is_some();
// A named preset is told by its first level as well as the paragraph's own, as deeper levels of
// two presets can look alike; unless the list starts with the other kind of marker (a bullet
// above numbers, or the reverse), where the paragraph's own level decides.
let is_bullet = |i: u8| s.doc.numbering.level(n.num, i).map(|l| l.format == wordcraft_doc::section::NumFormat::Bullet);
let one_kind_throughout = is_bullet(0) == is_bullet(n.level);
level_is(n.level, named) && (!named || !one_kind_throughout || level_is(0, true))
};
let remove = off || (!current.is_empty() && current.iter().all(|n| n.as_ref().is_some_and(same_kind)));
if remove {
+7 -1
View File
@@ -54,7 +54,13 @@ type Reset = (fn(&CharProps) -> bool, fn(&mut CharProps));
const RESETS: [Reset; 24] = [
(|c| c.font.is_some(), |c| c.font = None),
(|c| c.font_cs.is_some(), |c| c.font_cs = None),
(|c| c.font_ea.is_some(), |c| c.font_ea = None),
(
|c| c.font_ea.is_some() || c.font_ea_theme.is_some(),
|c| {
c.font_ea = None;
c.font_ea_theme = None;
},
),
(|c| c.size.is_some(), |c| c.size = None),
(|c| c.size_cs.is_some(), |c| c.size_cs = None),
(|c| c.color.is_some(), |c| c.color = None),
+1 -1
View File
@@ -337,7 +337,7 @@ fn clipboard_content(s: &mut Session, v: &Value) -> Result<Pasted, CmdError> {
let text = p::str(v, "text").map(|t| t.replace("\r\n", "\n"));
match text {
Some(t) if !t.is_empty() => Ok(Pasted::Text(t)),
_ => Err(CmdError::Failed("the clipboard is empty".into())),
_ => Err(CmdError::ClipboardEmpty),
}
}
+21
View File
@@ -695,6 +695,27 @@ pub(crate) fn typing_pos(s: &Session, p: &Pos) -> Pos {
Pos { off, ..p.clone() }
}
/// The ranges, in any story, that a document protected as read only, comments only or forms
/// lets this author edit; `None` when the protection doesn't limit where edits may land. A command
/// that searches the whole document keeps only its matches inside them, so a match in protected
/// content (a header repeating a placeholder) is left alone instead of failing the command.
pub(crate) fn editable_ranges(s: &Session) -> Option<Vec<(Pos, Pos)>> {
match s.doc.settings.protection.as_deref()? {
"forms" => {
let stories = std::iter::once(StoryRef::Body).chain(s.doc.parts.keys().map(|k| StoryRef::Part(*k)));
Some(
stories
.flat_map(|story| s.doc.control_ranges(story))
.filter(|r| r.control.lock.can_edit())
.map(|r| (r.content_start(), r.end))
.collect(),
)
}
"readOnly" | "comments" => Some(s.doc.perm_ranges().into_iter().filter(|r| editable_by(r, &s.author)).map(|r| (r.start, r.end)).collect()),
_ => None,
}
}
/// The first position in an editable range after `from` (wrapping round), for Find Next Region
/// I Can Edit; with it, the range's end. Filling in forms: the next fillable control's content.
pub fn next_region(s: &Session, from: &Pos) -> Option<(Pos, Pos)> {
+24
View File
@@ -32,6 +32,30 @@ fn read_only_with_an_exception_allows_edits_only_inside_it() {
assert_eq!(s.doc.settings.protection.as_deref(), Some("readOnly"));
}
/// Replace All covers every story, but in a protected document only the editable regions change:
/// the same placeholder in a header, a footnote or the locked body text is left as it is, and
/// the replacement in the editable region still goes through.
#[test]
fn replace_all_in_a_protected_document_skips_protected_matches() {
let mut s = Session::new(Document::from_text("Locked [NAME].\nFill [NAME] in."));
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();
let r = s.run("edit.replaceAll", &json!({"text": "[NAME]", "with": "Jane"})).unwrap();
assert_eq!(r["replaced"], 1, "{r}");
let body = s.doc.plain_text(StoryRef::Body).replace(OBJ, "");
assert!(body.contains("Locked [NAME]."), "{body}");
assert!(body.contains("Fill Jane in."), "{body}");
for id in [header, note] {
let first = Pos::new(StoryRef::Part(id), wordcraft_doc::Path::top(0), 0);
assert!(s.doc.para_at(&first).unwrap().text.contains("[NAME]"));
}
}
/// An exception that starts a line: Home, Left and Down put the caret before its start
/// marker, and Enter and typing there go inside the exception. A caret after the end marker at
/// the end of the line goes back inside it too.
+10 -7
View File
@@ -402,7 +402,7 @@ pub fn update_fields_in(s: &mut Session, all: bool) -> Result<(), CmdError> {
}
let mut updates: Vec<(usize, String)> = Vec::new();
for (k, o) in p.objects.iter().enumerate() {
let InlineObject::Field { instr, locked: false, .. } = o else { continue };
let InlineObject::Field { instr, result, locked: false, .. } = o else { continue };
// A table formula reads the cells around its own cell again.
if instr.trim_start().starts_with('=') {
if let Some((tp, r, c)) = path.cell()
@@ -425,12 +425,15 @@ pub fn update_fields_in(s: &mut Session, all: bool) -> Result<(), CmdError> {
let created = s.doc.core.created.trim();
// CREATEDATE shows when the document was created (ECMA-376 §17.16.5.11). A new
// document, never saved, has no creation date yet and saving stamps now. A
// file opened without one, or with one that can't be read, keeps the result
// it has.
let text = if name != "CREATEDATE" || (created.is_empty() && s.path.is_none()) {
crate::cmd::insert::format_date_in(&pic, lang.as_deref())
} else if let Some((unix, offset)) = created_at(created) {
// file opened without one, or with one that can't be read, keeps any result
// it already has; when inserted with none, it shows today's date (the date
// a save would stamp).
let text = if name == "CREATEDATE"
&& let Some((unix, offset)) = created_at(created)
{
crate::cmd::insert::format_date_at_in(&pic, lang.as_deref(), unix, offset)
} else if name != "CREATEDATE" || result.is_empty() || (created.is_empty() && s.path.is_none()) {
crate::cmd::insert::format_date_in(&pic, lang.as_deref())
} else {
continue;
};
@@ -604,7 +607,7 @@ fn created_at(stamp: &str) -> Option<(u64, i64)> {
/// Word's default date or time picture when a field instruction carries no `\@` picture switch.
fn default_picture(name: &str, lang: Option<&str>) -> String {
if name == "TIME" { "h:mm am/pm".into() } else { crate::cmd::insert::default_date_picture(lang).into() }
if name == "TIME" { crate::cmd::insert::default_time_picture(lang).into() } else { crate::cmd::insert::default_date_picture(lang).into() }
}
/// Most names SET fields give values.
const MAX_SET: usize = 10_000;
+110
View File
@@ -556,6 +556,26 @@ fn createdate_without_a_readable_creation_date() {
assert_eq!(fields(&s)[0].1, crate::cmd::insert::format_date("yyyy-MM"));
}
/// Inserting CREATEDATE into an opened file that has no creation date (plain text, Markdown, or a
/// DOCX without `dcterms:created`) shows today's date rather than an empty result, while an
/// existing field with a cached result keeps it.
#[test]
fn createdate_inserted_into_opened_file_without_creation_date() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Notes"));
s.path = Some(std::env::temp_dir().join("notes.txt"));
s.doc.core.created.clear();
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#, "result": "2019-05"})).unwrap();
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#})).unwrap();
let expected = crate::cmd::insert::format_date("yyyy-MM");
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
assert_eq!(results, ["2019-05".to_string(), expected.clone()]);
// An unreadable creation date behaves the same way: cached results stay, empty ones fill in.
s.doc.core.created = "sometime in May".into();
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#})).unwrap();
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
assert_eq!(results, ["2019-05".to_string(), expected.clone(), expected]);
}
#[test]
fn toc_tabs_ignore_nonentries() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Before\nContents\nOld\t9\nAfter"));
@@ -677,6 +697,96 @@ fn a_toc_replaced_right_before_a_table_still_lands_the_caret_in_a_paragraph() {
assert!(matches!(&*s.doc.body[new_end + 1], Block::Para(_)));
}
/// Inserting a table of contents in the middle of a document places the caret in the paragraph
/// right after the table and leaves the text above and below it unchanged.
#[test]
fn a_toc_inserted_in_the_middle_of_a_document_leaves_the_caret_after_it() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Intro\nAfter TOC\nChapter One\nBody below."));
s.run("select.text", &json!({"text": "Chapter One"})).unwrap();
s.run("styles.apply", &json!({"style": "Heading 1"})).unwrap();
s.sel = Selection::caret(Pos { story: StoryRef::Body, path: Path::top(1), off: 0 });
s.run("references.toc", &json!({"levels": 2})).unwrap();
let (start, end) = toc_range(&s).unwrap();
assert_eq!(start, 1, "the TOC must immediately follow Intro without an extra blank paragraph");
assert_eq!(s.doc.body[0].as_para().map(|p| p.plain_text()).as_deref(), Some("Intro"));
assert_eq!(
s.sel.focus,
Pos { story: StoryRef::Body, path: Path::top(end + 1), off: 0 },
"the caret must land in the paragraph right after the TOC"
);
let below: Vec<String> = s.doc.body[end + 1..].iter().filter_map(|b| b.as_para()).map(|p| p.plain_text()).collect();
assert_eq!(below, ["After TOC", "Chapter One", "Body below."]);
}
/// One undo removes both the table of contents and the empty paragraph `caret_after_toc` adds
/// when the table ends the document or comes right before a table, leaving no stray blank
/// paragraph behind.
#[test]
fn undoing_a_toc_removes_both_the_table_and_the_added_paragraph() {
let toc_instr = |s: &Session, i: usize| {
s.doc.body[i].as_para().and_then(|p| {
p.objects.iter().find_map(|o| match o {
InlineObject::Field { instr, .. } => Some(instr.clone()),
_ => None,
})
})
};
// Fresh insert on an empty document undoes in one step.
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("references.toc", &json!({"levels": 2})).unwrap();
assert!(toc_range(&s).is_some());
assert_eq!(s.undo_depth(), 1);
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(s.undo_depth(), 0);
assert!(toc_range(&s).is_none());
assert_eq!(s.doc.body.len(), 1);
assert_eq!(s.doc.plain_text(StoryRef::Body), "");
// Table ending the document: `caret_after_toc` appends an empty paragraph, and one undo
// removes both the replaced table and that added paragraph.
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("references.toc", &json!({"levels": 2})).unwrap();
let (start, end) = toc_range(&s).unwrap();
while s.doc.body.len() > end + 1 {
s.doc.remove_block(StoryRef::Body, &Path::top(end + 1)).unwrap();
}
let before_blocks = s.doc.body.len();
let depth = s.undo_depth();
s.run("references.toc", &json!({"levels": 3})).unwrap();
let (_, new_end) = toc_range(&s).unwrap();
assert!(s.doc.body.get(new_end + 1).is_some_and(|b| b.as_para().is_some_and(|p| p.is_empty())));
assert_eq!(s.doc.body.len(), before_blocks + 1);
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(s.undo_depth(), depth);
assert_eq!(s.doc.body.len(), before_blocks, "undo must remove the added trailing paragraph");
assert_eq!(toc_range(&s), Some((start, end)));
assert!(toc_instr(&s, start).as_deref().is_some_and(|i| i.contains(r#"\o "1-2""#)));
// Table right before another table: `caret_after_toc` inserts an empty paragraph before the
// table, and one undo removes both the replaced TOC and that added paragraph.
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("references.toc", &json!({"levels": 2})).unwrap();
s.run("insert.table", &json!({"rows": 1, "cols": 1})).unwrap();
let (start, end) = toc_range(&s).unwrap();
while s.doc.body.get(end + 1).is_some_and(|b| b.as_para().is_some_and(|p| p.is_empty())) {
s.doc.remove_block(StoryRef::Body, &Path::top(end + 1)).unwrap();
}
assert!(matches!(&*s.doc.body[end + 1], Block::Table(_)));
let before_blocks = s.doc.body.len();
let depth = s.undo_depth();
s.run("references.toc", &json!({"levels": 3})).unwrap();
let (_, new_end) = toc_range(&s).unwrap();
assert!(s.doc.body.get(new_end + 1).is_some_and(|b| b.as_para().is_some_and(|p| p.is_empty())));
assert_eq!(s.doc.body.len(), before_blocks + 1);
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(s.undo_depth(), depth);
assert_eq!(s.doc.body.len(), before_blocks, "undo must remove the added paragraph before the table");
assert_eq!(toc_range(&s), Some((start, end)));
assert!(matches!(&*s.doc.body[end + 1], Block::Table(_)));
assert!(toc_instr(&s, start).as_deref().is_some_and(|i| i.contains(r#"\o "1-2""#)));
}
/// A fresh scratch directory for the file-name tests below.
#[cfg(not(target_arch = "wasm32"))]
fn filename_scratch_dir(tag: &str) -> std::path::PathBuf {
+2
View File
@@ -439,6 +439,8 @@ pub(super) fn insert_toc(s: &mut Session, v: &Value) -> CmdResult {
s.doc.remove_block(StoryRef::Body, &at.path)?;
}
at.path.last()
} else if at.off == 0 {
at.path.last()
} else {
s.doc.split_paragraph(&at)?.path.last()
};
+3 -11
View File
@@ -19,10 +19,8 @@ pub use changes::{
DELETION_TEXT_CHARS, DeletionBalloon, deletion_balloons, format_changes, has_deletions, has_format_changes, move_changes, tracking_json,
};
use changes::{list_changes, nav_change, resolve_all_then, resolve_sel_then, tracking_options};
use comments::{
comment_at_caret, comments_change, delete_comment, edit_comment, list_comments, nav_comment, new_comment, reply, validate_comment_id,
};
pub use comments::{comment_list, comment_range_at_caret};
use comments::{comments_change, delete_comment, edit_comment, list_comments, nav_comment, new_comment, reply, resolve_comment};
use proofing::{all_issues, issue_at, next_issue, suggestions, thesaurus, word_count};
pub fn specs() -> Vec<CommandSpec> {
@@ -37,14 +35,8 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("review.deleteComment", "Delete", "Review › Comments", delete_comment).params(
r#"{"id"?: non-negative 32-bit JSON integer (omit to use the caret), "all"?: bool (every comment), "resolved"?: bool (every resolved comment, with its replies; wins over all)}"#,
),
CommandSpec::new("review.resolveComment", "Resolve", "Review › Comments", |s, v| {
validate_comment_id(v)?;
let id = p::u64(v, "id").map(|x| x as u32).or_else(|| comment_at_caret(s)).ok_or_else(|| CmdError::Params("`id` required".into()))?;
let c = s.doc.comments.get_mut(&id).ok_or_else(|| CmdError::Params("no such comment".into()))?;
c.resolved = p::bool(v, "value").unwrap_or(!c.resolved);
sel_result(s)
})
.params(r#"{"id"?: non-negative 32-bit JSON integer (omit to use the caret), "value"?: bool (omit to toggle)}"#),
CommandSpec::new("review.resolveComment", "Resolve", "Review › Comments", resolve_comment)
.params(r#"{"id"?: non-negative 32-bit JSON integer (a comment or reply; omit to use the caret), "value"?: bool (omit to toggle the whole thread)}"#),
CommandSpec::new("review.nextComment", "Next", "Review › Comments", |s, _| nav_comment(s, 1)).pure(),
CommandSpec::new("review.previousComment", "Previous", "Review › Comments", |s, _| nav_comment(s, -1)).pure(),
CommandSpec::new("review.comments", "Show Comments", "Review › Comments", list_comments).pure(),
+67 -11
View File
@@ -26,7 +26,8 @@ fn resolve_runs(para: &mut wordcraft_doc::Paragraph, from: usize, to: usize, pro
}
/// Accept or reject a revision range in one paragraph; `mark` includes its paragraph mark (and
/// the section break on it), `props` the paragraph's own formatting change.
/// the section break on it), `props` the paragraph's own formatting change. If the next
/// paragraph moves into this path, return how many bytes of this paragraph precede it.
fn resolve_para(
s: &mut Session,
story: StoryRef,
@@ -34,11 +35,11 @@ fn resolve_para(
(from, to): (usize, usize),
(mark, props): (bool, bool),
accept: bool,
) -> Result<(), CmdError> {
) -> Result<Option<usize>, CmdError> {
let para = s.doc.para_mut(story, path)?;
resolve_runs(para, from, to, props, accept)?;
if !mark {
return Ok(());
return Ok(None);
}
if para.mark.fmt_change.is_some() || para.section.as_ref().is_some_and(|x| x.fmt_change.is_some()) {
fmt_revisions::resolve_char(&mut para.mark, accept);
@@ -49,8 +50,9 @@ fn resolve_para(
}
let (ins, del) = (para.mark.ins, para.mark.del);
if ins.is_none() && del.is_none() {
return Ok(());
return Ok(None);
}
let prefix_len = para.len();
// An inserted paragraph mark that is rejected, or a deleted one that is accepted, goes away:
// the next paragraph joins this one (the split is undone). A paragraph left empty goes away
// whole, so the next one keeps its own style and numbering, as in Word. The end mark of a
@@ -66,15 +68,18 @@ fn resolve_para(
if sectioned {
s.doc.remove_section_break(path.last());
}
if crate::cmd::remove_empty_para(s, story, path)? || crate::cmd::join_next_para(s, story, path)? {
return Ok(());
if crate::cmd::remove_empty_para(s, story, path)? {
return Ok(Some(0));
}
if crate::cmd::join_next_para(s, story, path)? {
return Ok(Some(prefix_len));
}
}
let para = s.doc.para_mut(story, path)?;
para.mark.ins = None;
para.mark.del = None;
para.touch();
Ok(())
Ok(None)
}
/// Remove the whole paragraph at `path` when a whole-paragraph revision on its mark resolved to
@@ -259,7 +264,49 @@ fn resolve_loose_blocks(blocks: &mut wordcraft_doc::Blocks, accept: bool) -> Res
Ok(())
}
/// Byte offset after resolving the runs in the endpoint's original paragraph. Only apply it
/// when paragraph removal or joining also moves the endpoint.
fn resolved_offset(s: &Session, end: &Pos, accept: bool) -> usize {
let Some(para) = s.doc.para_at(end) else { return end.off };
let removed: usize = para
.run_ranges()
.filter(|(_, c)| if accept { c.del.is_some() } else { c.ins.is_some() })
.map(|(range, _)| end.off.min(range.end).saturating_sub(range.start))
.sum();
end.off - removed
}
/// The next paragraph has moved into `path` (empty removal) or been appended to its surviving
/// prefix (join). Later siblings, including a table containing an endpoint, shift one block back.
fn remap_after_middle_paragraph(s: &mut Session, story: StoryRef, path: &wordcraft_doc::Path, prefix_len: usize, offsets: &mut [usize; 2]) {
let depth = path.parent().len();
for (end, offset) in [&mut s.sel.anchor, &mut s.sel.focus].into_iter().zip(offsets) {
if end.story != story || !end.path.0.starts_with(path.parent()) {
continue;
}
let Some(&block) = end.path.0.get(depth) else { continue };
if block as usize > path.last() {
let mut dest = end.path.clone();
dest.0[depth] -= 1;
// An endpoint in a terminal paragraph removed earlier still uses terminal clamping.
if s.doc.para(story, &dest).is_none() {
continue;
}
if &dest == path {
*offset = offset.saturating_add(prefix_len);
}
end.path = dest;
} else if &end.path == path {
*offset = (*offset).min(prefix_len);
} else {
continue;
}
end.off = *offset;
}
}
fn resolve_all(s: &mut Session, accept: bool) -> CmdResult {
let mut offsets = [&s.sel.anchor, &s.sel.focus].map(|end| resolved_offset(s, end, accept));
let stories: Vec<StoryRef> = std::iter::once(StoryRef::Body).chain(s.doc.parts.keys().map(|k| StoryRef::Part(*k))).collect();
for st in stories {
for path in s.doc.para_paths(st).into_iter().rev() {
@@ -269,9 +316,18 @@ fn resolve_all(s: &mut Session, accept: bool) -> CmdResult {
let is_last = s.doc.block(st, &path.with_last(path.last().saturating_add(1))).is_none();
let trailing = is_last && s.doc.para(st, &path).is_some_and(|p| (p.mark.del.is_some() && accept) || (p.mark.ins.is_some() && !accept));
let len = s.doc.para(st, &path).map(|p| p.len()).unwrap_or(0);
resolve_para(s, st, &path, (0, len), (true, true), accept)?;
if trailing {
remove_trailing_para(s, st, &path)?;
let prefix_len = resolve_para(s, st, &path, (0, len), (true, true), accept)?;
if trailing && remove_trailing_para(s, st, &path)? {
// Selection ends in the removed paragraph go to the end of the one before it;
// clamping later would keep their offsets in that paragraph's text (#8500).
for end in [&mut s.sel.anchor, &mut s.sel.focus] {
if end.story == st && end.path == path {
*end = s.doc.clamp(&Pos { off: usize::MAX, ..end.clone() });
}
}
}
if let Some(prefix_len) = prefix_len {
remap_after_middle_paragraph(s, st, &path, prefix_len, &mut offsets);
}
}
}
@@ -957,7 +1013,7 @@ fn resolve_sel(s: &mut Session, accept: bool, next: bool) -> CmdResult {
// A paragraph's mark is in the selection when the selection goes on past it.
let mark = path != b.path || caret_mark.as_ref() == Some(&path);
let props = (ranged && (path != b.path || to > from)) || caret_props.as_ref() == Some(&path);
resolve_para(s, a.story, &path, (from, to), (mark, props), accept)?;
let _ = resolve_para(s, a.story, &path, (from, to), (mark, props), accept)?;
if ranged {
resolve_cell(s, a.story, &path, accept)?;
}
+23
View File
@@ -186,6 +186,29 @@ fn threads_of(s: &Session, roots: impl IntoIterator<Item = u32>) -> Vec<u32> {
ids
}
/// Resolve or reopen the whole discussion, even when the target is a reply. A toggle uses
/// the target's state, matching its Resolve/Reopen button even in a mixed-state file.
pub(super) fn resolve_comment(s: &mut Session, v: &Value) -> CmdResult {
validate_comment_id(v)?;
let id = p::u64(v, "id").map(|x| x as u32).or_else(|| comment_at_caret(s)).ok_or_else(|| CmdError::Params("`id` required".into()))?;
let c = s.doc.comments.get(&id).ok_or_else(|| CmdError::Params("no such comment".into()))?;
let resolved = p::bool(v, "value").unwrap_or(!c.resolved);
let mut root = id;
let mut seen = BTreeSet::new();
while seen.insert(root) {
match s.doc.comments.get(&root).and_then(|c| c.parent).filter(|p| s.doc.comments.contains_key(p)) {
Some(parent) => root = parent,
None => break,
}
}
for id in threads_of(s, [root]) {
if let Some(c) = s.doc.comments.get_mut(&id) {
c.resolved = resolved;
}
}
sel_result(s)
}
pub(super) fn delete_comment(s: &mut Session, v: &Value) -> CmdResult {
validate_comment_id(v)?;
let ids: Vec<u32> = if p::bool(v, "resolved").unwrap_or(false) {
+141 -1
View File
@@ -311,7 +311,7 @@ fn comment_range_at_caret_needs_the_caret_inside_the_range() {
assert_eq!(super::comment_range_at_caret(&s), Some(id), "inside the commented text");
s.run("select.text", &json!({"text": "three"})).unwrap();
assert_eq!(super::comment_range_at_caret(&s), None, "elsewhere in the paragraph");
assert_eq!(super::comment_at_caret(&s), Some(id), "the older lookup still falls back to the paragraph's comment");
assert_eq!(super::comments::comment_at_caret(&s), Some(id), "the older lookup still falls back to the paragraph's comment");
}
fn glyph_text(d: &[Draw]) -> String {
@@ -491,6 +491,81 @@ fn deletions_outside_the_body_stay_inline_when_revisions_go_in_balloons() {
assert_eq!(deletion_balloons(&s), vec![DeletionBalloon { at: Pos::body(0, at), author: "Ana".into(), text: "zeta".into() }]);
}
fn assert_revision_arrow_stops(s: &mut Session, story: wordcraft_doc::StoryRef, from: [usize; 2], to: [usize; 2]) {
use wordcraft_doc::{Path, Pos};
let pos = |off| Pos::new(story, Path::top(0), off);
for (key, start, end) in [("Right", from[0], to[0]), ("Left", from[1], to[1])] {
let cmd = s.registry.by_shortcut(key).unwrap().id;
for extend in [false, true] {
s.run("caret.set", &json!({"pos": pos(start)})).unwrap();
s.run(cmd, &json!({"extend": extend})).unwrap();
assert_eq!(s.sel.focus, pos(end), "{key}, Shift {extend}, from {start}");
assert_eq!(s.sel.anchor, pos(if extend { start } else { end }));
}
}
}
#[test]
fn horizontal_arrows_follow_revision_balloon_visibility_by_story() {
use wordcraft_doc::{Path, Pos, StoryRef};
let mut s = Session::new(Document::from_text("AQRSZ"));
let id = s.run("insert.header", &json!({"text": "ABCDZ"})).unwrap()["story"].as_u64().unwrap() as u32;
let header = StoryRef::Part(id);
s.run("insert.closeHeader", &json!({})).unwrap();
s.run("review.trackChanges", &json!({"value": true})).unwrap();
for story in [StoryRef::Body, header] {
let at = |off| Pos::new(story, Path::top(0), off);
s.run("select.range", &json!({"anchor": at(1), "focus": at(4)})).unwrap();
s.run("text.delete", &json!({})).unwrap();
assert!(s.doc.para_at(&at(1)).unwrap().props_of_char(1).del.is_some());
}
s.run("review.trackingOptions", &json!({"balloons": "revisions"})).unwrap();
assert!(s.revisions_in_balloons());
assert_revision_arrow_stops(&mut s, StoryRef::Body, [1, 4], [5, 0]);
assert_revision_arrow_stops(&mut s, header, [1, 4], [2, 3]);
s.run("view.commentsPane", &json!({"value": true})).unwrap();
assert!(!s.revisions_in_balloons());
assert_revision_arrow_stops(&mut s, StoryRef::Body, [1, 4], [2, 3]);
s.run("review.trackingOptions", &json!({"balloons": "inline"})).unwrap();
s.run("view.commentsPane", &json!({"value": false})).unwrap();
assert_revision_arrow_stops(&mut s, StoryRef::Body, [1, 4], [2, 3]);
s.run("review.markup", &json!({"value": "noMarkup"})).unwrap();
for story in [StoryRef::Body, header] {
assert_revision_arrow_stops(&mut s, story, [1, 4], [5, 0]);
}
}
#[test]
fn horizontal_arrows_distinguish_hidden_deletions_from_hidden_move_sources() {
use wordcraft_doc::{Pos, Revision, RevisionKind, StoryRef};
let mut doc = Document::from_text("AxyuvZuv");
let deletion = Revision::new(RevisionKind::Delete, "Author", "");
let source = Revision { move_name: Some("Move1".into()), ..deletion.clone() };
let destination = Revision { kind: RevisionKind::Insert, ..source.clone() };
doc.revisions.extend([deletion, source, destination]);
doc.format_range(&Pos::body(0, 1), &Pos::body(0, 3), &|c| c.del = Some(0)).unwrap();
doc.format_range(&Pos::body(0, 3), &Pos::body(0, 5), &|c| c.del = Some(1)).unwrap();
doc.format_range(&Pos::body(0, 6), &Pos::body(0, 8), &|c| c.ins = Some(2)).unwrap();
let mut s = Session::new(doc);
for (delete_mark, move_from_mark, expected) in [
("strikethrough", "strikethrough", [2, 4]),
("hidden", "strikethrough", [4, 4]),
("strikethrough", "hidden", [2, 2]),
("hidden", "hidden", [6, 0]),
] {
s.run("review.trackingOptions", &json!({"balloons": "inline", "deleteMark": delete_mark, "moveFromMark": move_from_mark})).unwrap();
assert_revision_arrow_stops(&mut s, StoryRef::Body, [1, 5], expected);
}
}
fn body_para(s: &Session) -> &wordcraft_doc::Paragraph {
s.doc.para(wordcraft_doc::StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap()
}
@@ -925,6 +1000,71 @@ fn deleting_a_comment_deletes_replies_to_replies() {
assert_eq!(anchors(&s).len(), 2);
}
/// Resolving from the root, the caret or a nested reply changes the whole discussion in one
/// undo step. Reopening is also thread-wide, and unrelated discussions stay untouched.
#[test]
fn resolving_a_comment_changes_its_whole_thread() {
let mut s = Session::new(Document::from_text("first second"));
s.run("select.text", &json!({"text": "first"})).unwrap();
let root = s.run("review.newComment", &json!({"text": "root"})).unwrap()["id"].as_u64().unwrap();
let reply = s.run("review.reply", &json!({"id": root, "text": "reply"})).unwrap()["id"].as_u64().unwrap();
let nested = s.run("review.reply", &json!({"id": reply, "text": "nested"})).unwrap()["id"].as_u64().unwrap();
s.run("review.reply", &json!({"id": root, "text": "sibling"})).unwrap();
s.run("select.text", &json!({"text": "second"})).unwrap();
let other = s.run("review.newComment", &json!({"text": "other"})).unwrap()["id"].as_u64().unwrap() as u32;
s.run("select.text", &json!({"text": "first"})).unwrap();
let before = s.doc.comments.clone();
let body = s.doc.body.clone();
let parts = s.doc.parts.clone();
let depth = s.undo_depth();
let mut resolved = before.clone();
for (id, c) in &mut resolved {
c.resolved = *id != other;
}
for params in [json!({"id": root, "value": true}), json!({}), json!({"id": nested})] {
s.run("review.resolveComment", &params).unwrap();
assert_eq!(s.doc.comments, resolved, "{params}: all replies resolve, not the other discussion");
assert_eq!(s.undo_depth(), depth + 1, "one undo step for the whole thread");
s.run("review.resolveComment", &json!({"id": reply, "value": true})).unwrap();
assert_eq!(s.undo_depth(), depth + 1, "resolving an already resolved thread adds no step");
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc.comments, before, "one undo restores every comment");
s.run("edit.redo", &json!({})).unwrap();
assert_eq!(s.doc.comments, resolved);
s.run("review.resolveComment", &json!({"id": nested})).unwrap();
assert_eq!(s.doc.comments, before, "toggling a reply reopens the whole thread");
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc.comments, resolved);
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc.comments, before);
}
assert_eq!(s.doc.body, body, "resolution leaves the body and anchors alone");
assert_eq!(s.doc.parts, parts, "resolution leaves the comments' text alone");
}
/// Imported comments can have mixed resolved flags, missing parents or a parent cycle. A
/// thread operation reconciles the connected comments without following a missing parent.
#[test]
fn resolving_a_comment_handles_mixed_state_and_broken_parent_links() {
use wordcraft_doc::Comment;
for parent in [None, Some(99), Some(2)] {
let mut doc = Document::new();
doc.comments.insert(0, Comment { resolved: true, parent, ..Default::default() });
doc.comments.insert(1, Comment { parent: Some(0), ..Default::default() });
doc.comments.insert(2, Comment { parent: Some(1), ..Default::default() });
doc.comments.insert(3, Comment { parent: Some(99), ..Default::default() });
let mut s = Session::new(doc);
s.run("review.resolveComment", &json!({"id": 2})).unwrap();
assert!(
s.doc.comments.iter().all(|(id, c)| c.resolved == (*id != 3)),
"a reply's Resolve action must not reopen its resolved parent: {parent:?}"
);
s.run("review.resolveComment", &json!({"id": 1, "value": false})).unwrap();
assert!(s.doc.comments.values().all(|c| !c.resolved), "{parent:?}");
}
}
/// A parent cycle (possible in a hostile file) doesn't hang Delete; both comments go.
#[test]
fn deleting_a_comment_in_a_parent_cycle_ends() {
+1 -1
View File
@@ -1,7 +1,7 @@
use super::cells::{cell, cell_at, grid_cols, row_ends, selected_cells};
use super::{CmdError, CmdResult, Paragraph, Path, Pos, Selection, Session, StoryRef, Value, sel_result};
/// Ctrl+A in a table, as in Word: the cell, then its row, then the table. A nested table that
/// Explicit staged select-all in a table: the cell, then its row, then the table. A nested table that
/// is already fully selected grows to the cell around it. Returns `None` when the next step is
/// the whole story (not in a table, or the top-level table is already selected).
pub(crate) fn grow_select_all(s: &mut Session) -> Option<CmdResult> {
+4 -4
View File
@@ -630,10 +630,10 @@ fn room_right(l: &DocLayout, doc: &Document, page: usize, target: &ResizeTarget)
let Some(b) = boxes.iter().find(|b| b.story == target.story && b.table == outer && b.row == row && b.cell == cell) else {
return margin;
};
// A right-to-left table has its cells' start (left) margin on their right.
let m = wordcraft_layout::cell_margins(doc, t, row, cell);
let inset = if t.props.bidi_visual { m[1] } else { m[3] };
(b.rect.right() - inset).min(margin)
// A cell's right margin is on its right in a right-to-left table too, as the layout draws
// it (#6941): Word doesn't mirror cell margins.
let right_margin = wordcraft_layout::cell_margins(doc, t, row, cell)[3];
(b.rect.right() - right_margin).min(margin)
}
#[cfg(test)]
@@ -136,6 +136,30 @@ fn a_selected_column_is_edited_cell_by_cell() {
assert_eq!(s.cell_range().map(|r| r.cols), Some((1, 1)), "undo brings the column selection back");
}
/// Toggling a format on a selected table column follows the first character in document order (#8589).
#[test]
fn toggle_on_a_selected_table_column_follows_first_character() {
let toggled = |bold_row: usize| -> Vec<bool> {
let mut s = table_session(3, 3);
fill(&mut s);
let p = cell_pos(&s, bold_row, 1);
s.sel = Selection { anchor: p.clone(), focus: Pos { off: 4, ..p } };
s.run("format.bold", &json!({"value": true})).unwrap();
// Start from the bottom row so the caret is not on row 0.
s.sel = Selection::caret(cell_pos(&s, 2, 1));
s.run("table.selectColumn", &json!({})).unwrap();
s.run("format.bold", &json!({})).unwrap();
for r in 0..3 {
assert!(!bold(&s, r, 0) && !bold(&s, r, 2), "row {r}'s other cells stay plain");
}
(0..3).map(|r| bold(&s, r, 1)).collect()
};
// First row bold, later rows plain: Bold turns off across the column.
assert_eq!(toggled(0), vec![false, false, false]);
// First row plain, middle row bold: Bold turns on across the column.
assert_eq!(toggled(1), vec![true, true, true]);
}
/// Numbering a column numbers its cells as one list, like Word.
#[test]
fn numbering_a_column_makes_one_list() {
@@ -510,6 +534,46 @@ fn a_nested_tables_column_fits_within_its_cell() {
assert_eq!((host1.x, host1.w), (host.x, host.w), "the table around it keeps its columns");
}
/// #8441: a right-to-left table keeps its cells' right margins on their right (#6941), so a
/// nested table in such a cell fits up to that cell's right margin, not its left one, when the
/// two differ.
#[test]
fn a_nested_tables_column_fits_within_a_right_to_left_cell() {
let mut s = rtl_table_session(1, 2);
s.sel = Selection::caret(cell_pos(&s, 0, 0));
s.run("insert.table", &json!({"rows": 1, "cols": 2})).unwrap();
let (inner, _, _) = s.sel.focus.path.cell().unwrap();
let outer = table_path(&s);
// A left margin of 20 pt and a right one of 2 pt; the nested table itself left to right.
s.doc.table_mut(StoryRef::Body, &outer).unwrap().rows[0].cells[0].props.margins = Some([0.0, 20.0, 0.0, 2.0]);
s.doc.table_mut(StoryRef::Body, &inner).unwrap().props.bidi_visual = false;
s.touch();
let rect = |s: &mut Session, table: &Path, cell: usize| {
s.layout().pages[0]
.items
.iter()
.find_map(|it| match it {
Placed::Cell { rect, table: t, row: 0, cell: c, .. } if t == table && *c == cell => Some(*rect),
_ => None,
})
.unwrap()
};
for col in [1, 0] {
let r = rect(&mut s, &inner, col);
s.run("table.fitColumn", &json!({"page": 0, "x": r.right(), "y": mid_y(r)})).unwrap();
}
s.run("text.insert", &json!({"text": "word ".repeat(40)})).unwrap();
let host = rect(&mut s, &outer, 0);
let (a, b) = (rect(&mut s, &inner, 0), rect(&mut s, &inner, 1));
assert!(b.right() < host.right() - 40.0, "{b:?} in {host:?}");
s.run("table.fitColumn", &json!({"page": 0, "x": a.right(), "y": mid_y(a)})).unwrap();
let b1 = rect(&mut s, &inner, 1);
let text_right = host.right() - 2.0;
assert!((b1.right() - text_right).abs() < 0.5, "the table fills its cell's text up to its right margin: {b1:?}, {text_right}");
let host1 = rect(&mut s, &outer, 0);
assert_eq!((host1.x, host1.w), (host.x, host.w), "the table around it keeps its columns");
}
/// Pasting formatting onto a selected column leaves its text (it used to clear it).
#[test]
fn the_format_painter_keeps_a_selected_columns_text() {
+15 -3
View File
@@ -206,7 +206,11 @@ pub(super) fn tab(s: &mut Session, _: &Value) -> CmdResult {
&& n.num != 0
{
let para = s.doc.para_mut(f.story, &f.path)?;
para.props.numbering = Some(NumRef { num: n.num, level: n.level.saturating_add(1).min(8) });
let level = n.level.saturating_add(1).min(8);
para.props.numbering = Some(NumRef { num: n.num, level });
if level != n.level {
crate::cmd::para::drop_direct_indents(&mut para.props);
}
para.touch();
return sel_result(s);
}
@@ -255,7 +259,11 @@ fn indent_by_tab(s: &mut Session, f: &Pos) -> CmdResult {
&& let Some(n) = r.numbering.filter(|n| n.num != 0)
{
let p = s.doc.para_mut(f.story, &f.path)?;
p.props.numbering = Some(NumRef { num: n.num, level: n.level.saturating_add(1).min(8) });
let level = n.level.saturating_add(1).min(8);
p.props.numbering = Some(NumRef { num: n.num, level });
if level != n.level {
crate::cmd::para::drop_direct_indents(&mut p.props);
}
p.touch();
return sel_result(s);
}
@@ -288,7 +296,11 @@ pub(super) fn back_tab(s: &mut Session, _: &Value) -> CmdResult {
let f = s.sel.focus.clone();
if let Some(n) = s.doc.para_at(&f).and_then(|x| x.props.numbering).filter(|n| n.num != 0) {
let para = s.doc.para_mut(f.story, &f.path)?;
para.props.numbering = Some(NumRef { num: n.num, level: n.level.saturating_sub(1) });
let level = n.level.saturating_sub(1);
para.props.numbering = Some(NumRef { num: n.num, level });
if level != n.level {
crate::cmd::para::drop_direct_indents(&mut para.props);
}
para.touch();
return sel_result(s);
}
+20 -9
View File
@@ -260,12 +260,12 @@ fn diff_notes(
}
for &new_id in &notes.inserted {
if let Some(part) = doc.parts.get_mut(&new_id) {
part.blocks = part.blocks.iter().map(|b| Arc::new(mark_block(b, &|c| c.ins = Some(ctx.ins)))).collect();
part.blocks = part.blocks.iter().map(|b| Arc::new(mark_block(b, &|c| c.ins = Some(ctx.ins), &|_| {}))).collect();
}
}
for &orig_id in &notes.deleted {
if let Some(part) = doc.parts.get_mut(&orig_id) {
part.blocks = part.blocks.iter().map(|b| Arc::new(mark_block(b, &|c| c.del = Some(ctx.del)))).collect();
part.blocks = part.blocks.iter().map(|b| Arc::new(mark_block(b, &|c| c.del = Some(ctx.del), &|_| {}))).collect();
}
}
}
@@ -443,14 +443,18 @@ fn diff_blocks(doc: &mut Document, old: &[Arc<Block>], new: &[Arc<Block>], ctx:
(Some(Block::Para(pa)), Some(Block::Para(pb))) => out.push(para_block(word_diff(doc, pa, pb, ctx))),
_ => {
if let Some(x) = a {
out.push(Arc::new(mark_block(x, &|c| {
// An existing deletion is another author's: keep their revision
// stamp instead of re-attributing the paragraph to this compare.
c.del.get_or_insert(ctx.del);
})));
out.push(Arc::new(mark_block(
x,
&|c| {
// An existing deletion is another author's: keep their revision
// stamp instead of re-attributing the paragraph to this compare.
c.del.get_or_insert(ctx.del);
},
&|_| {},
)));
}
if let Some(x) = b {
out.push(Arc::new(mark_block(x, &|c| c.ins = Some(ctx.ins))));
out.push(Arc::new(mark_block(x, &|c| c.ins = Some(ctx.ins), &|c| c.del = None)));
}
}
}
@@ -1627,7 +1631,13 @@ fn block_text(b: &Block, depth: usize) -> String {
/// where the paragraph carries a section break or is the container's only paragraph. A
/// non-terminal section-carrying paragraph is removed whole too: `resolve_para` removes the
/// section break first (#5734, issue #5667), so the following paragraph keeps its own properties.
fn mark_block(b: &Block, f: &dyn Fn(&mut CharProps)) -> Block {
///
/// `mark` additionally updates each paragraph mark. A whole inserted block keeps only the
/// compare's insertion on its mark: a `del` the revised document's mark already carried (a pending
/// deletion by another author) must not survive next to the compare's `ins` — on accept the
/// deletion branch would resolve the inserted paragraph away (#6899). Run-level revisions of the
/// source block are left alone.
fn mark_block(b: &Block, f: &dyn Fn(&mut CharProps), mark: &dyn Fn(&mut CharProps)) -> Block {
let mut out = b.clone();
let mut todo = vec![&mut out];
while let Some(blk) = todo.pop() {
@@ -1636,6 +1646,7 @@ fn mark_block(b: &Block, f: &dyn Fn(&mut CharProps)) -> Block {
let len = p.len();
let _ = p.format(0, len, f);
f(&mut p.mark);
mark(&mut p.mark);
p.touch();
}
Block::Table(t) => {
+158 -57
View File
@@ -55,6 +55,37 @@ fn compare_marks_a_whole_paragraph_and_its_mark() {
assert_eq!(empty_paras(&s), 0, "rejecting a deleted paragraph left an empty paragraph behind");
}
#[test]
fn resolving_a_middle_paragraph_keeps_the_caret_with_its_text() {
for (original, revised, command) in [("A\nB\nC", "A\nNEW\nB\nC", "review.rejectAll"), ("A\nOLD\nB\nC", "A\nB\nC", "review.acceptAll")] {
let mut s = Session::new(Document::from_text(original));
s.run("review.compare", &json!({"text": revised})).unwrap();
s.sel = Selection::caret(Pos::body(2, 1));
s.run(command, &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB\nC");
assert!(s.sel.is_collapsed());
assert_eq!(s.sel.focus, Pos::body(1, 1), "{command} keeps the caret after B");
s.run("text.insert", &json!({"text": "!"})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB!\nC");
}
}
#[test]
fn accepting_a_middle_paragraph_join_keeps_the_backward_selection() {
let mut s = Session::new(Document::from_text("A\néDROP\nX🙂B\nC"));
s.run("review.trackChanges", &json!({"value": true})).unwrap();
s.sel = Selection { anchor: Pos::body(1, "é".len()), focus: Pos::body(2, "X".len()) };
s.run("text.delete", &json!({})).unwrap();
s.sel = Selection { anchor: Pos::body(2, "X🙂".len()), focus: Pos::body(1, 0) };
s.run("review.acceptAll", &json!({"stopTracking": true})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\né🙂B\nC");
assert_eq!(s.sel.anchor, Pos::body(1, "é🙂".len()));
assert_eq!(s.sel.focus, Pos::body(1, 0));
s.run("text.insert", &json!({"text": "Q"})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nQB\nC");
}
#[test]
fn compare_marks_an_empty_paragraphs_mark() {
// An empty inserted paragraph is stamped on its mark, though `format` skips its empty range.
@@ -130,6 +161,24 @@ fn compare_terminal_deleted_paragraph_resolves_fully() {
assert_eq!(empty_paras(&s), 0, "accepting a terminal deleted paragraph left an empty paragraph behind");
}
#[test]
fn resolving_a_selected_terminal_paragraph_puts_the_caret_before_it() {
// A selection inside the terminal paragraph that Reject All (insertion) or Accept All
// (deletion) removes ends as a caret at the end of the paragraph before it, not over the
// same offsets of that paragraph's text (#8500).
let cases = [("A\nKeep this", "A\nKeep this\nNEW", "review.rejectAll"), ("A\nKeep this\nOLD", "A\nKeep this", "review.acceptAll")];
for (orig, revised, cmd) in cases {
let mut s = Session::new(Document::from_text(orig));
s.run("review.compare", &json!({"text": revised})).unwrap();
s.sel = Selection { anchor: Pos::body(2, 0), focus: Pos::body(2, 3) };
s.run(cmd, &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nKeep this", "{cmd}");
assert_eq!(s.sel, Selection::caret(Pos::body(1, "Keep this".len())), "{cmd}");
s.run("text.insert", &json!({"text": "Z"})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nKeep thisZ", "{cmd}");
}
}
#[test]
fn reject_all_keeps_an_empty_inserted_paragraph_between_tables() {
// An empty paragraph between two tables is not the container's last block: removing it
@@ -220,16 +269,8 @@ fn compare_pins_accepting_a_deleted_section_keeps_the_next_paragraphs_style() {
}
#[test]
fn compare_marks_the_last_paragraphs_mark() {
// Inserted last paragraph: rejecting removes it whole.
let mut s = Session::new(Document::from_text("A\nB"));
s.run("review.compare", &json!({"text": "A\nB\nNEW"})).unwrap();
assert_eq!(s.doc.body.len(), 3);
assert!(s.doc.body[2].as_para().unwrap().mark.ins.is_some());
s.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
assert_eq!(s.doc.body.len(), 2);
assert_eq!(empty_paras(&s), 0);
fn compare_keeps_terminal_paragraph_when_insertion_accepted_or_deletion_rejected() {
// Inserted last paragraph: accepting keeps it whole.
let mut s = Session::new(Document::from_text("A\nB"));
s.run("review.compare", &json!({"text": "A\nB\nNEW"})).unwrap();
s.run("review.acceptAll", &json!({})).unwrap();
@@ -237,15 +278,7 @@ fn compare_marks_the_last_paragraphs_mark() {
assert_eq!(s.doc.body.len(), 3);
assert_eq!(empty_paras(&s), 0);
// Deleted last paragraph: accepting removes it whole.
let mut s = Session::new(Document::from_text("A\nB\nOLD"));
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
assert_eq!(s.doc.body.len(), 3);
assert!(s.doc.body[2].as_para().unwrap().mark.del.is_some());
s.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
assert_eq!(s.doc.body.len(), 2);
assert_eq!(empty_paras(&s), 0);
// Deleted last paragraph: rejecting keeps it whole.
let mut s = Session::new(Document::from_text("A\nB\nOLD"));
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
s.run("review.rejectAll", &json!({})).unwrap();
@@ -1743,55 +1776,123 @@ fn compare_lcs_window_move_past_cap_does_not_cascade_false_revisions() {
assert_eq!(s.doc.plain_text(StoryRef::Body), revised);
}
fn assert_whole_block_mark_compare(from: &str, to: &str, expected_mid: &str, is_del: bool, preserve_bold: bool) {
let expected_empty = |text: &str| text.split('\n').filter(|line| line.is_empty()).count();
let from_len = from.split('\n').count();
let to_len = to.split('\n').count();
let mut s = Session::new(Document::from_text(from));
if preserve_bold && let Some(Block::Para(p)) = s.doc.body.get_mut(1).map(Arc::make_mut) {
p.mark.bold = Some(true);
}
s.run("review.compare", &json!({"text": to})).unwrap();
assert_eq!(s.doc.body.len(), 3);
let mid = s.doc.body[1].as_para().expect("block 1 must be paragraph");
assert_eq!(mid.plain_text(), expected_mid);
if expected_mid.is_empty() {
assert_eq!(mid.len(), 0);
}
if is_del {
assert!(mid.mark.del.is_some(), "whole-block delete must record revision on paragraph mark");
} else {
assert!(mid.mark.ins.is_some(), "whole-block insert must record revision on paragraph mark");
}
if preserve_bold {
assert_eq!(mid.mark.bold, Some(true), "paragraph mark formatting must be preserved on deleted block");
}
let mut s_rej = Session::new(s.doc.clone());
s_rej.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s_rej.doc.plain_text(StoryRef::Body), from);
assert_eq!(s_rej.doc.body.len(), from_len);
assert_eq!(empty_paras(&s_rej), expected_empty(from), "rejecting a whole-block revision changed empty paragraph count");
s.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), to);
assert_eq!(s.doc.body.len(), to_len);
assert_eq!(empty_paras(&s), expected_empty(to), "accepting a whole-block revision changed empty paragraph count");
}
/// Verifies that `mark_block` records paragraph mark revisions on whole-block deletions,
/// whole-block insertions, empty paragraphs, and ensures clean resolution via `review.acceptAll`.
/// whole-block insertions, empty paragraphs, and ensures clean resolution via `review.acceptAll`
/// and `review.rejectAll`.
#[test]
fn compare_mark_block_records_paragraph_mark_revisions_on_whole_block_changes() {
// Whole block delete/insert: test with differing paragraph count so whole-block paths trigger
let orig_multi = "Keep start.\nDelete me.\nKeep end.";
let rev_multi = "Keep start.\nKeep end.";
let mut s2 = Session::new(Document::from_text(orig_multi));
if let Some(Block::Para(p)) = s2.doc.body.get_mut(1).map(Arc::make_mut) {
p.mark.bold = Some(true);
}
s2.run("review.compare", &json!({"text": rev_multi})).unwrap();
// In s2.doc.body, block 1 was deleted whole.
// Verify that p.mark.del is recorded by mark_block and formatting is preserved.
let del_para = s2.doc.body[1].as_para().expect("block 1 must be paragraph");
assert!(del_para.mark.del.is_some(), "whole-block delete must record revision on paragraph mark");
assert_eq!(del_para.mark.bold, Some(true), "paragraph mark formatting must be preserved on deleted block");
// Accept all changes: deleted paragraph is removed
s2.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s2.doc.plain_text(StoryRef::Body), rev_multi);
// Test whole-block insertion
let mut s3 = Session::new(Document::from_text(rev_multi));
s3.run("review.compare", &json!({"text": orig_multi})).unwrap();
let ins_para = s3.doc.body[1].as_para().expect("block 1 must be paragraph");
assert!(ins_para.mark.ins.is_some(), "whole-block insert must record revision on paragraph mark");
s3.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s3.doc.plain_text(StoryRef::Body), orig_multi);
assert_whole_block_mark_compare(orig_multi, rev_multi, "Delete me.", true, true);
assert_whole_block_mark_compare(rev_multi, orig_multi, "Delete me.", false, false);
// Test empty paragraph deletion and insertion (len == 0, where only mark carries the revision)
let orig_empty = "Before.\n\nAfter.";
let rev_empty = "Before.\nAfter.";
let mut s4 = Session::new(Document::from_text(orig_empty));
s4.run("review.compare", &json!({"text": rev_empty})).unwrap();
let empty_del = s4.doc.body[1].as_para().expect("empty paragraph block");
assert_eq!(empty_del.len(), 0);
assert!(empty_del.mark.del.is_some(), "empty paragraph deletion must set mark.del");
s4.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s4.doc.plain_text(StoryRef::Body), rev_empty);
assert_whole_block_mark_compare(orig_empty, rev_empty, "", true, false);
assert_whole_block_mark_compare(rev_empty, orig_empty, "", false, false);
}
let mut s5 = Session::new(Document::from_text(rev_empty));
s5.run("review.compare", &json!({"text": orig_empty})).unwrap();
let empty_ins = s5.doc.body[1].as_para().expect("empty paragraph block");
assert_eq!(empty_ins.len(), 0);
assert!(empty_ins.mark.ins.is_some(), "empty paragraph insertion must set mark.ins");
s5.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s5.doc.plain_text(StoryRef::Body), orig_empty);
/// Issue #6899: when the revised document's paragraph mark already carries another author's
/// pending deletion, a whole-paragraph insertion by compare must not leave the mark with both
/// `ins` and `del` — on accept the deletion branch would remove the inserted paragraph (or join
/// it away), losing the inserted break. The revised clone's mark keeps only the compare's `ins`.
#[test]
fn compare_inserted_paragraph_mark_drops_a_foreign_del() {
use wordcraft_doc::{Revision, RevisionKind};
let mut rev = Document::from_text("Keep start.\nNew line.\nKeep end.");
rev.revisions.push(Revision { kind: RevisionKind::Delete, author: "Other".into(), date: String::new(), date_utc: None, move_name: None });
if let Some(Block::Para(p)) = rev.body.get_mut(1).map(Arc::make_mut) {
p.mark.del = Some(0);
}
let path = std::env::temp_dir().join(format!("wc-compare-6899-{}.docx", std::process::id()));
crate::io::save_path(&path, &rev).unwrap();
let check = crate::io::open_path(&path).unwrap();
assert!(check.body[1].as_para().unwrap().mark.del.is_some(), "the foreign del must survive the docx round-trip, or this test proves nothing");
let mut s = Session::new(Document::from_text("Keep start.\nKeep end."));
s.run("review.compare", &json!({"path": path.to_string_lossy()})).unwrap();
let _ = std::fs::remove_file(&path);
let ins = s.doc.body[1].as_para().expect("block 1 is the inserted paragraph");
assert!(ins.mark.ins.is_some(), "compare marks the whole inserted paragraph's mark");
assert!(ins.mark.del.is_none(), "the foreign del does not sit next to the compare's ins");
// Accepting keeps the inserted paragraph break: the text reads as the revised document's.
s.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "Keep start.\nNew line.\nKeep end.");
}
/// Issue #6899, inside a table: `mark_block` recurses into cells, so a paragraph mark there gets
/// the same treatment — a foreign `del` does not sit next to the compare's `ins`.
#[test]
fn compare_inserted_table_cell_paragraph_mark_drops_a_foreign_del() {
use wordcraft_doc::{Revision, RevisionKind, Table};
let mut rev = Document::from_text("Keep start.\nKeep end.");
rev.revisions.push(Revision { kind: RevisionKind::Delete, author: "Other".into(), date: String::new(), date_utc: None, move_name: None });
let mut t = Table::new(1, 1, 200.0);
if let Some(c) = t.rows.first_mut().and_then(|r| r.cells.first_mut())
&& let Some(Block::Para(p)) = c.blocks.first_mut().map(Arc::make_mut)
{
p.mark.del = Some(0);
}
rev.body.insert(1, Arc::new(Block::Table(t)));
let path = std::env::temp_dir().join(format!("wc-compare-6899-table-{}.docx", std::process::id()));
crate::io::save_path(&path, &rev).unwrap();
let check = crate::io::open_path(&path).unwrap();
let cell_marked = check.body.iter().any(|b| match &**b {
Block::Table(t) => {
t.rows.iter().flat_map(|r| r.cells.iter()).flat_map(|c| c.blocks.iter()).any(|b| b.as_para().is_some_and(|p| p.mark.del.is_some()))
}
_ => false,
});
assert!(cell_marked, "the cell paragraph's foreign del must survive the docx round-trip, or this test proves nothing");
let mut s = Session::new(Document::from_text("Keep start.\nKeep end."));
s.run("review.compare", &json!({"path": path.to_string_lossy()})).unwrap();
let _ = std::fs::remove_file(&path);
let Some(Block::Table(t)) = s.doc.body.get(1).map(|b| &**b) else { panic!("block 1 is the inserted table") };
let cell_para = t.rows[0].cells[0].blocks[0].as_para().expect("the cell paragraph");
assert!(cell_para.mark.ins.is_some(), "compare marks the inserted cell paragraph's mark");
assert!(cell_para.mark.del.is_none(), "the foreign del does not sit next to the compare's ins");
s.run("review.acceptAll", &json!({})).unwrap();
assert!(matches!(s.doc.body.get(1).map(|b| &**b), Some(Block::Table(_))), "accepting keeps the inserted table");
}
#[test]
+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);
+6
View File
@@ -76,6 +76,12 @@ impl AutomationRoots {
Ok(Some(Arc::new(Self { read, write })))
}
/// Roots that grant no access at all: what an agent gets when its folders can't be used, so it
/// is refused rather than left unconfined.
pub fn none() -> Arc<Self> {
Arc::new(Self { read: None, write: None })
}
/// The read root, absolute with its links followed.
pub fn read_root(&self) -> Option<&Path> {
self.read.as_ref().map(|r| r.shown.as_path())
+1 -1
View File
@@ -509,7 +509,7 @@ pub fn open_path_in(path: &std::path::Path, password: Option<&str>, region: &wor
/// Largest document file opened by path.
#[cfg(not(target_arch = "wasm32"))]
const MAX_DOCUMENT: u64 = 2 << 30;
const MAX_DOCUMENT: u64 = 2u64 << 30;
/// The bytes of the document at `path`, read as `file.open` reads a path: inside the automation
/// read root, and only a regular file of at most 2 GB. A named pipe would block the open and a
+18 -1
View File
@@ -92,7 +92,7 @@ pub fn save(ext: &str, doc: &Document, opts: &crate::io::ExportOptions) -> Optio
// Output shows the fields Word fills in as it prints (see `output_fields`).
let out = crate::cmd::references::output_fields(doc);
let doc = out.as_ref().unwrap_or(doc);
Some(crate::strict::export_pdf(doc, opts))
Some(crate::strict::export_pdf(&pdf_document(doc), opts))
}
other => wordcraft_formats::export_with(other, doc, &wordcraft_formats::ExportOptions { comments: opts.markup && opts.comments }),
}
@@ -142,6 +142,23 @@ pub fn render_png(doc: &Document, page: usize, scale: f32, opts: &crate::io::Exp
Ok(img.to_png())
}
/// Supply an absent or unreadable PDF creation date without changing the document or advancing
/// its revision. This covers direct exports and web downloads, which do not pass through
/// `stamp_save`.
///
/// Unreadable, not only absent: the DOCX reader takes `core.created` as it finds it, so a file can
/// arrive carrying something like `not-a-date`. The PDF writer cannot put that in a document and
/// falls back to the clock, which is the one thing a pinned date is meant to stop -- so the
/// question asked here is the writer's own (`reads_as_date`), not whether the string is empty
/// (noted in review).
pub(crate) fn pdf_document(doc: &Document) -> std::borrow::Cow<'_, Document> {
let mut output = std::borrow::Cow::Borrowed(doc);
if !wordcraft_pdf::reads_as_date(&doc.core.created) {
output.to_mut().core.created = crate::cmd::saved_iso();
}
output
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
+2
View File
@@ -84,6 +84,8 @@ pub enum CmdError {
Params(String),
#[error("not available: {0}")]
Disabled(String),
#[error("the clipboard is empty")]
ClipboardEmpty,
#[error("{0}")]
Failed(String),
}
+1 -1
View File
@@ -243,7 +243,7 @@ impl Session {
compress: p::bool(v, "compress").unwrap_or(true),
..Default::default()
};
let bytes = wordcraft_pdf::export_layout(doc, &lay, &opts).map_err(|e| CmdError::Failed(e.to_string()))?;
let bytes = wordcraft_pdf::export_layout(&crate::io_ext::pdf_document(doc), &lay, &opts).map_err(|e| CmdError::Failed(e.to_string()))?;
Ok((bytes, plan))
}
}
+1 -1
View File
@@ -106,7 +106,7 @@ impl Session {
pub fn stamp_save(&mut self) {
self.doc.settings.zoom = crate::cmd::view::saved_zoom(&self.view);
let core = &mut self.doc.core;
core.modified = crate::cmd::now_iso();
core.modified = crate::cmd::saved_iso();
if core.created.is_empty() {
core.created = core.modified.clone();
}
+20 -5
View File
@@ -1,3 +1,5 @@
use wordcraft_layout::HideDeleted;
use super::doc_state::{Selection, TypedWord, typed_range};
use super::locale::SYSTEM_LOCALE;
use super::snapshot_types::LayoutEntry;
@@ -11,6 +13,20 @@ impl Session {
self.layout_with(typing)
}
fn revision_layout_options(&self) -> LayoutOptions {
LayoutOptions {
hide_deleted: !self.view.show_markup,
hide_marked: self.prefs.markup.hidden_deletions(),
deletions_in_balloons: self.revisions_in_balloons(),
..LayoutOptions::default()
}
}
/// Which tracked deletions the editor leaves out of this story.
pub(crate) fn layout_hides_deleted(&self, story: StoryRef) -> HideDeleted {
self.revision_layout_options().hides_deleted(story)
}
/// [`Session::layout`] with `typing` as the word being typed.
fn layout_with(&mut self, typing: Option<wordcraft_layout::TypingWord>) -> Arc<DocLayout> {
let mode = if self.view.read_mode { ViewMode::Read } else { self.view.mode };
@@ -23,8 +39,8 @@ impl Session {
let spacing = if self.view.read_mode { self.view.read_line_spacing.map(f32::to_bits) } else { None };
// Deletions in balloons depend on the view (the Comments pane, Read Mode, side by side), so
// a view change that moves them in or out of the text lays it out again.
let hide_deleted = !self.view.show_markup;
let deleted = (hide_deleted, self.prefs.markup.hidden_deletions(), self.revisions_in_balloons());
let revisions = self.revision_layout_options();
let deleted = (revisions.hide_deleted, revisions.hide_marked, revisions.deletions_in_balloons);
let outline = (mode == ViewMode::Outline).then(|| self.view.outline.view());
let shown = (self.view.marks || self.prefs.marks.hidden, self.view.field_codes);
// A dictionary or Language pack installed, removed or edited (in this document's window or
@@ -62,9 +78,6 @@ impl Session {
read_height: height,
read_line_spacing: spacing.map(f32::from_bits),
show_hidden: shown.0,
hide_deleted,
hide_marked: deleted.1,
deletions_in_balloons: deleted.2,
proofing: self.view.proofing,
numeral: self.view.numeral.resolve(SYSTEM_LOCALE.get().map(String::as_str)),
comment_balloons: false,
@@ -77,6 +90,7 @@ impl Session {
// The editor shows a body page reference as stored until fields are updated.
output_page_refs: false,
bookmark_error: None,
..revisions
};
let l = Arc::new(wordcraft_layout::layout(&self.doc, &mut self.cache, &opts));
let [newest, _] = std::mem::take(&mut self.layout);
@@ -286,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"
+541 -124
View File
@@ -293,14 +293,6 @@ fn custom_dictionary_words_persist_through_their_file() {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn confined_sessions_test_is_native_only() {
let source = include_str!("tests.rs");
assert!(source.contains(
"#[cfg(not(target_arch = \"wasm32\"))]\n#[test]\nfn confined_sessions_neither_save_the_dictionary_nor_choose_folders_outside_their_roots()"
));
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn confined_sessions_neither_save_the_dictionary_nor_choose_folders_outside_their_roots() {
@@ -1118,6 +1110,79 @@ fn toggle_on_a_selection_from_an_empty_paragraph_follows_the_first_text() {
assert_eq!(toggled(false, true), Some(false));
}
/// Toggling a format on a selected text box follows the first character of its text (#8589).
#[test]
fn toggle_on_a_selected_text_box_follows_first_character() {
let toggled = |first_bold: bool, second_bold: bool, leading_empty_bold: Option<bool>| -> String {
let mut s = s();
let id = run(&mut s, "insert.textBox", json!({}))["story"].as_u64().unwrap() as u32;
let boxed = StoryRef::Part(id);
if let Some(mark_bold) = leading_empty_bold {
s.doc.para_mut(boxed, &wordcraft_doc::Path::top(0)).unwrap().mark.bold = Some(mark_bold);
run(&mut s, "text.newParagraph", json!({}));
}
let text_block = usize::from(leading_empty_bold.is_some());
run(&mut s, "text.insert", json!({"text": "ab"}));
let box_pos = |off| Pos { story: boxed, path: wordcraft_doc::Path::top(text_block), off };
run(&mut s, "select.range", json!({"anchor": box_pos(0), "focus": box_pos(1)}));
run(&mut s, "format.bold", json!({"value": first_bold}));
run(&mut s, "select.range", json!({"anchor": box_pos(1), "focus": box_pos(2)}));
run(&mut s, "format.bold", json!({"value": second_bold}));
let anchor = s.doc.text_box_anchor(id).unwrap();
run(&mut s, "select.range", json!({"anchor": Pos { off: anchor.off - "\u{FFFC}".len(), ..anchor.clone() }, "focus": anchor}));
run(&mut s, "format.bold", json!({}));
let p = s.doc.para(boxed, &wordcraft_doc::Path::top(text_block)).unwrap();
(0..2).map(|i| if p.props_of_char(i).bold == Some(true) { 'B' } else { '.' }).collect()
};
// First character bold, second plain: Bold turns off across the box.
assert_eq!(toggled(true, false, None), "..");
// First character plain, second bold: Bold turns on across the box.
assert_eq!(toggled(false, true, None), "BB");
// A bold empty paragraph at the top of the box does not override plain text after it.
assert_eq!(toggled(false, true, Some(true)), "BB");
}
/// Toggling a format on a column block follows the first character in document order (#8589).
#[test]
fn toggle_on_a_column_block_follows_first_character() {
let toggled = |bold_row: usize, top_to_bottom: bool| -> Vec<bool> {
let mut s = column_doc();
run(&mut s, "select.range", json!({"anchor": {"block": bold_row, "off": 2}, "focus": {"block": bold_row, "off": 4}}));
run(&mut s, "format.bold", json!({"value": true}));
let (a, f) = if top_to_bottom { (Pos::body(0, 2), Pos::body(2, 4)) } else { (Pos::body(2, 4), Pos::body(0, 2)) };
run(&mut s, "select.column", json!({"anchor": a, "focus": f}));
run(&mut s, "format.bold", json!({}));
(0..3).map(|i| s.doc.para_at(&Pos::body(i, 0)).unwrap().props_of_char(2).bold == Some(true)).collect()
};
// Row 0 bold, rows 1-2 plain: Bold turns off across the block even when selected bottom-to-top.
assert_eq!(toggled(0, true), vec![false, false, false]);
assert_eq!(toggled(0, false), vec![false, false, false]);
// Row 0 plain, row 1 bold: Bold turns on across the block even when selected bottom-to-top.
assert_eq!(toggled(1, true), vec![true, true, true]);
assert_eq!(toggled(1, false), vec![true, true, true]);
}
/// A collapsed caret inside a partly formatted word (including when column mode just started with
/// an empty block) turns the format on unless the whole word already has it (#8658).
#[test]
fn toggle_at_collapsed_caret_in_partly_formatted_word_turns_on() {
let toggled = |column_mode: bool| -> String {
let mut s = s();
run(&mut s, "text.insert", json!({"text": "Abc"}));
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 0}, "focus": {"block": 0, "off": 1}}));
run(&mut s, "format.bold", json!({"value": true}));
run(&mut s, "caret.set", json!({"pos": {"block": 0, "off": 1}}));
if column_mode {
run(&mut s, "select.column", json!({}));
}
run(&mut s, "format.bold", json!({}));
let p = s.doc.para_at(&Pos::body(0, 0)).unwrap();
(0..3).map(|i| if p.props_of_char(i).bold == Some(true) { 'B' } else { '.' }).collect()
};
assert_eq!(toggled(false), "BBB");
assert_eq!(toggled(true), "BBB");
}
#[test]
fn bold_at_a_caret_takes_a_word_with_a_typographic_apostrophe() {
// Word bolds `don’t` and `dogs’` whole: `’` is part of the word like `'` (#6517).
@@ -3646,6 +3711,23 @@ fn tracked_table_changes_are_kept_as_formatting_changes() {
assert!(b && !ch, "Accept All keeps it");
}
#[test]
fn ctrl_a_inside_table_selects_document() {
let mut s = s();
run(&mut s, "text.insert", json!({"text": "Before"}));
run(&mut s, "text.newParagraph", json!({}));
run(&mut s, "insert.table", json!({"rows": 2, "cols": 2}));
run(&mut s, "text.insert", json!({"text": "A1"}));
assert!(s.sel.focus.path.cell().is_some());
run(&mut s, "select.all", json!({}));
assert_eq!(s.sel.ordered(), (s.doc.start_of(StoryRef::Body), s.doc.end_of(StoryRef::Body)));
assert!(s.column.is_none());
assert!(s.selected_text().contains("Before"));
assert!(s.selected_text().contains("A1"));
}
#[test]
fn select_all_grows_cell_then_row_then_table_then_document() {
let mut s = s();
@@ -3655,24 +3737,24 @@ fn select_all_grows_cell_then_row_then_table_then_document() {
run(&mut s, "text.insert", json!({"text": "A1"}));
assert_eq!(s.sel.focus.path.cell().map(|(_, r, c)| (r, c)), Some((0, 0)));
run(&mut s, "select.all", json!({}));
assert_eq!(cells(&s), Some(((0, 0), (0, 0))), "first Ctrl+A selects the cell");
run(&mut s, "select.all", json!({"whole": false}));
assert_eq!(cells(&s), Some(((0, 0), (0, 0))), "first staged selection selects the cell");
assert_eq!(s.selected_text(), "A1");
run(&mut s, "select.all", json!({}));
assert_eq!(cells(&s), Some(((0, 0), (0, 1))), "second Ctrl+A selects the row");
run(&mut s, "select.all", json!({"whole": false}));
assert_eq!(cells(&s), Some(((0, 0), (0, 1))), "second staged selection selects the row");
run(&mut s, "select.all", json!({}));
assert_eq!(cells(&s), Some(((0, 1), (0, 1))), "third Ctrl+A selects the table");
run(&mut s, "select.all", json!({"whole": false}));
assert_eq!(cells(&s), Some(((0, 1), (0, 1))), "third staged selection selects the table");
run(&mut s, "select.all", json!({}));
run(&mut s, "select.all", json!({"whole": false}));
assert!(s.column.is_none());
let (a, b) = s.sel.ordered();
assert_eq!(a, s.doc.start_of(StoryRef::Body));
assert_eq!(b, s.doc.end_of(StoryRef::Body));
assert!(s.selected_text().starts_with("Before"));
run(&mut s, "select.all", json!({}));
run(&mut s, "select.all", json!({"whole": false}));
let (a, b) = s.sel.ordered();
assert_eq!((a, b), (s.doc.start_of(StoryRef::Body), s.doc.end_of(StoryRef::Body)));
}
@@ -3683,8 +3765,8 @@ fn select_all_from_a_column_grows_to_the_table() {
run(&mut s, "insert.table", json!({"rows": 2, "cols": 2}));
run(&mut s, "table.selectColumn", json!({}));
assert_eq!(cells(&s), Some(((0, 1), (0, 0))));
run(&mut s, "select.all", json!({}));
assert_eq!(cells(&s), Some(((0, 1), (0, 1))), "Ctrl+A on a column selects the table");
run(&mut s, "select.all", json!({"whole": false}));
assert_eq!(cells(&s), Some(((0, 1), (0, 1))), "staged selection on a column selects the table");
}
#[test]
@@ -3693,14 +3775,14 @@ fn select_all_keeps_the_whole_story_when_it_ends_in_a_table() {
run(&mut s, "insert.table", json!({"rows": 2, "cols": 2}));
run(&mut s, "text.insert", json!({"text": "A1"}));
s.doc.body.pop();
run(&mut s, "select.all", json!({}));
run(&mut s, "select.all", json!({}));
run(&mut s, "select.all", json!({}));
run(&mut s, "select.all", json!({}));
run(&mut s, "select.all", json!({"whole": false}));
run(&mut s, "select.all", json!({"whole": false}));
run(&mut s, "select.all", json!({"whole": false}));
run(&mut s, "select.all", json!({"whole": false}));
let whole = (s.doc.start_of(StoryRef::Body), s.doc.end_of(StoryRef::Body));
assert!(s.doc.end_of(StoryRef::Body).path.cell().is_some());
assert_eq!(s.sel.ordered(), whole);
run(&mut s, "select.all", json!({}));
run(&mut s, "select.all", json!({"whole": false}));
assert!(s.column.is_none());
assert_eq!(s.sel.ordered(), whole);
}
@@ -5109,6 +5191,174 @@ fn no_markup_view_lays_out_the_final_text() {
assert!(gap(&mut s).abs() < 0.01);
}
#[test]
fn horizontal_caret_skips_hidden_tracked_deletions() {
let mut s = s();
let text = "Aé🧪ZUVΩT";
let before = Pos::body(0, "A".len());
let between = Pos::body(0, "Aé".len());
let after = Pos::body(0, "Aé🧪".len());
let far_start = Pos::body(0, "Aé🧪ZUV".len());
let far_end = Pos::body(0, "Aé🧪ZUVΩ".len());
run(&mut s, "document.setText", json!({"text": text}));
// Keep the adjacent deleted characters in separate formatting runs.
s.doc.format_range(&before, &between, &|c| c.bold = Some(true)).unwrap();
run(&mut s, "review.trackChanges", json!({"value": true}));
run(&mut s, "select.text", json!({"text": "é🧪"}));
run(&mut s, "text.delete", json!({}));
run(&mut s, "select.text", json!({"text": "Ω"}));
run(&mut s, "text.delete", json!({}));
assert_eq!(s.doc.para_at(&before).unwrap().deleted_ranges(), [before.off..between.off, between.off..after.off, far_start.off..far_end.off]);
s.sel = crate::Selection::caret(before.clone());
run(&mut s, "caret.right", json!({}));
assert_eq!(s.sel.focus, Pos::body(0, "Aé".len()), "visible markup still has ordinary caret stops");
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
s.sel = crate::Selection::caret(before.clone());
run(&mut s, "caret.right", json!({"extend": true}));
assert_eq!(s.sel.anchor, before);
assert_eq!(s.sel.focus, Pos::body(0, "Aé🧪Z".len()), "Right crosses the next visible character in one step");
s.sel = crate::Selection::caret(after);
run(&mut s, "caret.left", json!({}));
assert_eq!(s.sel.focus, Pos::body(0, 0), "Left crosses the previous visible character in one step");
assert!(s.sel.is_collapsed());
s.sel = crate::Selection::caret(Pos::body(0, "Aé🧪Z".len()));
run(&mut s, "caret.right", json!({}));
assert_eq!(s.sel.focus, Pos::body(0, "Aé🧪ZU".len()), "a distant deletion does not change a visible stop");
s.sel = crate::Selection::caret(far_end);
run(&mut s, "caret.left", json!({}));
assert_eq!(s.sel.focus, Pos::body(0, "Aé🧪ZU".len()), "Left also skips the later deletion");
}
#[test]
fn word_caret_skips_hidden_tracked_deletions() {
let mut s = s();
run(&mut s, "document.setText", json!({"text": "one two three"}));
let two_start = Pos::body(0, "one ".len());
let two_mid = Pos::body(0, "one tw".len());
let three_start = Pos::body(0, "one two ".len());
let end = Pos::body(0, "one two three".len());
// Keep the deleted word split across two formatting runs.
s.doc.format_range(&two_start, &two_mid, &|c| c.bold = Some(true)).unwrap();
run(&mut s, "review.trackChanges", json!({"value": true}));
run(&mut s, "select.text", json!({"text": "two "}));
run(&mut s, "text.delete", json!({}));
s.sel = crate::Selection::caret(Pos::body(0, 0));
run(&mut s, "caret.wordRight", json!({}));
assert_eq!(s.sel.focus, two_start, "visible markup still stops at the deleted word");
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
s.sel = crate::Selection::caret(Pos::body(0, 0));
run(&mut s, "caret.wordRight", json!({"extend": true}));
assert_eq!(s.sel.anchor, Pos::body(0, 0));
assert_eq!(s.sel.focus, three_start, "Ctrl+Right skips the hidden deleted word in one press");
s.sel = crate::Selection::caret(two_start.clone());
run(&mut s, "caret.wordRight", json!({}));
assert_eq!(s.sel.focus, end, "Ctrl+Right from the hidden start moves across the next visible word");
s.sel = crate::Selection::caret(end.clone());
run(&mut s, "caret.wordLeft", json!({}));
assert_eq!(s.sel.focus, three_start);
run(&mut s, "caret.wordLeft", json!({}));
assert_eq!(s.sel.focus, Pos::body(0, 0), "Ctrl+Left skips the hidden deleted word in one press");
s.sel = crate::Selection::caret(two_start);
run(&mut s, "caret.wordLeft", json!({}));
assert_eq!(s.sel.focus, Pos::body(0, 0));
// A deleted space between two visible word fragments joins them into one visible word.
let mut s = self::s();
run(&mut s, "document.setText", json!({"text": "foot ball next"}));
run(&mut s, "review.trackChanges", json!({"value": true}));
run(&mut s, "select.text", json!({"text": " "}));
run(&mut s, "text.delete", json!({}));
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
let next_start = Pos::body(0, "foot ball ".len());
s.sel = crate::Selection::caret(Pos::body(0, 0));
run(&mut s, "caret.wordRight", json!({}));
assert_eq!(s.sel.focus, next_start, "Ctrl+Right crosses a hidden deleted space inside a word");
run(&mut s, "caret.wordLeft", json!({}));
assert_eq!(s.sel.focus, Pos::body(0, 0), "Ctrl+Left crosses back over the joined word");
// Trailing and leading hidden deletions step to the neighbouring paragraph once no visible text remains.
let mut s = self::s();
run(&mut s, "document.setText", json!({"text": "alpha beta\ngamma delta"}));
run(&mut s, "review.trackChanges", json!({"value": true}));
run(&mut s, "select.text", json!({"text": "beta"}));
run(&mut s, "text.delete", json!({}));
run(&mut s, "select.text", json!({"text": "gamma "}));
run(&mut s, "text.delete", json!({}));
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
s.sel = crate::Selection::caret(Pos::body(0, 0));
run(&mut s, "caret.wordRight", json!({}));
assert_eq!(s.sel.focus, Pos::body(0, "alpha ".len()));
run(&mut s, "caret.wordRight", json!({}));
assert_eq!(s.sel.focus, Pos::body(1, 0), "Ctrl+Right before a trailing deletion crosses to the next paragraph");
s.sel = crate::Selection::caret(Pos::body(1, "gamma delta".len()));
run(&mut s, "caret.wordLeft", json!({}));
assert_eq!(s.sel.focus, Pos::body(1, "gamma ".len()));
run(&mut s, "caret.wordLeft", json!({}));
assert_eq!(s.sel.focus, Pos::body(0, "alpha beta".len()), "Ctrl+Left after a leading deletion crosses to the previous paragraph");
// Multi-run paragraph with separately formatted words, a far-away deletion, and adjacent deleted runs.
let mut s = self::s();
run(&mut s, "document.setText", json!({"text": "alpha beta gamma delta epsilon zeta"}));
for word in ["alpha", "gamma", "epsilon"] {
run(&mut s, "select.text", json!({"text": word}));
run(&mut s, "format.bold", json!({}));
}
let beta_mid = Pos::body(0, "alpha be".len());
let gamma_start = Pos::body(0, "alpha beta ".len());
s.doc.format_range(&Pos::body(0, "alpha ".len()), &beta_mid, &|c| c.italic = Some(true)).unwrap();
run(&mut s, "review.trackChanges", json!({"value": true}));
run(&mut s, "select.text", json!({"text": "beta "}));
run(&mut s, "text.delete", json!({}));
run(&mut s, "select.text", json!({"text": "epsilon "}));
run(&mut s, "text.delete", json!({}));
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
let expected_right = [
Pos::body(0, "alpha beta ".len()),
Pos::body(0, "alpha beta gamma ".len()),
Pos::body(0, "alpha beta gamma delta epsilon ".len()),
Pos::body(0, "alpha beta gamma delta epsilon zeta".len()),
];
s.sel = crate::Selection::caret(Pos::body(0, 0));
for expected in &expected_right {
run(&mut s, "caret.wordRight", json!({}));
assert_eq!(s.sel.focus, *expected, "Ctrl+Right keeps the same visible word stops across formatted runs and far-away/adjacent deletions");
}
let expected_left =
[Pos::body(0, "alpha beta gamma delta epsilon ".len()), Pos::body(0, "alpha beta gamma ".len()), gamma_start, Pos::body(0, 0)];
for expected in &expected_left {
run(&mut s, "caret.wordLeft", json!({}));
assert_eq!(s.sel.focus, *expected, "Ctrl+Left keeps the same visible word stops across formatted runs and far-away/adjacent deletions");
}
// Word boundaries at paragraph edges preserve step_to_neighbor (do not skip a wholly deleted neighbor paragraph).
let mut s = self::s();
run(&mut s, "document.setText", json!({"text": "AB\nCD\nEF"}));
run(&mut s, "review.trackChanges", json!({"value": true}));
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 1), "focus": Pos::body(2, 1)}));
run(&mut s, "text.delete", json!({}));
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
s.sel = crate::Selection::caret(Pos::body(0, 1));
run(&mut s, "caret.wordRight", json!({}));
assert_eq!(s.sel.focus, Pos::body(1, 0), "Ctrl+Right at paragraph edge uses step_to_neighbor(skip_deleted=false)");
s.sel = crate::Selection::caret(Pos::body(2, 1));
run(&mut s, "caret.wordLeft", json!({}));
assert_eq!(s.sel.focus, Pos::body(1, "CD".len()), "Ctrl+Left at paragraph edge uses step_to_neighbor(skip_deleted=false)");
}
#[test]
fn replace_all_is_tracked() {
let mut s = s();
@@ -7062,6 +7312,56 @@ fn select_box(s: &mut Session) {
run(s, "select.range", json!({"anchor": o.pos(), "focus": end}));
}
#[test]
fn dragging_above_a_pushed_first_line_keeps_the_drop_position() {
use wordcraft_doc::para::{Anchor, Float, InlineObject, OBJ, ShapeKind, Wrap};
let shape = |w, h, float| InlineObject::Shape {
kind: ShapeKind::Rectangle,
w,
h,
fill: None,
stroke: None,
stroke_width: 1.0,
float,
story: None,
freeform: None,
effects: Default::default(),
extra: Default::default(),
};
for frame_wrap in [Wrap::TopAndBottom, Wrap::BehindText] {
// Original synthetic version of #6587's first-line push. Only the frame wraps text.
let mut doc = wordcraft_doc::Document::from_text("A line under a frame.");
let old_top = doc.last_section.margin_top;
let (x, y) = (120.0, old_top - 22.0);
let object = Float { wrap: Wrap::InFrontOfText, h_rel: Anchor::Page, v_rel: Anchor::Page, x, y: old_top + 12.0, ..Default::default() };
let frame = Float { wrap: frame_wrap, v_rel: Anchor::Paragraph, y: -20.0, ..Default::default() };
let at = Pos::body(0, 0);
let end = Pos::body(0, OBJ.len_utf8());
doc.insert_object(&at, shape(40.0, 18.0, object), &Default::default()).unwrap();
doc.insert_object(&end, shape(300.0, 250.0, frame), &Default::default()).unwrap();
let mut s = Session::new(doc);
run(&mut s, "select.range", json!({"anchor": at, "focus": end}));
run(&mut s, "arrange.bounds", json!({"page": 0, "x": x, "y": y}));
let hit = s.layout().object(&at, 0).unwrap();
assert!((hit.rect.y - y).abs() < 0.01 && (hit.rect.x - x).abs() < 0.01, "{frame_wrap:?}: {hit:?}");
assert_eq!(hit.origin.y > old_top + 1.0, frame_wrap == Wrap::TopAndBottom);
for (with_text, anchor) in [(false, Anchor::Page), (true, Anchor::Paragraph)] {
run(&mut s, "arrange.moveWithText", json!({"value": with_text}));
let hit = s.layout().object(&at, 0).unwrap();
let (_, _, float) = s.doc.para_at(&at).unwrap().object_at(at.off).unwrap().frame().unwrap();
assert_eq!(float.v_rel, anchor);
assert!((hit.rect.y - y).abs() < 0.01, "{frame_wrap:?}, {anchor:?}: {hit:?}");
let origin = if with_text { hit.origin.y } else { 0.0 };
assert!((hit.rect.y - origin - float.y).abs() < 0.01, "{frame_wrap:?}, {anchor:?}: {hit:?}");
}
run(&mut s, "draw.stroke", json!({"page": 0, "points": [[x, y], [x + 10.0, y]], "width": 2.0}));
let ink = s.layout().object(&at, 0).unwrap();
assert!((ink.rect.y - (y - 1.0)).abs() < 0.01, "{frame_wrap:?}: {ink:?}");
}
}
#[test]
fn arrange_bounds_resizes_and_moves_objects() {
use wordcraft_doc::para::{Anchor, Wrap};
@@ -10004,77 +10304,6 @@ fn change_case_keeps_each_runs_formatting_when_lengths_change() {
assert_eq!(text(&s), "Q");
}
/// #3479: Change Case follows language-aware mapping for Turkish, Azerbaijani, and Crimean Tatar (i↔İ, ı↔I).
#[test]
fn change_case_follows_turkic_language_mapping() {
// 1. Turkish (tr-TR): all 5 modes
// Capitalize Each Word (title)
let mut s = s();
run(&mut s, "review.language", json!({"lang": "tr-TR", "default": true}));
run(&mut s, "text.insert", json!({"text": "istanbul ışık", "raw": true}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": "title"}));
assert_eq!(text(&s), "İstanbul Işık");
// UPPERCASE
run(&mut s, "format.changeCase", json!({"mode": "upper"}));
assert_eq!(text(&s), "İSTANBUL IŞIK");
// lowercase
run(&mut s, "format.changeCase", json!({"mode": "lower"}));
assert_eq!(text(&s), "istanbul ışık");
// sentence case
let mut s = self::s();
run(&mut s, "review.language", json!({"lang": "tr-TR", "default": true}));
run(&mut s, "text.insert", json!({"text": "istanbul. ışık.", "raw": true}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": "sentence"}));
assert_eq!(text(&s), "İstanbul. Işık.");
// toggle case
let mut s = self::s();
run(&mut s, "review.language", json!({"lang": "tr-TR", "default": true}));
run(&mut s, "text.insert", json!({"text": "İstanbul Işık", "raw": true}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": "toggle"}));
assert_eq!(text(&s), "iSTANBUL ıŞIK");
// 2. Azerbaijani (az-AZ)
let mut s = self::s();
run(&mut s, "review.language", json!({"lang": "az-AZ", "default": true}));
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": "title"}));
assert_eq!(text(&s), "İstanbul");
// 3. Crimean Tatar (crh)
let mut s = self::s();
run(&mut s, "review.language", json!({"lang": "crh", "default": true}));
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": "title"}));
assert_eq!(text(&s), "İstanbul");
// 4. English control (en-US): unchanged Unicode default
let mut s = self::s();
run(&mut s, "review.language", json!({"lang": "en-US", "default": true}));
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": "title"}));
assert_eq!(text(&s), "Istanbul");
// 5. Mixed-language selection: Turkish run followed by English run
let mut s = self::s();
run(&mut s, "review.language", json!({"lang": "tr-TR"}));
run(&mut s, "text.insert", json!({"text": "istanbul ", "raw": true}));
run(&mut s, "review.language", json!({"lang": "en-US"}));
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": "title"}));
assert_eq!(text(&s), "İstanbul Istanbul");
}
#[test]
fn change_case_sentence_ignores_decimal_points() {
// #3485: Sentence case should not capitalize after decimal points.
@@ -11661,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";
@@ -11681,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 =
@@ -11758,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.
@@ -11789,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).
@@ -11802,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!({}));
@@ -11857,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.
@@ -11964,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!({}));
@@ -12007,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}));
@@ -12036,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!({}));
@@ -12055,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);
@@ -12094,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
@@ -12104,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.
@@ -12137,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.
@@ -12177,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!({}));
@@ -12204,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!({}));
@@ -12232,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()
@@ -12276,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");
@@ -12382,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!({}));
@@ -12623,10 +12856,12 @@ fn outline_level_changes_are_undoable() {
assert!(s.run("outline.level", &json!({"level": 12})).is_err());
assert!(s.run("outline.level", &json!({})).is_err());
// Every outline command survives junk parameters in Outline view.
for spec in cmd::registry().all().iter().filter(|c| c.id.starts_with("outline.")) {
let reg = cmd::registry();
for spec in reg.all().iter().filter(|c| c.id.starts_with("outline.")) {
for j in [json!(null), json!({"block": 99999, "level": "x", "value": 5}), json!({"block": -1, "level": 0})] {
let mut s = outline_doc();
let _ = s.run(spec.id, &j);
let r = s.run(spec.id, &j);
assert!(!caught_panic(&reg, &r), "{} panicked on {j}: {r:?}", spec.id);
let _ = s.layout();
}
}
@@ -15625,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}));
@@ -15685,6 +15920,91 @@ fn page_down_extends_a_selection_that_ends_in_collapsed_outline_text() {
assert!(s.layout().caret(&s.sel.focus).is_some(), "to a place the outline shows");
}
/// #3300: Replace All, as in Word, replaces in the main text, headers, footers, footnotes,
/// endnotes and text boxes, wherever the caret is. Comments keep their words.
#[test]
fn replace_all_replaces_in_every_story() {
use wordcraft_doc::{CharProps, Paragraph, PartKind, StoryRef, para_block};
let story_text = |t: &Session, story: StoryRef| {
let first = wordcraft_doc::Pos::new(story, wordcraft_doc::Path::top(0), 0);
if story == StoryRef::Body { t.doc.plain_text(story) } else { t.doc.para_at(&first).map(|p| p.text.clone()).unwrap_or_default() }
};
let build = || {
let mut t = s();
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;
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).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).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])).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).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}));
let r = run(&mut t, "edit.replaceAll", json!({"text": "[NAME]", "with": "Jane"}));
assert_eq!(r["replaced"], 7, "{r}");
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();
@@ -16166,3 +16486,100 @@ fn nested_group_text_box_survives_mutating_session_commands() {
assert_eq!(s.doc.plain_text(StoryRef::Part(id)), "nested group box");
}
}
#[test]
fn copy_refuses_to_fill_clipboard_by_halves_when_export_fails() {
let mut s = Session::new(wordcraft_doc::Document::from_text("first second"));
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, 5)}));
run(&mut s, "edit.copy", json!({}));
let prev_text = s.clipboard_text.clone();
let prev_html = s.clipboard_html.clone();
let prev_rtf = s.clipboard_rtf.clone();
let prev_history_len = s.clip_history.len();
assert_eq!(prev_text, "first");
assert!(!prev_html.is_empty() && !prev_rtf.is_empty());
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 6), "focus": Pos::body(0, 12)}));
// HTML export fails first.
let err = wordcraft_formats::with_shared_conversion_error("html failed", || s.run("edit.copy", &json!({}))).unwrap_err();
assert!(err.to_string().contains("html failed"), "{err}");
assert_eq!(s.clipboard_text, prev_text);
assert_eq!(s.clipboard_html, prev_html);
assert_eq!(s.clipboard_rtf, prev_rtf);
assert_eq!(s.clipboard.as_ref().map(|f| f.plain_text()), Some("first".to_string()));
assert_eq!(s.clip_history.len(), prev_history_len);
// HTML export succeeds and RTF export fails: clipboard still keeps "first" whole.
let err = wordcraft_formats::with_shared_conversion_error_after(1, "rtf failed", || s.run("edit.copy", &json!({}))).unwrap_err();
assert!(err.to_string().contains("rtf failed"), "{err}");
assert_eq!(s.clipboard_text, prev_text);
assert_eq!(s.clipboard_html, prev_html);
assert_eq!(s.clipboard_rtf, prev_rtf);
assert_eq!(s.clipboard.as_ref().map(|f| f.plain_text()), Some("first".to_string()));
assert_eq!(s.clip_history.len(), prev_history_len);
// Cut also refuses to delete the selection when export fails.
let err = wordcraft_formats::with_shared_conversion_error_after(1, "rtf failed", || s.run("edit.cut", &json!({}))).unwrap_err();
assert!(err.to_string().contains("rtf failed"), "{err}");
assert_eq!(text(&s), "first second");
assert_eq!(s.clipboard_text, prev_text);
assert_eq!(s.clipboard_html, prev_html);
assert_eq!(s.clipboard_rtf, prev_rtf);
assert_eq!(s.clip_history.len(), prev_history_len);
}
#[test]
fn paste_reports_or_falls_back_when_html_import_fails() {
let mut s = Session::new(wordcraft_doc::Document::from_text("kept"));
let err = wordcraft_formats::with_shared_conversion_error("html import failed", || {
s.run("edit.pasteSpecial", &json!({"as": "html", "html": "<p>new</p>"}))
})
.unwrap_err();
assert!(err.to_string().contains("html import failed"), "{err}");
assert_eq!(text(&s), "kept");
let fallback = wordcraft_formats::with_shared_conversion_error_after(0, "html import failed", || {
cmd::paste::rich_fragment(&mut s, &json!({"html": "<p>from html</p>", "rtf": "{\\rtf1 from rtf}"}))
});
assert_eq!(fallback.as_ref().map(|f| f.plain_text()), Some("from rtf".to_string()));
let none = wordcraft_formats::with_shared_conversion_error("html import failed", || {
cmd::paste::rich_fragment(&mut s, &json!({"html": "<p>from html</p>"}))
});
assert!(none.is_none());
}
#[test]
fn open_and_save_report_format_conversion_errors() {
let doc = wordcraft_doc::Document::from_text("hello");
wordcraft_formats::with_shared_conversion_error("bridge down", || {
for (name, bytes) in [("a.html", b"<p>hello</p>" as &[u8]), ("a.md", b"# hello"), ("a.tex", b"hello")] {
let err = crate::io::open_bytes(name, bytes).unwrap_err();
assert!(err.contains("bridge down"), "{name}: {err}");
}
for name in ["a.html", "a.md", "a.tex", "a.rtf"] {
let err = crate::io::save_bytes(name, &doc).unwrap_err();
assert!(err.contains("bridge down"), "{name}: {err}");
}
});
}
#[test]
fn opening_open_document_files_reports_section_conversion_errors_without_replacing_the_document() {
let incoming = wordcraft_doc::Document::from_text("Incoming document");
let message = "OpenDocument page conversion failed";
for name in ["incoming.odt", "incoming.ott", "incoming.fodt"] {
let bytes = crate::io::save_bytes(name, &incoming).unwrap();
let params = json!({"path": name, "data": crate::cmd::insert::base64_encode(&bytes)});
let mut s = Session::new(wordcraft_doc::Document::from_text("Keep this document"));
let id = s.document_id();
let err = wordcraft_formats::with_shared_conversion_error(message, || s.run("file.open", &params)).unwrap_err();
assert!(err.to_string().contains(message), "{name}: {err}");
assert_eq!(s.document_id(), id, "{name}");
assert_eq!(text(&s), "Keep this document", "{name}");
run(&mut s, "file.open", params);
assert_eq!(text(&s), "Incoming document", "{name}");
}
}
+37
View File
@@ -226,6 +226,27 @@ fn arrow_keys_move_visually_in_rtl_text() {
assert_eq!(s.sel.focus.off, b.off);
}
#[test]
fn arrow_keys_skip_hidden_deletions_in_rtl_text() {
let text = "אבגדה";
let mut s = session(text, true);
run(&mut s, "review.trackChanges", json!({"value": true}));
run(&mut s, "select.text", json!({"text": "בגד"}));
run(&mut s, "text.delete", json!({}));
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
for (command, from, to, direction) in [("caret.left", 0, text.len(), -1.0), ("caret.right", text.len(), 0, 1.0)] {
s.sel = crate::Selection::caret(Pos::body(0, from));
for _ in 0..2 {
let before = caret_x(&mut s);
run(&mut s, command, json!({}));
assert!((caret_x(&mut s) - before) * direction > 0.01, "{command} moves to the next visual stop");
assert!(s.sel.focus.off <= "א".len() || s.sel.focus.off >= "אבגד".len());
}
assert_eq!(s.sel.focus.off, to);
}
}
#[test]
fn arrow_keys_in_mixed_text_visit_each_position() {
// A left-to-right paragraph with a Persian word: Right walks across the screen.
@@ -253,6 +274,22 @@ fn word_moves_follow_reading_order() {
assert_eq!(s.sel.focus.off, 0);
}
#[test]
fn word_moves_skip_hidden_deletions_in_rtl_text() {
let mut s = session("אב גדה וז", true);
run(&mut s, "review.trackChanges", json!({"value": true}));
run(&mut s, "select.text", json!({"text": "גדה "}));
run(&mut s, "text.delete", json!({}));
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
let third_word = "אב גדה ".len();
s.sel = crate::Selection::caret(Pos::body(0, 0));
run(&mut s, "caret.wordLeft", json!({}));
assert_eq!(s.sel.focus.off, third_word, "Ctrl+Left skips the hidden deleted word in RTL text");
run(&mut s, "caret.wordRight", json!({}));
assert_eq!(s.sel.focus.off, 0, "Ctrl+Right skips back across the hidden deleted word in RTL text");
}
#[test]
fn typing_persian_keeps_logical_order() {
let mut s = session("", true);
+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
}
+31 -8
View File
@@ -179,34 +179,57 @@ fn fit_one_page_respects_max_delta() {
#[test]
fn fit_one_page_respects_step_pt() {
let at_11_4 = |lines: usize| {
let mut s = create_multiline_doc(lines);
let set_size = |s: &mut Session, size_pt: f32| {
for b in &mut s.doc.body {
if let wordcraft_doc::Block::Para(p) = std::sync::Arc::make_mut(b) {
p.mark.size = Some(11.4);
p.mark.size = Some(size_pt);
for r in &mut p.runs {
r.props.size = Some(11.4);
r.props.size = Some(size_pt);
}
}
}
s.touch();
s.relayout();
};
let at_size = |lines: usize, size_pt: f32| {
let mut s = create_multiline_doc(lines);
set_size(&mut s, size_pt);
s
};
let mut s = just_spilling(at_11_4);
// Find the most lines that fit on one page at 11.4 pt, spill the last paragraph at 11.1 pt
// so 0.1..0.3 pt reductions are not enough, then restore 11.4 pt so fitting requires 0.4 pt.
let mut lines = 10;
while at_size(lines + 1, 11.4).layout().pages.len() < 2 {
lines += 1;
assert!(lines < 120, "{lines} lines still fit on one page at 11.4 pt");
}
let mut s = at_size(lines, 11.1);
assert_eq!(s.layout().pages.len(), 1, "{lines} lines must fit on one page at 11.1 pt");
spill_last_paragraph(&mut s);
set_size(&mut s, 11.4);
assert_eq!(s.layout().pages.len(), 2, "must start as 2-page document at 11.4 pt");
assert_fixture_font(&mut s);
// Both calls hold maxDeltaPt constant at 0.4 and disable spacing adjustments.
// Hold maxDeltaPt constant at 0.4 and disable spacing adjustments.
// Default 0.5 pt step generates no candidates <= 0.4 pt, so it must fail.
let doc_backup = s.doc.clone();
let default_res = s.run("layout.fitOnePage", &json!({"maxDeltaPt": 0.4, "adjustSpacing": false}));
assert!(default_res.is_err(), "default step 0.5 must skip all candidates when maxDelta is 0.4");
// With stepPt = 0.1 under the same maxDeltaPt = 0.4, a fine-grained step (0.1 to 0.4 pt) succeeds.
// With stepPt = 0.1 and maxDeltaPt = 0.3, the document still spills onto page 2.
s.doc = doc_backup.clone();
s.touch();
let too_small_res = s.run("layout.fitOnePage", &json!({"maxDeltaPt": 0.3, "stepPt": 0.1, "adjustSpacing": false}));
assert!(too_small_res.is_err(), "0.3 pt cap must not recover a document needing 0.4 pt");
// With stepPt = 0.1 under maxDeltaPt = 0.4, the 0.4 pt boundary step (11.4 -> 11.0 pt) succeeds.
s.doc = doc_backup;
s.touch();
let res = s.run("layout.fitOnePage", &json!({"maxDeltaPt": 0.4, "stepPt": 0.1, "adjustSpacing": false}));
assert!(res.is_ok(), "stepPt=0.1 must generate fine-grained candidates under maxDelta 0.4: {res:?}");
assert!(res.is_ok(), "stepPt=0.1 must reach the 0.4 pt boundary step under maxDelta 0.4: {res:?}");
assert_eq!(s.layout().pages.len(), 1);
assert!(s.status.contains("font: -0.4 pt"), "expected 0.4 pt reduction in status, got: {}", s.status);
}
#[test]
+24
View File
@@ -6,6 +6,30 @@ use wordcraft_doc::Pos;
use crate::Session;
use crate::cmd::insert::base64_encode;
#[test]
fn format_state_reports_the_east_asian_theme_face_and_keeps_unresolved_and_mixed_controls() {
use std::sync::Arc;
use wordcraft_doc::props::ThemeFont;
use wordcraft_doc::{Document, Path, StoryRef};
let mut doc = Document::from_text("漢字");
Arc::make_mut(&mut doc.styles).default_chr.font_ea = Some("Times New Roman".into());
doc.para_mut(StoryRef::Body, &Path::top(0))
.unwrap()
.format(0, "漢".len(), &|props| props.font_ea_theme = Some(ThemeFont::MinorEastAsia))
.unwrap();
let mut fallback = Session::new(doc.clone());
fallback.run("select.all", &json!({})).unwrap();
assert_eq!(fallback.run("format.state", &json!({})).unwrap()["fontEastAsia"], "Times New Roman");
doc.passthrough.insert("wordcraft:theme.fonts".into(), Arc::new(b"minor\tface\tea\tExample CJK Face\n".to_vec()));
let mut s = Session::new(doc);
s.run("select.range", &json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, "漢".len())})).unwrap();
assert_eq!(s.run("format.state", &json!({})).unwrap()["fontEastAsia"], "Example CJK Face");
s.run("select.all", &json!({})).unwrap();
assert!(s.run("format.state", &json!({})).unwrap()["fontEastAsia"].is_null(), "the theme face and named face differ");
}
/// The bundled face `file` of family `original` renamed `family` (as long as `original`), so it
/// is a font the database doesn't have.
fn renamed(file: &str, original: &str, family: &str) -> Vec<u8> {
+347 -20
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.
@@ -1598,11 +1660,20 @@ fn a_new_selection_drops_the_formatting_left_after_a_link() {
#[test]
fn a_link_over_two_paragraphs_keeps_their_text() {
// Word shows <<Selection in Document>> for such a selection: the text to display is ignored.
// The caller is told the text was not applied, not left to think it was (#8541).
let mut s = typed("one\ntwo");
run(&mut s, "select.all", json!({}));
run(&mut s, "insert.link", json!({"url": "https://example.org/", "text": "both"}));
let r = s.run("insert.link", &json!({"url": "https://example.org/", "text": "both"})).unwrap();
assert_eq!(texts(&s), ["one", "two"]);
assert_eq!(links(&s), [("One".into(), false), ("two".into(), false)]);
let warning = r.get("warning").and_then(|w| w.as_str()).unwrap_or_default();
assert!(!warning.is_empty(), "the result says the text was kept: {r}");
assert_eq!(s.status, warning, "the status line says the same");
// Text to display left as the selection shows it is no change, so there is nothing to report.
let mut s = typed("go see kiln now");
run(&mut s, "select.text", json!({"text": "see"}));
let r = s.run("insert.link", &json!({"url": "https://example.org/", "text": "see"})).unwrap();
assert!(r.get("warning").is_none(), "{r}");
}
#[test]
@@ -2407,6 +2478,57 @@ fn arrow(s: &mut Session, key: &str) {
run(s, id, if extend { json!({"extend": true}) } else { json!({}) });
}
#[test]
fn arrow_keys_skip_wholly_deleted_paragraphs_in_no_markup() {
for (text, last) in [("AB\nCD\nEF", 2), ("AB\nCD\nDE\nEF", 3)] {
let mut s = typed(text);
let after_a = Pos::body(0, 1);
let before_f = Pos::body(last, 1);
run(&mut s, "review.trackChanges", json!({"value": true}));
run(&mut s, "select.range", json!({"anchor": after_a, "focus": before_f}));
run(&mut s, "text.delete", json!({}));
for i in 1..last {
let middle = s.doc.para_at(&Pos::body(i, 0)).unwrap();
assert!(middle.mark.del.is_some() && middle.runs.iter().all(|r| r.props.del.is_some()));
}
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
for (from, key, shift, across, next) in [
(after_a.clone(), "Right", "Shift+Right", Pos::body(last, 0), Pos::body(last, 2)),
(before_f.clone(), "Left", "Shift+Left", Pos::body(0, 2), Pos::body(0, 0)),
] {
run(&mut s, "caret.set", json!({"pos": from}));
arrow(&mut s, shift);
assert_eq!((&s.sel.anchor, &s.sel.focus), (&from, &across));
run(&mut s, "caret.set", json!({"pos": from}));
arrow(&mut s, key);
assert!(s.sel.is_collapsed());
assert_eq!(s.sel.focus, across);
arrow(&mut s, key);
assert_eq!(s.sel.focus, next);
}
run(&mut s, "review.markup", json!({"value": "allMarkup"}));
run(&mut s, "review.trackingOptions", json!({"balloons": "inline"}));
for (from, key, expected) in [(Pos::body(0, 2), "Right", Pos::body(1, 0)), (Pos::body(last, 0), "Left", Pos::body(last - 1, 2))] {
run(&mut s, "caret.set", json!({"pos": from}));
arrow(&mut s, key);
assert_eq!(s.sel.focus, expected);
}
}
}
#[test]
fn arrow_keys_stop_in_a_visible_empty_paragraph_in_no_markup() {
let mut s = typed("AB\n\nEF");
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
for (from, key) in [(Pos::body(0, 2), "Right"), (Pos::body(2, 0), "Left")] {
run(&mut s, "caret.set", json!({"pos": from}));
arrow(&mut s, key);
assert_eq!(s.sel.focus, Pos::body(1, 0));
}
}
/// The equation being edited and the caret in it.
fn editing(s: &Session) -> Option<(Pos, wordcraft_doc::math_edit::MathPos)> {
s.math.as_ref().map(|m| (m.at.clone(), m.pos.clone()))
@@ -2471,6 +2593,63 @@ fn left_and_right_keys_step_into_and_out_of_an_equation() {
assert_eq!((editing(&s), s.sel.anchor.clone(), s.sel.focus.clone()), (None, Pos::body(0, 1), Pos::body(0, 1)));
}
#[test]
fn arrow_keys_skip_a_deleted_equation_in_no_markup() {
let mut s = equations_between_a_and_b(1);
let before = Pos::body(0, 1);
let after = Pos::body(0, 1 + wordcraft_doc::para::OBJ.len_utf8());
run(&mut s, "review.trackChanges", json!({"value": true}));
run(&mut s, "select.range", json!({"anchor": before, "focus": after}));
run(&mut s, "text.delete", json!({}));
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
let end = Pos::body(0, after.off + 1);
for (from, key, expected) in [(before, "Right", end), (after, "Left", Pos::body(0, 0))] {
run(&mut s, "caret.set", json!({"pos": from}));
arrow(&mut s, key);
assert!(editing(&s).is_none(), "{key} must not open a hidden equation");
assert_eq!(s.sel.focus, expected);
}
}
#[test]
fn arrow_keys_enter_a_visible_equation_across_a_hidden_deletion() {
use wordcraft_doc::math_edit::{MathPos, units};
let equation_width = wordcraft_doc::para::OBJ.len_utf8();
let before = "a".len();
let after = "aé".len();
let end = MathPos::new(Vec::new(), units(&wordcraft_doc::math::parse_linear("x+y")));
for markup in ["noMarkup", "allMarkup"] {
for (key, shift_key, equation, from, across, math_pos) in [
("Right", "Shift+Right", after, before, after + equation_width, MathPos::default()),
("Left", "Shift+Left", before, after + equation_width, before, end.clone()),
] {
let mut s = typed("aéb");
let from = Pos::body(0, from);
let equation = Pos::body(0, equation);
run(&mut s, "caret.set", json!({"pos": equation}));
run(&mut s, "insert.equation", json!({"linear": "x+y", "edit": false}));
run(&mut s, "review.trackChanges", json!({"value": true}));
run(&mut s, "select.text", json!({"text": "é"}));
run(&mut s, "text.delete", json!({}));
run(&mut s, "review.markup", json!({"value": markup}));
if markup == "allMarkup" {
run(&mut s, "review.trackingOptions", json!({"balloons": "inline", "deleteMark": "hidden"}));
}
run(&mut s, "caret.set", json!({"pos": from}));
arrow(&mut s, shift_key);
assert!(editing(&s).is_none(), "{shift_key} extends the selection");
assert_eq!((s.sel.anchor.clone(), s.sel.focus.clone()), (from.clone(), Pos::body(0, across)));
run(&mut s, "caret.set", json!({"pos": from}));
arrow(&mut s, key);
assert_eq!(editing(&s), Some((equation, math_pos)), "{key} with {markup}");
}
}
}
#[test]
fn right_out_of_an_equation_steps_into_the_one_beside_it() {
let e = wordcraft_doc::para::OBJ.len_utf8();
@@ -2717,23 +2896,12 @@ fn typing_rtl_letters_into_an_empty_paragraph_makes_it_rtl() {
#[test]
fn select_all_then_delete_removes_tables() {
let tables = |s: &Session| s.doc.body.iter().filter(|b| b.as_table().is_some()).count();
// With the caret in a table, Select All grows the selection a step at a time (cell, row,
// table, document; #1478): press it until the whole document is selected.
let select_whole_document = |s: &mut Session| {
for _ in 0..6 {
let before = s.sel.clone();
run(s, "select.all", json!({}));
if s.sel == before {
break;
}
}
};
for key in ["text.delete", "text.backspace"] {
let mut s = typed("");
run(&mut s, "insert.table", json!({"rows": 2, "cols": 2}));
typ(&mut s, "cell");
assert_eq!(tables(&s), 1);
select_whole_document(&mut s);
run(&mut s, "select.all", json!({}));
run(&mut s, key, json!({}));
assert_eq!(tables(&s), 0, "{key}: a table at the start of the document goes");
assert_eq!(s.doc.plain_text(StoryRef::Body), "", "{key}");
@@ -2742,7 +2910,7 @@ fn select_all_then_delete_removes_tables() {
run(&mut s, "insert.table", json!({"rows": 2, "cols": 2}));
typ(&mut s, "cell");
assert_eq!(tables(&s), 1);
select_whole_document(&mut s);
run(&mut s, "select.all", json!({}));
run(&mut s, key, json!({}));
assert_eq!(tables(&s), 0, "{key}: a table after text goes");
assert_eq!(s.doc.plain_text(StoryRef::Body), "", "{key}");
@@ -3465,11 +3633,11 @@ fn autocorrect_capitalisation_follows_turkic_case_mapping() {
fn change_case_follows_turkic_case_mapping() {
for tag in ["tr-TR", "az-AZ", "crh"] {
for (mode, input, want) in [
("upper", "istanbul", "İSTANBUL"),
("lower", "IŞIK", "ışık"),
("title", "istanbul güzel", "İstanbul Güzel"),
("sentence", "istanbul. izmir", "İstanbul. İzmir"),
("toggle", "iI", "İı"),
("upper", "istanbul ışık", "İSTANBUL IŞIK"),
("lower", "İSTANBUL IŞIK", "istanbul ışık"),
("title", "istanbul ışık", "İstanbul Işık"),
("sentence", "istanbul. izmir. ışık.", "İstanbul. İzmir. Işık."),
("toggle", "iIİı", "İıiI"),
] {
let mut s = s();
run(&mut s, "review.language", json!({"lang": tag, "default": true}));
@@ -3481,11 +3649,27 @@ fn change_case_follows_turkic_case_mapping() {
}
// Other languages keep the Unicode default.
let mut s = self::s();
run(&mut s, "review.language", json!({"lang": "en-US", "default": true}));
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": "title"}));
assert_eq!(s.doc.plain_text(StoryRef::Body), "Istanbul", "en-US");
// Mixed runs: each run's own language decides.
for (mode, first, second, want) in [
("lower", "IŞIK ", "IŞIK", "ışık işik"),
("title", "istanbul ", "istanbul", "İstanbul Istanbul"),
("upper", "istanbul ", "istanbul", "İSTANBUL ISTANBUL"),
] {
let mut s = self::s();
run(&mut s, "review.language", json!({"lang": "tr-TR"}));
run(&mut s, "text.insert", json!({"text": first, "raw": true}));
run(&mut s, "review.language", json!({"lang": "en-US"}));
run(&mut s, "text.insert", json!({"text": second, "raw": true}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": mode}));
assert_eq!(s.doc.plain_text(StoryRef::Body), want, "mixed runs {mode}");
}
// Mixed runs tagged on selections within existing text: each run's own language decides.
let mut s = self::s();
run(&mut s, "text.insert", json!({"text": "IŞIK IŞIK", "raw": true}));
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 0)}));
@@ -3496,7 +3680,7 @@ fn change_case_follows_turkic_case_mapping() {
run(&mut s, "review.language", json!({"lang": "en-US"}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": "lower"}));
assert_eq!(s.doc.plain_text(StoryRef::Body), "ışık işik", "mixed runs");
assert_eq!(s.doc.plain_text(StoryRef::Body), "ışık işik", "mixed runs on selection");
}
// Spelling as you type (#1552): the word being typed gets no red squiggle until the caret leaves
@@ -4528,6 +4712,149 @@ fn issues_1281_1045_english_dialects_proof_typed_text() {
assert_eq!(words, ["21th"]);
}
/// #4281: Home › Numbering offers every preset, "a. b. c." among them, and picking another preset
/// for a list that is already numbered changes its style (only picking the same one again turns it off).
#[test]
fn the_numbering_gallery_presets_each_apply_and_switch_between_each_other() {
let labels = |s: &mut Session| numbers(s).into_iter().map(|(l, _)| l.unwrap_or_default()).collect::<Vec<_>>();
for (kind, want) in [
("numbered", ["1.", "2.", "3."]),
("numberedParen", ["1)", "2)", "3)"]),
("outline", ["I.", "II.", "III."]),
("upperLetter", ["A.", "B.", "C."]),
("lowerLetter", ["a)", "b)", "c)"]),
("lowerLetterDot", ["a.", "b.", "c."]),
("lowerRoman", ["i.", "ii.", "iii."]),
] {
let mut s = s();
typ(&mut s, "One\nTwo\nThree");
run(&mut s, "select.all", json!({}));
run(&mut s, "para.numbering", json!({"kind": kind}));
assert_eq!(labels(&mut s), want, "{kind}");
// Picking the same preset again turns the list off.
run(&mut s, "para.numbering", json!({"kind": kind}));
assert_eq!(labels(&mut s), ["", "", ""], "{kind} again");
}
// From one preset to another: the list changes style, it doesn't go off.
let mut s = s();
typ(&mut s, "One\nTwo\nThree");
run(&mut s, "select.all", json!({}));
run(&mut s, "para.numbering", json!({"kind": "numbered"}));
for (kind, want) in [("upperLetter", "A."), ("lowerLetterDot", "a."), ("lowerRoman", "i."), ("outline", "I."), ("numbered", "1.")] {
run(&mut s, "para.numbering", json!({"kind": kind}));
assert_eq!(labels(&mut s)[0], want, "to {kind}");
}
}
/// #4281: whatever level a list item is on, picking a different Numbering preset changes the list
/// and never turns it off; deeper levels of two presets can look alike.
#[test]
fn another_numbering_preset_never_switches_a_list_off_at_any_level() {
let kinds = ["numbered", "numberedParen", "outline", "upperLetter", "lowerLetter", "lowerLetterDot", "lowerRoman"];
for a in kinds {
for b in kinds.into_iter().filter(|b| *b != a) {
for level in 0..9 {
let mut s = s();
typ(&mut s, "One");
run(&mut s, "para.numbering", json!({"kind": a}));
run(&mut s, "para.listLevel", json!({"level": level}));
run(&mut s, "para.numbering", json!({"kind": b}));
let label = numbers(&mut s).into_iter().next().and_then(|(l, _)| l);
assert!(label.is_some(), "{a} -> {b} at level {level} turned the list off");
}
}
}
}
/// Where the first paragraph's list label starts (points from the page's text edge), and where its text starts.
fn label_and_text_x(s: &mut Session) -> (f32, f32) {
let l = s.layout();
l.pages
.iter()
.flat_map(|p| &p.items)
.find_map(|i| {
if let wordcraft_layout::Placed::Lines { para, l0: 0, .. } = i {
// The text starts where the first cluster is placed, after the label's suffix or tab stop.
para.label.as_ref().and_then(|lb| para.lines.first().and_then(|line| line.xs.first().map(|&x| (lb.x, x))))
} else {
None
}
})
.expect("a list label")
}
/// #4287: changing a list item's level (Change List Level, Tab, Shift+Tab) puts it at the new level's
/// indent, also when it carried a direct indent (a ruler drag, a pasted block, a Word file's `w:ind`).
#[test]
fn changing_a_list_level_drops_a_direct_indent() {
// The reference: a fresh list item moved to level 2 with no direct indent in the way.
let fresh = |command: &str, params: serde_json::Value| {
let mut s = s();
typ(&mut s, "Item");
run(&mut s, "para.numbering", json!({"kind": "upperLetter"}));
run(&mut s, command, params);
label_and_text_x(&mut s)
};
let dragged = |command: &str, params: serde_json::Value| {
let mut s = s();
typ(&mut s, "Item");
run(&mut s, "para.numbering", json!({"kind": "upperLetter"}));
// The ruler's left-indent marker dragged to a custom place.
run(&mut s, "para.indents", json!({"left": 120.0, "firstLine": -6.0}));
run(&mut s, command, params);
label_and_text_x(&mut s)
};
for (command, params) in [("para.listLevel", json!({"level": 1})), ("para.indent", json!({}))] {
assert_eq!(dragged(command, params.clone()), fresh(command, params), "{command}");
}
// Tab at the start of the item takes it down a level the same way.
let tabbed = |drag: bool| {
let mut s = s();
typ(&mut s, "Item");
run(&mut s, "para.numbering", json!({"kind": "upperLetter"}));
if drag {
run(&mut s, "para.indents", json!({"left": 120.0, "firstLine": -6.0}));
}
run(&mut s, "caret.home", json!({}));
run(&mut s, "text.tab", json!({}));
label_and_text_x(&mut s)
};
assert_eq!(tabbed(true), tabbed(false), "text.tab");
// Shift+Tab takes it back up.
let backtabbed = |drag: bool| {
let mut s = s();
typ(&mut s, "Item");
run(&mut s, "para.numbering", json!({"kind": "upperLetter"}));
run(&mut s, "para.listLevel", json!({"level": 1}));
if drag {
run(&mut s, "para.indents", json!({"left": 200.0, "firstLine": -30.0}));
}
run(&mut s, "text.backTab", json!({}));
label_and_text_x(&mut s)
};
assert_eq!(backtabbed(true), backtabbed(false), "text.backTab");
// Back out (Shift+Tab) from level 2 to 1 as well.
let back = |drag: bool| {
let mut s = s();
typ(&mut s, "Item");
run(&mut s, "para.numbering", json!({"kind": "upperLetter"}));
run(&mut s, "para.listLevel", json!({"level": 1}));
if drag {
run(&mut s, "para.indents", json!({"left": 200.0, "firstLine": -30.0}));
}
run(&mut s, "para.outdent", json!({}));
label_and_text_x(&mut s)
};
assert_eq!(back(true), back(false), "para.outdent");
// A ruler drag with no level change sticks.
let mut s = s();
typ(&mut s, "Item");
run(&mut s, "para.numbering", json!({"kind": "upperLetter"}));
let before = label_and_text_x(&mut s);
run(&mut s, "para.indents", json!({"left": 120.0, "firstLine": -6.0}));
assert_ne!(label_and_text_x(&mut s), before, "the drag moves the item");
}
/// #6788: Enter in a paragraph with a drop cap makes a normal paragraph; only the first keeps
/// the cap (Word behaviour), for a dropped cap and one in the margin.
#[test]
-33
View File
@@ -183,18 +183,6 @@ fn german_date_fields_inherit_the_document_default_language() {
}
}
/// `MMM` and `ddd` use Word's Windows NLS short forms for German: two-letter weekdays (`So`,
/// `Mo`…) and `Mrz` for March, with no trailing full stop (#7146).
#[test]
fn a_german_short_date_field_uses_windows_nls_abbreviations() {
const PICTURE: &str = "ddd, d. MMM yyyy";
let d = open_body_in_lang("de-DE", &format!("<w:p>{}</w:p>", field(&format!(r#"DATE \@ "{PICTURE}""#), "Wed, 1 Jan 2020", false)));
let got = fields(&d);
assert_eq!(got[0].1, wordcraft_engine::cmd::insert::format_date_in(PICTURE, Some("de-DE")));
// The abbreviations at a fixed date, independent of when the test runs.
assert_eq!(wordcraft_engine::cmd::insert::format_date_parts_in(PICTURE, Some("de-DE"), 2026, 3, 15, (12, 0, 0), 3), "So, 15. Mrz 2026");
}
/// A `TIME` field whose picture carries German name tokens inherits the language too, so the
/// English result cached in the fixture is replaced with German weekday and month names.
#[test]
@@ -207,27 +195,6 @@ fn a_german_time_field_uses_german_names() {
assert_eq!(got[0].1, wordcraft_engine::cmd::insert::format_date_in(PICTURE, Some("de-DE")));
}
/// Austrian Standard German writes January as `Jänner` (`Jän`), while Germany, Switzerland and
/// bare `de` keep `Januar` (`Jan`), as in Windows NLS (#7146). A `de-AT` document reads German
/// through `docDefaults`; the refresh always uses the real clock, so the January names are asked
/// of the same formatter at a fixed January instant.
#[test]
fn austrian_german_documents_use_jaenner() {
const PICTURE: &str = "dddd, d. MMMM yyyy";
let d = open_body_in_lang("de-AT", &format!("<w:p>{}</w:p>", field(&format!(r#"DATE \@ "{PICTURE}""#), "Wednesday, 1 January 2020", false)));
let got = fields(&d);
assert_eq!(got[0].1, wordcraft_engine::cmd::insert::format_date_in(PICTURE, Some("de-AT")), "an Austrian document reads German");
let january = |lang: &str, picture: &str| wordcraft_engine::cmd::insert::format_date_parts_in(picture, Some(lang), 2026, 1, 15, (12, 0, 0), 0);
assert_eq!(january("de-AT", "MMMM"), "Jänner");
assert_eq!(january("de-AT", "MMM"), "Jän");
assert_eq!(january("de-AT", PICTURE), "Donnerstag, 15. Jänner 2026");
for lang in ["de-DE", "de-CH", "de"] {
assert_eq!(january(lang, "MMMM"), "Januar", "{lang}");
assert_eq!(january(lang, "MMM"), "Jan", "{lang}");
}
}
/// A minimal Word 97-2003 file whose only paragraph holds a `DATE` field cached as " 2001":
/// FIB, one compressed text piece, and the Clx that points at it.
fn binary_doc_with_stale_date() -> Vec<u8> {
+11
View File
@@ -224,6 +224,17 @@ impl FontDb {
log::debug!("cataloged {n} system font faces");
*self.catalog.write().unwrap_or_else(std::sync::PoisonError::into_inner) = found;
self.catalog_gen.fetch_add(1, Ordering::AcqRel);
{
let mut sys = self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
sys.tried.clear();
sys.misses.clear();
}
self.fallbacks.write().unwrap_or_else(std::sync::PoisonError::into_inner).map.clear();
{
let mut rf = self.run_fallbacks.write().unwrap_or_else(std::sync::PoisonError::into_inner);
rf.map.clear();
rf.chars = 0;
}
n
}
+4 -7
View File
@@ -82,12 +82,12 @@ pub struct FontFace {
/// than the full-width figure in the table. Word's automatic spacing between East Asian and
/// Latin text is half of it (see `wordcraft_layout::para::grid::auto_space`).
pub avg_char_width: f64,
pub shaper: harfrust::ShaperData,
/// Variable fonts: the named instance's axis settings (user units; empty = default instance),
/// the normalised location and the shaper's view of it.
/// The shaper's view of the face, at the named instance's location for variable fonts.
pub hb: harfrust::Font,
/// Variable fonts: the named instance's axis settings (user units; empty = default instance)
/// and the normalised location.
pub coords: Vec<([u8; 4], f32)>,
pub(super) location: Location,
pub instance: Option<harfrust::ShaperInstance>,
/// Basic Multilingual Plane coverage bitset, built on first use.
pub(super) bmp: std::sync::OnceLock<Box<[u64]>>,
// Some legacy CJK fonts assemble their contours with TrueType instructions.
@@ -205,9 +205,6 @@ impl FontFace {
pub fn skrifa(&self) -> Option<skrifa::FontRef<'_>> {
skrifa::FontRef::from_index(self.data(), self.index).ok()
}
pub fn hb(&self) -> Option<harfrust::FontRef<'_>> {
harfrust::FontRef::from_index(self.data(), self.index).ok()
}
/// Where in the design space glyphs, metrics and outlines come from.
pub fn location(&self) -> LocationRef<'_> {
(&self.location).into()
+1 -1
View File
@@ -98,7 +98,7 @@ impl FontDb {
#[cfg(not(target_arch = "wasm32"))]
{
let enabled = self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).enabled;
if enabled {
if enabled && self.family_maps(FAMILY, c) {
self.load_cataloged(FAMILY);
}
}
+7 -6
View File
@@ -418,10 +418,12 @@ pub(super) fn make_face(
let location = if coords.is_empty() { Location::default() } else { f.axes().location(settings.iter().copied()) };
let m = f.metrics(Size::unscaled(), &location);
let a = f.attributes();
let hb = harfrust::FontRef::from_index(data, index).ok()?;
let shaper = harfrust::ShaperData::new(&hb);
let instance = (!coords.is_empty())
.then(|| harfrust::ShaperInstance::from_variations(&hb, settings.iter().map(|(t, v)| harfrust::Variation { tag: *t, value: *v })));
let source: harfrust::font::Source = match &bytes {
FontBytes::Static(b) => (*b).into(),
FontBytes::Owned(v) => (v.clone() as Arc<dyn AsRef<[u8]> + Send + Sync>).into(),
};
let hb = harfrust::Font::new(source, index)?;
let hb = if coords.is_empty() { hb } else { hb.instance_builder().variations(coords.iter().map(|(t, v)| (harfrust::Tag::new(t), *v))).build() };
let axis = |tag: &[u8; 4]| coords.iter().find(|(t, _)| t == tag).map(|(_, v)| *v);
// Old releases of heavy faces (Arial Black in the core fonts) claim weight 400 where current
// ones say 900, which Word doesn't embolden: a family named for its weight is that heavy.
@@ -447,10 +449,9 @@ pub(super) fn make_face(
cap_height: m.cap_height.map(|v| v as f64).filter(|v| *v > 0.0).unwrap_or(m.ascent as f64 * 0.72),
x_height: m.x_height.map(|v| v as f64).filter(|v| *v > 0.0).unwrap_or(m.ascent as f64 * 0.5),
avg_char_width: avg_char_width(&f, upem),
shaper,
hb,
coords,
location,
instance,
bytes,
index,
bmp: std::sync::OnceLock::new(),
+33
View File
@@ -1018,6 +1018,39 @@ fn catalog_postscript_names() {
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn cataloged_family_without_glyph_is_not_loaded_by_fallback_and_rescan_clears_misses() {
struct Cleanup(std::path::PathBuf);
impl Drop for Cleanup {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
let dir = std::env::temp_dir().join(format!("wc-sysfonts-{}-cmap-skip-and-rescan", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let _cleanup = Cleanup(dir.clone());
// SourceSerif4-Regular lacks '●' (\u{25CF}): cataloging it under Times New Roman and Arial
// must not cause circle_fallback or system_fallback to load those families when searching for '●'.
std::fs::write(dir.join("TNR.ttf"), named_face("SourceSerif4-Regular.ttf", "Times New Roman")).unwrap();
std::fs::write(dir.join("Arial.ttf"), named_face("SourceSerif4-Regular.ttf", "Arial")).unwrap();
let db = FontDb::with_font_dirs(vec![dir.clone()]);
db.faces.write().unwrap().retain(|face| face.family == "Source Serif 4");
let primary = db.face("Source Serif 4", "Regular");
assert!(db.fallback_for('●', primary.id()).is_none(), "no loaded or cataloged face covers '●'");
assert!(!db.is_loaded("Times New Roman"), "circle_fallback must skip Times New Roman when its cmap lacks '●'");
assert!(!db.is_loaded("Arial"), "system_fallback must skip Arial when its cmap lacks '●'");
// Populate sys.tried before rescanning; replacing Arial.ttf in place with a covering face and
// rescanning clears sys.tried, cached misses, and stale file coverage ranges.
db.sys.lock().unwrap().tried.insert("Arial");
std::fs::write(dir.join("Arial.ttf"), named_face("SourceSans3-Regular.ttf", "Arial")).unwrap();
db.load_system_fonts();
assert!(db.sys.lock().unwrap().tried.is_empty(), "rescan clears sys.tried");
let resolved = db.fallback_for('●', primary.id()).expect("rescan drops cached miss and reloads replaced Arial.ttf");
assert_eq!(resolved.family, "Arial");
}
/// Diagram fallback matches the primary font's serif/sans classification while body-text
/// fallback preserves loaded order (#5672), and changing user fonts invalidates run fallbacks.
#[test]
+67 -53
View File
@@ -20,7 +20,7 @@ pub use fontdb::{
base_style, bundled, bundled_inter, decode_font_file, is_font_file_name, name_language_matches, sniff, system_font_dirs,
};
pub use harfrust::Feature;
use harfrust::{Direction, ShapeOptions, ShapePlan, ShapePlanKey, Shaper, Tag, UnicodeBuffer};
use harfrust::{Buffer, Direction, ShapeOptions, ShapePlan, ShapePlanKey, ShaperFont, Tag};
pub use kurbo::BezPath;
pub use script::{fallback_rank, is_emoji, joins_cursively, needs_layout_tables, script_fallbacks};
use skrifa::MetadataProvider;
@@ -202,50 +202,53 @@ fn shape_dir(
around: ShapeContext<'_>,
) -> Vec<ShapedGlyph> {
let mut out = Vec::with_capacity(text.len());
let shaped = face.hb().map(|hb| {
let shaper = face.shaper.shaper(&hb).instance(face.instance.as_ref()).build();
// One script per shaping call: the shaper picks its script engine (Myanmar, Khmer,
// Indic, USE reordering…) from the run's script, so "Hi မြန်မာ" in one face must not be
// shaped as Latin. Runs come in text order; right-to-left callers regroup by cluster.
for r in script::script_runs(text) {
let Some(sub) = text.get(r.clone()) else { continue };
let mut buf = UnicodeBuffer::new();
for (i, c) in sub.char_indices() {
buf.add(map(c), (r.start + i) as u32);
}
// After the text: adding to a buffer clears what follows it.
let around = around.at_edges_of(text, &r);
buf.set_pre_context(around.before);
buf.set_post_context(around.after);
buf.guess_segment_properties();
buf.set_direction(if rtl { Direction::RightToLeft } else { Direction::LeftToRight });
let plan = shape_plan(face, &shaper, &buf, features);
let gb = shaper.shape(buf, ShapeOptions::new().plan(plan.as_deref()).features(features));
for (info, pos) in gb.glyph_infos().iter().zip(gb.glyph_positions()) {
out.push(ShapedGlyph {
gid: info.glyph_id,
cluster: info.cluster as usize,
x_advance: pos.x_advance,
x_offset: pos.x_offset,
y_offset: pos.y_offset,
});
}
let sf = ShaperFont::new(&face.hb);
// One script per shaping call: the shaper picks its script engine (Myanmar, Khmer,
// Indic, USE reordering…) from the run's script, so "Hi မြန်မာ" in one face must not be
// shaped as Latin. Runs come in text order; right-to-left callers regroup by cluster.
for r in script::script_runs(text) {
let Some(sub) = text.get(r.clone()) else { continue };
let mut buf = Buffer::new();
for (i, c) in sub.char_indices() {
buf.push(map(c) as u32, (r.start + i) as u32);
}
});
if shaped.is_none()
&& let Some(f) = face.skrifa()
{
let cmap = f.charmap();
let gm = f.glyph_metrics(Size::unscaled(), face.location());
for (i, c) in text.char_indices() {
let g = cmap.map(map(c)).unwrap_or_default();
let adv = gm.advance_width(g).unwrap_or(face.upem as f32 * 0.5);
out.push(ShapedGlyph { gid: g.to_u32(), cluster: i, x_advance: adv.round() as i32, x_offset: 0, y_offset: 0 });
// After the text: adding to a buffer clears what follows it.
let around = around.at_edges_of(text, &r);
buf.set_pre_context(around.before);
buf.set_post_context(around.after);
buf.guess_segment_properties();
buf.set_direction(if rtl { Direction::RightToLeft } else { Direction::LeftToRight });
let plan = shape_plan(face, &buf, features);
// A run that exhausts the shaper's budget returns Ok with an incomplete buffer.
if harfrust::shape(&sf, &mut buf, ShapeOptions::new().plan(plan.as_deref()).features(features)).is_err() || !buf.allocation_successful() {
cmap_glyphs(face, sub, r.start, map, &mut out);
continue;
}
for (info, pos) in buf.glyph_infos().iter().zip(buf.glyph_positions()) {
out.push(ShapedGlyph {
gid: info.glyph_id,
cluster: info.cluster as usize,
x_advance: pos.x_advance,
x_offset: pos.x_offset,
y_offset: pos.y_offset,
});
}
}
out
}
/// One glyph per character straight from the cmap, for a run the shaper could not do.
fn cmap_glyphs(face: &FontFace, text: &str, base: usize, map: &impl Fn(char) -> char, out: &mut Vec<ShapedGlyph>) {
let Some(f) = face.skrifa() else { return };
let cmap = f.charmap();
let gm = f.glyph_metrics(Size::unscaled(), face.location());
for (i, c) in text.char_indices() {
let g = cmap.map(map(c)).unwrap_or_default();
let adv = gm.advance_width(g).unwrap_or(face.upem as f32 * 0.5);
out.push(ShapedGlyph { gid: g.to_u32(), cluster: base + i, x_advance: adv.round() as i32, x_offset: 0, y_offset: 0 });
}
}
/// How many shape plans each thread keeps: the oldest is dropped to make room, so a thread never
/// holds more than this many, whatever fonts, scripts and feature sets it shapes.
const MAX_SHAPE_PLANS: usize = 64;
@@ -279,22 +282,22 @@ thread_local! {
/// oldest dropped past [`MAX_SHAPE_PLANS`]). A kept plan is used only for the same face and when
/// harfrust's own [`ShapePlanKey::matches`] accepts it (script, direction, language, the face's
/// variation instance and the features). `None` leaves making it to the shaper.
fn shape_plan(face: &FontFace, shaper: &Shaper, buf: &UnicodeBuffer, features: &[Feature]) -> Option<std::rc::Rc<ShapePlan>> {
fn shape_plan(face: &FontFace, buf: &Buffer, features: &[Feature]) -> Option<std::rc::Rc<ShapePlan>> {
// The buffer's script is unset when it reads as unknown: the guess never sets that.
let script = Some(buf.script()).filter(|s| *s != harfrust::script::UNKNOWN);
let script = buf.script().filter(|s| *s != harfrust::Script::UNKNOWN);
let language = buf.language();
let direction = buf.direction();
if direction == Direction::Invalid {
return None;
}
let key = ShapePlanKey::new(script, direction).language(language.as_ref()).instance(face.instance.as_ref()).features(features);
let key = ShapePlanKey::new(&face.hb, script, direction).language(language).features(features);
let of = PlanFace::of(face);
SHAPE_PLANS.with(|cell| {
let mut plans = cell.try_borrow_mut().ok()?;
if let Some((_, plan)) = plans.iter().find(|(f, plan)| *f == of && key.matches(plan)) {
return Some(plan.clone());
}
let plan = std::rc::Rc::new(ShapePlan::new(shaper, direction, script, language.as_ref(), features));
let plan = std::rc::Rc::new(ShapePlan::new(&face.hb, direction, script, language, features));
if plans.len() >= MAX_SHAPE_PLANS {
plans.remove(0);
}
@@ -359,14 +362,14 @@ mod tests {
#[test]
fn kept_shape_plans_shape_as_fresh_ones() {
let fresh = |face: &FontFace, text: &str, features: &[Feature], rtl: bool| -> Vec<(u32, u32, i32, i32, i32)> {
let Some(hb) = face.hb() else { return Vec::new() };
let shaper = face.shaper.shaper(&hb).instance(face.instance.as_ref()).build();
let mut buf = UnicodeBuffer::new();
let mut buf = Buffer::new();
buf.push_str(text);
buf.guess_segment_properties();
buf.set_direction(if rtl { Direction::RightToLeft } else { Direction::LeftToRight });
let gb = shaper.shape(buf, ShapeOptions::new().features(features));
gb.glyph_infos().iter().zip(gb.glyph_positions()).map(|(i, p)| (i.glyph_id, i.cluster, p.x_advance, p.x_offset, p.y_offset)).collect()
if harfrust::shape(&ShaperFont::new(&face.hb), &mut buf, ShapeOptions::new().features(features)).is_err() {
return Vec::new();
}
buf.glyph_infos().iter().zip(buf.glyph_positions()).map(|(i, p)| (i.glyph_id, i.cluster, p.x_advance, p.x_offset, p.y_offset)).collect()
};
let kept = |face: &FontFace, text: &str, features: &[Feature], rtl: bool| -> Vec<(u32, u32, i32, i32, i32)> {
shape_dir(face, text, features, &|c| c, rtl, ShapeContext::default())
@@ -395,14 +398,14 @@ mod tests {
fn kept_shape_plans_are_bounded() {
let face = FontDb::global().face(DEFAULT_FAMILY, "Regular");
let fresh = |features: &[Feature], rtl: bool| -> Vec<(u32, i32)> {
let Some(hb) = face.hb() else { return Vec::new() };
let shaper = face.shaper.shaper(&hb).instance(face.instance.as_ref()).build();
let mut buf = UnicodeBuffer::new();
let mut buf = Buffer::new();
buf.push_str("office");
buf.guess_segment_properties();
buf.set_direction(if rtl { Direction::RightToLeft } else { Direction::LeftToRight });
let gb = shaper.shape(buf, ShapeOptions::new().features(features));
gb.glyph_infos().iter().zip(gb.glyph_positions()).map(|(i, p)| (i.glyph_id, p.x_advance)).collect()
if harfrust::shape(&ShaperFont::new(&face.hb), &mut buf, ShapeOptions::new().features(features)).is_err() {
return Vec::new();
}
buf.glyph_infos().iter().zip(buf.glyph_positions()).map(|(i, p)| (i.glyph_id, p.x_advance)).collect()
};
for n in 0..3 * MAX_SHAPE_PLANS as u32 {
let features = [feature_value(b"kern", n % 2), feature_value(b"liga", n)];
@@ -415,6 +418,17 @@ mod tests {
assert_eq!(kept_shape_plans(), MAX_SHAPE_PLANS);
}
/// The cmap fallback for a failed run gives one glyph per character, its clusters offset by
/// where the run starts in the text.
#[test]
fn cmap_fallback_keeps_cluster_offsets() {
let face = FontDb::global().face(DEFAULT_FAMILY, "Regular");
let mut out = Vec::new();
cmap_glyphs(&face, "ab", 5, &|c| c, &mut out);
assert_eq!(out.iter().map(|g| g.cluster).collect::<Vec<_>>(), [5, 6]);
assert!(out.iter().all(|g| g.gid != 0 && g.x_advance > 0));
}
#[test]
fn ligatures_can_be_disabled() {
let face = FontDb::global().face(DEFAULT_FAMILY, "Regular");
+4 -3
View File
@@ -122,7 +122,8 @@ const COLOR_EMOJI: &[&str] = &["Segoe UI Emoji", "Apple Color Emoji", "Noto Colo
pub fn is_emoji(c: char) -> bool {
matches!(
u32::from(c),
0x1F000..=0x1FAFF
0x1F000..=0x1F7FF
| 0x1F900..=0x1FAFF
| 0x231A..=0x231B
| 0x23E9..=0x23EC
| 0x23F0
@@ -210,8 +211,8 @@ mod tests {
assert!(fallback_rank(c, "Segoe UI Emoji") < fallback_rank(c, "Segoe UI Symbol"), "{c}");
assert!(fallback_rank(c, "Noto Color Emoji") < fallback_rank(c, "Noto Emoji"), "{c}");
}
// Text-style symbols keep the symbol fonts.
for c in ['✔', '☺', '→', 'a', '1'] {
// Text-style symbols keep the symbol fonts, including Supplemental Arrows-C.
for c in ['✔', '☺', '→', '\u{1F86A}', 'a', '1'] {
assert!(!is_emoji(c), "{c}");
}
}
+4 -2
View File
@@ -9,8 +9,10 @@ description = "WordCraft import/export: plain text, Markdown, HTML, RTF, OpenDoc
workspace = true
[features]
# `sheet::xls_fixture`, the binary workbook builder other crates' tests share; turned on only as a
# dev-dependency, so never built into the app.
# Test helpers shared with other crates: `sheet::xls_fixture` (binary workbook builder via
# `craft-xls/test-support`) and `with_shared_conversion_error` / `with_shared_conversion_error_after`,
# which wire thread-local forced-failure hooks into `to_shared` and `from_shared`. Never enable
# outside dev-dependencies, so those hooks are never built into the app.
test-support = ["craft-xls/test-support"]
[dependencies]
+59
View File
@@ -28,17 +28,76 @@ use wordcraft_doc::Document;
/// (`wordcraft_docx::package::MAX_ENTRIES`); checked before `zip` parses them (#3660).
pub const MAX_ZIP_ENTRIES: u64 = 20_000;
#[cfg(any(test, feature = "test-support"))]
thread_local! {
/// `(skip, repeat, message)`: when `Some`, lets `skip` calls to `to_shared` / `from_shared`
/// run normally, then fails the next call with `message` (and every subsequent call when
/// `repeat` is `true`).
static SHARED_ERROR: std::cell::Cell<Option<(usize, bool, &'static str)>> = const { std::cell::Cell::new(None) };
}
#[cfg(any(test, feature = "test-support"))]
fn take_shared_error() -> Option<String> {
SHARED_ERROR.with(|slot| {
let (skip, repeat, msg) = slot.get()?;
if skip > 0 {
slot.set(Some((skip - 1, repeat, msg)));
None
} else {
if !repeat {
slot.set(None);
}
Some(msg.to_string())
}
})
}
#[cfg(any(test, feature = "test-support"))]
fn with_shared_error_state<T>(state: Option<(usize, bool, &'static str)>, f: impl FnOnce() -> T) -> T {
struct Reset(Option<(usize, bool, &'static str)>);
impl Drop for Reset {
fn drop(&mut self) {
SHARED_ERROR.with(|slot| slot.set(self.0));
}
}
let prev = SHARED_ERROR.with(|slot| slot.replace(state));
let _reset = Reset(prev);
f()
}
/// Simulates a `to_shared` / `from_shared` conversion failure for every call inside `f`.
#[cfg(any(test, feature = "test-support"))]
#[doc(hidden)]
pub fn with_shared_conversion_error<T>(msg: &'static str, f: impl FnOnce() -> T) -> T {
with_shared_error_state(Some((0, true, msg)), f)
}
/// Lets `skip` `to_shared` / `from_shared` conversions run normally, then fails the next one once.
#[cfg(any(test, feature = "test-support"))]
#[doc(hidden)]
pub fn with_shared_conversion_error_after<T>(skip: usize, msg: &'static str, f: impl FnOnce() -> T) -> T {
with_shared_error_state(Some((skip, false, msg)), f)
}
/// The document as the shared model the format crates read and write.
///
/// A conversion that fails is an error, never an empty document or an empty file: the caller
/// says so instead of writing a file with nothing in it.
pub(crate) fn to_shared(doc: &Document) -> Result<craft_wordmodel::Document, String> {
#[cfg(any(test, feature = "test-support"))]
if let Some(err) = take_shared_error() {
return Err(err);
}
wordcraft_docx::to_shared_model(doc).map_err(|e| e.to_string())
}
/// The shared model as the app's document model. A conversion that fails is an error, never
/// an empty document.
pub(crate) fn from_shared(shared: craft_wordmodel::Document) -> Result<Document, String> {
#[cfg(any(test, feature = "test-support"))]
if let Some(err) = take_shared_error() {
return Err(err);
}
wordcraft_docx::from_shared_model(shared).map_err(|e| e.to_string())
}
+4 -8
View File
@@ -4,17 +4,13 @@ use std::sync::Arc;
use wordcraft_doc::{Block, Document, SectionProps};
use crate::shared_section;
pub use craft_odf::text::{CryptError, TEMPLATE_MIME, TEXT_MIME, decrypt, encrypt, is_encrypted};
/// Text room, points, that header and footer bands leave on a page (as Page Setup's margins must).
const MIN_TEXT_ROOM: f32 = 36.0;
fn shared_section(page: &SectionProps) -> craft_wordmodel::SectionProps {
let mut d = Document::new();
d.last_section = page.clone();
wordcraft_docx::to_shared_model(&d).map(|s| s.last_section).unwrap_or_default()
}
/// A shared document opened as a WordCraft one, its pages keeping the text room the header and
/// footer bands leave ([`keep_text_room`]).
fn from_shared(shared: craft_wordmodel::Document) -> Result<Document, String> {
@@ -69,7 +65,7 @@ pub fn import(bytes: &[u8]) -> Result<Document, String> {
}
pub fn import_on(bytes: &[u8], page: &SectionProps) -> Result<Document, String> {
from_shared(craft_odf::text::import_on(bytes, &shared_section(page))?)
from_shared(craft_odf::text::import_on(bytes, &shared_section(page)?)?)
}
pub fn import_flat(bytes: &[u8]) -> Result<Document, String> {
@@ -77,7 +73,7 @@ pub fn import_flat(bytes: &[u8]) -> Result<Document, String> {
}
pub fn import_flat_on(bytes: &[u8], page: &SectionProps) -> Result<Document, String> {
from_shared(craft_odf::text::import_flat_on(bytes, &shared_section(page))?)
from_shared(craft_odf::text::import_flat_on(bytes, &shared_section(page)?)?)
}
/// The shared model an OpenDocument file is written from. ODF's `dc:date` is an instant (a `Z`
+96
View File
@@ -338,6 +338,74 @@ fn a_format_that_cannot_be_read_is_an_error_not_a_blank_document() {
assert!(e.contains("RTF"), "{e}");
}
/// Every HTML, Markdown, LaTeX, RTF and MHT importer and exporter propagates `to_shared` /
/// `from_shared` errors instead of falling back to an empty document or empty string.
#[test]
fn shared_conversion_errors_propagate_through_all_formats_without_empty_fallback() {
let doc = sample();
let page = wordcraft_doc::SectionProps::default();
let mht_bytes = b"MIME-Version: 1.0\r\nContent-Type: multipart/related; boundary=\"b\"\r\n\r\n--b\r\nContent-Type: text/html\r\n\r\n<p>hello</p>\r\n--b--\r\n";
let msg = "simulated shared conversion failure";
let assert_err = |res: Result<String, String>, label: &str| {
let e = res.unwrap_err();
assert!(e.contains(msg), "{label}: {e}");
};
crate::with_shared_conversion_error(msg, || {
assert_err(crate::html::import("<p>hello</p>").map(|_| String::new()), "html::import");
assert_err(crate::html::import_page("<p>hello</p>", &|_| None).map(|_| String::new()), "html::import_page");
assert_err(crate::html::import_with("<p>hello</p>", &|_| None).map(|_| String::new()), "html::import_with");
assert_err(crate::html::import_on("<p>hello</p>", &|_| None, &page).map(|_| String::new()), "html::import_on (section)");
assert_err(crate::html::export(&doc), "html::export");
assert_err(crate::html::export_fragment(&doc), "html::export_fragment");
assert_err(crate::markdown::import("hello").map(|_| String::new()), "markdown::import");
assert_err(crate::markdown::import_on("hello", &page).map(|_| String::new()), "markdown::import_on (section)");
assert_err(crate::markdown::import_on_with_lines("hello", &page).map(|_| String::new()), "markdown::import_on_with_lines (section)");
assert_err(crate::markdown::export(&doc), "markdown::export");
assert_err(crate::latex::import(b"hello").map(|_| String::new()), "latex::import");
assert_err(crate::latex::import_on(b"hello", &page).map(|_| String::new()), "latex::import_on");
assert_err(crate::latex::export(&doc), "latex::export");
assert_err(crate::rtf::import(br"{\rtf1 hello}").map(|_| String::new()), "rtf::import");
assert_err(crate::rtf::export(&doc), "rtf::export");
assert_err(crate::mht::import(mht_bytes).map(|_| String::new()), "mht::import (section)");
assert_err(crate::mht::import_on(mht_bytes, &page).map(|_| String::new()), "mht::import_on (section)");
for (ext, bytes) in [("html", b"<p>hello</p>" as &[u8]), ("md", b"hello"), ("tex", b"hello"), ("rtf", br"{\rtf1 hello}"), ("mht", mht_bytes)]
{
assert_err(import(ext, bytes).unwrap().map(|_| String::new()), &format!("import({ext})"));
assert_err(crate::import_on(ext, bytes, &page).unwrap().map(|_| String::new()), &format!("import_on({ext})"));
}
for ext in ["html", "md", "tex", "rtf"] {
assert_err(export(ext, &doc).unwrap().map(|_| String::new()), &format!("export({ext})"));
assert_err(
crate::export_with(ext, &doc, &crate::ExportOptions { comments: true }).unwrap().map(|_| String::new()),
&format!("export_with({ext})"),
);
}
});
// For `import_on` helpers that first convert `page` via `shared_section`, also verify that
// a `from_shared` failure after `shared_section` succeeds still propagates as an error.
for (label, res) in [
(
"html::import_on (from_shared)",
crate::with_shared_conversion_error_after(1, msg, || crate::html::import_on("<p>hello</p>", &|_| None, &page)),
),
("markdown::import_on (from_shared)", crate::with_shared_conversion_error_after(1, msg, || crate::markdown::import_on("hello", &page))),
(
"markdown::import_on_with_lines (from_shared)",
crate::with_shared_conversion_error_after(1, msg, || crate::markdown::import_on_with_lines("hello", &page).map(|(d, _)| d)),
),
("mht::import_on (from_shared)", crate::with_shared_conversion_error_after(1, msg, || crate::mht::import_on(mht_bytes, &page))),
] {
assert_err(res.map(|_| String::new()), label);
}
}
#[test]
fn odt_round_trip() {
check_round_trip("odt", true);
@@ -350,6 +418,34 @@ fn odt_round_trip() {
assert_eq!(back.core.creator, "Ada Writer");
}
#[test]
fn open_document_import_on_reports_section_conversion_errors() {
// Original synthetic ODT, OTT and FODT without a page layout, so they use the supplied paper size.
let ns = concat!(
r#"xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" "#,
r#"xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" office:version="1.3""#,
);
let body = "<office:body><office:text><text:p>Page geometry</text:p></office:text></office:body>";
let packaged = |mime: &str| {
let content = format!("<office:document-content {ns}>{body}</office:document-content>");
let mut zip = craft_zip::Writer::new();
zip.add("mimetype", mime.as_bytes(), craft_zip::Compression::Stored).unwrap();
zip.add("content.xml", content.as_bytes(), craft_zip::Compression::Stored).unwrap();
zip.finish().unwrap()
};
let flat = format!(r#"<office:document {ns} office:mimetype="{}">{body}</office:document>"#, crate::odt::TEXT_MIME);
let cases = [("odt", packaged(crate::odt::TEXT_MIME)), ("ott", packaged(crate::odt::TEMPLATE_MIME)), ("fodt", flat.into_bytes())];
let page = wordcraft_doc::SectionProps { page_w: 505.0, page_h: 731.0, ..Default::default() };
let message = "OpenDocument page conversion failed";
for (ext, bytes) in cases {
let open = || crate::import_on(ext, &bytes, &page).unwrap();
let doc = open().unwrap();
assert_eq!((doc.last_section.page_w, doc.last_section.page_h), (page.page_w, page.page_h), "{ext}");
assert_eq!(doc.plain_text(wordcraft_doc::StoryRef::Body), "Page geometry", "{ext}");
assert_eq!(crate::with_shared_conversion_error(message, open).unwrap_err(), message, "{ext}");
}
}
/// A flat ODT on A4 with a header and a footer, their bands' minimum heights (`fo:min-height`)
/// stated, and two body paragraphs.
fn flat_odt_with_bands(header: &str, footer: &str) -> Vec<u8> {
+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");
}
}
+1
View File
@@ -14,6 +14,7 @@ wordcraft-doc = { workspace = true }
wordcraft-fonts = { workspace = true }
wordcraft-proof = { workspace = true }
craft-metafile = { workspace = true }
craft-xml = { workspace = true }
kurbo = { workspace = true }
unicode-bidi = { workspace = true }
unicode-linebreak = { workspace = true }
+26 -16
View File
@@ -1,6 +1,7 @@
use super::ctx::{Ctx, Joining, page_anchored};
use super::floats::{
ObjFrame, ObjectPlacement, WrapArea, align_in, float_rect, floating, left_out_objects, place_objects, rel_exclusions, wrap_area,
AnchoredFloat, 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;
@@ -160,13 +161,13 @@ fn layout_table_block(input: TableBlockContext<'_, '_, '_>) -> bool {
let layout = table::layout_table(ctx, story, t, path, width, depth + 1);
let (tx, ty) = match t.props.float {
Some(float) => {
let legacy = (ctx.doc.settings.compat_mode < 15).then(|| table::first_cell_left_margin(ctx, t));
let (rect, area) = box_float_table_rect(frame, width, *y, &layout, &float, legacy, float_tables);
exclusions.push((area, false, None, WrapText::BothSides, true));
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, 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)
}
@@ -361,9 +362,9 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
let outline = ctx.wrap_outline(o);
excl.extend(wrap_area(r, float, outline.as_deref().map(Vec::as_slice)));
}
floats.insert(oi, r);
floats.insert(oi, AnchoredFloat::new(r));
}
let rel = rel_exclusions(&excl, 0.0, y);
let rel = rel_exclusions(&excl, 0.0, y, applied);
if !rel.is_empty() {
pl = ctx.para_labelled(p, width, table, &rel, applied, label);
}
@@ -525,17 +526,25 @@ pub(crate) struct BoxLayout {
pub(crate) last_top: f32,
}
/// How a floating table placed by an offset stands from it.
#[derive(Clone, Copy)]
struct FloatPlace {
/// How far left of the offset its edge stands ([`table::float_offset_shift`]).
shift: f32,
/// Word 2013 layout (compatibility mode 15).
modern: bool,
}
/// Where floating table `tl` goes in a box `width` wide whose next paragraph starts at `y`, and
/// the area text keeps clear of. Positions relative to the page or its margins need the box's
/// `frame`; without one (a table cell) they're relative to the box. `legacy` is the first cell's
/// left margin before Word 2013 layout, `None` in it.
/// `frame`; without one (a table cell) they're relative to the box.
fn box_float_table_rect(
frame: Option<PageFrame>,
width: f32,
y: f32,
tl: &table::TableLayout,
f: &TableFloat,
legacy: Option<f32>,
place: FloatPlace,
float_tables: &[Rect],
) -> (Rect, Rect) {
let h = tl.rows.iter().map(|r| r.height).sum::<f32>().clamp(0.0, 100_000.0);
@@ -571,8 +580,8 @@ fn box_float_table_rect(
};
// Nor is there an area to align in: the table starts where the text is.
let v_align = if frame.is_none() && matches!(f.v_rel, Anchor::Page | Anchor::Margin) { None } else { f.v_align };
let x = align_in(h_area, f.x, w, PageFrame::h_align(frame.as_ref(), f.h_align)) - if f.h_align.is_none() { legacy.unwrap_or(0.0) } else { 0.0 };
let r = clear_of_float_tables(Rect::new(x, align_in(v_area, y_off, h, v_align), w, h), f, legacy.is_none(), h_area.0, float_tables);
let x = align_in(h_area, f.x, w, PageFrame::h_align(frame.as_ref(), f.h_align)) - if f.h_align.is_none() { place.shift } else { 0.0 };
let r = clear_of_float_tables(Rect::new(x, align_in(v_area, y_off, h, v_align), w, h), f, place.modern, h_area.0 - place.shift, float_tables);
let [dl, dt, dr, db] = f.dist_from_text();
(r, r.inset(-dl, -dt, -dr, -db))
}
@@ -804,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
@@ -812,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)
}
@@ -827,8 +836,9 @@ impl Joint {
}
/// Paragraph `p` of a box `width` wide going on from here, unless a page break comes before
/// it, it runs right to left or it is a text frame (`frames`: placed apart, sharing no line):
/// without its space before, as [`Joint::fit`] lays it out.
/// it, it runs right to left, or it is a text frame placed apart (`frames` and `cell_frame`
/// both hold, sharing no line; in a table cell, only frames anchored to `"text"`): without
/// its space before, as [`Joint::fit`] lays it out.
fn take_up(
self,
ctx: &mut Ctx,
+5
View File
@@ -152,6 +152,11 @@ pub(crate) fn env_hash(doc: &Document, cache: &mut LayoutCache, opts: &LayoutOpt
let outline = (opts.view == ViewMode::Outline).then(|| opts.outline.as_ref().is_some_and(|o| o.plain));
let mut h = std::collections::hash_map::DefaultHasher::new();
styles.hash(&mut h);
// Theme fonts affect East Asian slot resolution (when `font_ea_theme` is set).
doc.settings.major_font.hash(&mut h);
doc.settings.minor_font.hash(&mut h);
doc.passthrough.get("wordcraft:theme.fonts").hash(&mut h);
doc.passthrough.get("wordcraft:settings.orig").hash(&mut h);
// The compatibility mode changes paragraph layout too (widow control in table cells).
doc.settings.compat_mode.hash(&mut h);
opts.show_hidden.hash(&mut h);
+104 -29
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,19 +222,22 @@ 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`.
pub(crate) fn rel_exclusions(excl: &[WrapArea], x0: f32, y0: f32) -> Vec<para::Exclusion> {
/// Wrap areas relative to a paragraph whose column starts at `x0` and whose top is `y0`, with
/// `space_before` the space before it that the flow laid out above it.
pub(crate) fn rel_exclusions(excl: &[WrapArea], x0: f32, y0: f32, space_before: f32) -> Vec<para::Exclusion> {
let before = if space_before > 0.0 { space_before } else { 0.0 };
excl.iter()
.map(|(r, tb, c, side, table)| para::Exclusion {
.map(|(r, tb, c, side, kind)| para::Exclusion {
top: r.y - y0,
bottom: r.bottom() - y0,
left: r.x - x0,
@@ -230,12 +245,14 @@ pub(crate) fn rel_exclusions(excl: &[WrapArea], x0: f32, y0: f32) -> Vec<para::E
top_bottom: *tb,
contour: c.clone(),
side: *side,
table: *table,
table: *kind == AreaKind::Table,
tight: *kind == AreaKind::Tight,
})
// Top-and-Bottom areas above the first line can still take room: they sit in the
// paragraph's space before, which Word lays out again below them (#7143). Side-wrapping
// areas there are above the text and take no room, as before.
.filter(|e| e.bottom > 0.0 || e.top_bottom)
// Top-and-Bottom areas ending within the paragraph's applied space before can still take
// room, with that space laid out again below them (#7143). Any ending at or above it
// (like side-wrapping areas above the first line) cannot reach the paragraph and is
// dropped so paragraphs below keep empty exclusions and hit the cache (#8613).
.filter(|e| e.bottom > 0.0 || (e.top_bottom && e.bottom > -before))
.collect()
}
@@ -346,7 +363,7 @@ pub(crate) fn anchor_floats(
pb: &mut PageBuilder,
anchor: FloatAnchor,
force: &[usize],
) -> (HashMap<usize, Rect>, Arc<ParaLayout>, Vec<para::Exclusion>, Vec<usize>) {
) -> (HashMap<usize, AnchoredFloat>, Arc<ParaLayout>, Vec<para::Exclusion>, Vec<usize>) {
let FloatAnchor { p, block, y0, place, .. } = anchor;
ctx.fields.page = pb.number;
// Each layout of it here counts its automatic equation numbers from the same place.
@@ -468,18 +485,32 @@ pub(crate) fn anchor_lines(p: &Paragraph, pl: &ParaLayout) -> Vec<Option<usize>>
out
}
/// A float placed before its paragraph's objects are drawn.
pub(crate) struct AnchoredFloat {
rect: Rect,
/// The origin used when the float was placed again from the pushed first line.
pushed_origin: Option<f32>,
}
impl AnchoredFloat {
pub(crate) fn new(rect: Rect) -> Self {
Self { rect, pushed_origin: None }
}
}
/// [`anchor_floats`], leaving out the floats in `late` (in order).
fn anchor_floats_but(
ctx: &mut Ctx,
pb: &mut PageBuilder,
anchor: FloatAnchor,
late: &[usize],
) -> (HashMap<usize, Rect>, Arc<ParaLayout>, Vec<para::Exclusion>) {
) -> (HashMap<usize, AnchoredFloat>, Arc<ParaLayout>, Vec<para::Exclusion>) {
let FloatAnchor { p, block, y0, before, excl_mark, label, place } = anchor;
ctx.fields.page = pb.number;
ctx.fields.page_format = pb.page_format;
let (col_x, width) = (pb.col_x(), pb.col_w());
let mut rects = HashMap::new();
let mut areas = HashMap::new();
if !pb.web && place {
// (A mark from a page before may be short of the areas this page started with.)
pb.excl.truncate(excl_mark.max(pb.seeded));
@@ -511,25 +542,68 @@ fn anchor_floats_but(
let seed = early.and_then(|v| v.iter().find(|(b, k, _)| (*b, *k) == (block, oi))).map(|(_, _, a)| a);
(r, area) = settle_early(r, area, seed, top, |r| wrap_area(r, float, outline));
}
rects.insert(oi, r);
rects.insert(oi, AnchoredFloat::new(r));
// Above the paragraph, beside text laid out before it: the page is laid out again
// with it known from the start (#2048).
let above = area.as_ref().filter(|a| text_before && a.0.y < top - 0.5).map(|a| (page, a.clone()));
ctx.floats_above.insert((block, oi), above);
if let Some(area) = area {
match early.and_then(|v| v.iter().position(|(b, k, _)| (*b, *k) == (block, oi))).filter(|k| *k < pb.seeded) {
let slot = if let Some(area) = area {
let b = area.0.bottom();
let k = match early.and_then(|v| v.iter().position(|(b, k, _)| (*b, *k) == (block, oi))).filter(|k| *k < pb.seeded) {
Some(k) => {
if let Some(slot) = pb.excl.get_mut(k) {
*slot = area;
}
k
}
None => pb.excl.push(area),
None => {
let k = pb.excl.len();
pb.excl.push(area);
k
}
};
Some((k, b))
} else {
None
};
areas.insert(oi, slot);
}
}
let rel = rel_exclusions(&body_wraps(ctx, pb), col_x, y0, before);
let pl = ctx.para_labelled(p, width, None, &rel, before, label.clone());
let lead = pl.lines.first().map_or(0.0, |l| l.top.max(0.0));
if !pb.web && place && lead > 0.0 {
let page = pb.pages.len().saturating_sub(1);
let top = y0 - before;
let text_before = top > pb.top + 0.5 || pb.col > 0;
let frame = PageFrame { sect: pb.sect, margin_top: None, origin: (0.0, 0.0), number: pb.number, mirror: ctx.mirror };
for (oi, o) in p.objects.iter().enumerate() {
let Some((_, _, float)) = floating(o) else { continue };
let Some(&area) = areas.get(&oi) else { continue };
let Some(placed) = rects.get_mut(&oi) else { continue };
let r = placed.rect;
if float.y < 0.0 && area.map_or(r.bottom(), |(_, b)| b) < y0 + lead - 0.5 {
// Only down: across it stays where it was placed (`settle_early` may have moved it).
let moved = Rect { y: float_rect(Some(frame), (col_x, width), top + lead, r.w, r.h, float).y, ..r };
// A wrap area moved onto the first line would cover text laid out without it.
if area.is_some_and(|(_, b)| b + (moved.y - r.y) > y0 + lead - 0.5) {
continue;
}
placed.rect = moved;
placed.pushed_origin = match float.v_rel {
Anchor::Page | Anchor::Margin | Anchor::TopMargin | Anchor::BottomMargin | Anchor::InsideMargin | Anchor::OutsideMargin => None,
_ => Some(top + lead),
};
if let Some((k, _)) = area
&& let Some(slot) = pb.excl.get_mut(k)
{
slot.0.y += moved.y - r.y;
let above = (text_before && slot.0.y < top - 0.5).then(|| (page, slot.clone()));
ctx.floats_above.insert((block, oi), above);
}
}
}
}
let rel = rel_exclusions(&body_wraps(ctx, pb), col_x, y0);
let pl = ctx.para_labelled(p, width, None, &rel, before, label.clone());
(rects, pl, rel)
}
@@ -696,7 +770,7 @@ pub(crate) struct ObjectPlacement<'a> {
pub lines: (usize, usize),
pub origin: (f32, f32),
pub at: &'a ObjFrame<'a>,
pub floats: &'a HashMap<usize, Rect>,
pub floats: &'a HashMap<usize, AnchoredFloat>,
pub depth: usize,
}
@@ -756,22 +830,23 @@ pub(crate) fn place_objects(ctx: &mut Ctx, req: &ObjectPlacement) -> (Vec<Placed
continue;
}
let pinned = at.pinned.and_then(|m| m.get(&oi)).copied().filter(|_| floating);
let rect = if let Some(r) = pinned {
r
let (rect, origin_y) = if let Some(r) = pinned {
(r, at.para_y)
} else if let Some(l) = late_here {
l.rect
(l.rect, l.top)
} else if floating {
match floats.get(&oi) {
Some(r) => *r,
Some(placed) => (placed.rect, placed.pushed_origin.unwrap_or(at.para_y)),
None => {
let h = ctx.float_height(obj, w, h);
float_rect(at.page, at.col, at.para_y, w, h, float)
(float_rect(at.page, at.col, at.para_y, w, h, float), at.para_y)
}
}
} else {
let cx = x + line.cl_left(k).unwrap_or(0.0);
let modern = ctx.doc.settings.compat_mode >= wordcraft_doc::COMPAT_MODE_CURRENT;
display::inline_rect(Some(obj), cx, y + (line.baseline - fl.top), c.adv, (c.obj_h, c.obj_d), pl.rule_room(line, k), modern)
let r = display::inline_rect(Some(obj), cx, y + (line.baseline - fl.top), c.adv, (c.obj_h, c.obj_d), pl.rule_room(line, k), modern);
(r, at.para_y)
};
let (mut behind, mut front) = (Vec::new(), Vec::new());
let layer = if float.wrap == Wrap::BehindText { &mut behind } else { &mut front };
@@ -818,7 +893,7 @@ pub(crate) fn place_objects(ctx: &mut Ctx, req: &ObjectPlacement) -> (Vec<Placed
off: c.start,
text_box: shown,
wrap: float.wrap,
origin: Point::new(at.col.0, late_here.map_or(at.para_y, |l| l.top)),
origin: Point::new(at.col.0, origin_y),
group_boxes,
});
for (id, rect) in boxes {
@@ -864,7 +939,7 @@ pub(crate) fn place_objects(ctx: &mut Ctx, req: &ObjectPlacement) -> (Vec<Placed
/// touch its lines and are left out.
pub(crate) fn continued_exclusions(rel: &[para::Exclusion], excl: &[WrapArea], x0: f32, y: f32, t: f32, width: f32) -> Vec<para::Exclusion> {
let before = rel.iter().filter(|e| e.top < t).map(|e| para::Exclusion { bottom: e.bottom.min(t), ..e.clone() });
let here = rel_exclusions(excl, x0, y - t)
let here = rel_exclusions(excl, x0, y - t, 0.0)
.into_iter()
.filter(|e| e.bottom > t && e.right > -width && e.left < 2.0 * width)
.map(|e| if e.top < t && e.contour.is_none() { para::Exclusion { top: t, ..e } } else { e });
+7 -6
View File
@@ -2,16 +2,16 @@ use super::boxes::{BoxInput, BoxLayout, Edges, Joint, frame_float, joined, layou
use super::cache::has_page_number_fields;
use super::ctx::{Ctx, Joining};
use super::floats::{
FloatAnchor, LateFloats, ObjFrame, ObjectPlacement, anchor_floats, body_wraps, continued_exclusions, fitting, float_rect, late_floats,
place_late, place_objects, wrap_area,
AnchoredFloat, FloatAnchor, LateFloats, ObjFrame, ObjectPlacement, anchor_floats, body_wraps, continued_exclusions, fitting, float_rect,
late_floats, place_late, place_objects, wrap_area,
};
use super::notes::{DECOR_STORY, NoteBox, para_notes};
use super::page::{PageBuilder, PageFrame, item_bottom};
use super::placed::Placed;
use super::table_flow::table_start_need;
use super::{
Arc, Block, Counters, Document, HashMap, InlineObject, Level, LineEnd, Page, ParaLayout, Paragraph, Path, Rect, StoryRef, TextDirection,
ViewMode, outline, para,
Arc, Block, Counters, Document, HashMap, InlineObject, Level, LineEnd, Page, ParaLayout, Paragraph, Path, StoryRef, TextDirection, ViewMode,
outline, para,
};
#[cfg(test)]
use crate::WRAP_RELAYS;
@@ -279,7 +279,7 @@ struct Flow<'a> {
excl_mark: usize,
/// Where its automatic equation numbers start: each layout of it again counts from here.
eq_start: u32,
float_rects: HashMap<usize, Rect>,
float_rects: HashMap<usize, AnchoredFloat>,
pl: Arc<ParaLayout>,
rel: Vec<para::Exclusion>,
/// The page its fields were laid out for, and the width.
@@ -1312,6 +1312,7 @@ mod tests {
use wordcraft_doc::Pos;
use wordcraft_doc::para::{Anchor, Float, LINE_BREAK, Wrap, WrapText};
use wordcraft_doc::props::LineSpacing;
use wordcraft_geom::Rect;
#[test]
fn strict_balancing_remeasures_kept_lines_in_the_next_column() {
@@ -1331,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");

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