Compare commits

...
Author SHA1 Message Date
skylar taylor f2e6403b9c Merge pull request #8914 from storytold/release-0.20.1-hotfix
Release 0.20.1: maximize and full screen on Windows again (#8838)
2026-12-04 12:45:16 -06:00
skylartaylor 1f1d8a05f7 Release 0.20.1: maximize and full-screen fix for Windows (#8838)
Pins craft-libs ad10c35a (wordcraft#8871's pin; one commit on the shipped 5299d8d9) and bumps to 0.20.1.
2026-12-04 18:39:29 +01:00
Martin BallandClaude Opus 5.5 72798d3db1 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 <[email protected]>
2026-12-04 02:27:41 +00:00
Martin Ball f1665031b3 Merge remote-tracking branch 'origin/main' into release
; Conflicts:
;	Cargo.lock
;	Cargo.toml
2026-12-04 00:45:48 +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 <[email protected]>
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 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

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

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-04 00:42:19 +00:00
autocraft-bot[bot] 5073f8e7c2 Merge pull request #8728 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] de328db448 Merge pull request #8719 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] 1ffd5f8d4a Merge pull request #8647
With AutoCraft's conflict resolution 849eb756.
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] b4ecd20dba Merge pull request #8631 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] 3b0257ff33 Merge pull request #6943
With AutoCraft's conflict resolution edb53680.
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] cfae52c97d Merge pull request #8714 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] e7172b9a8a Merge pull request #8705 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] 92eb57fd08 Merge pull request #8703 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] 3138201a56 Merge pull request #8692 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] e2f2fe1f09 Merge pull request #8678 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] 1812618f10 Merge pull request #8689 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] 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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
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
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
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 <[email protected]>

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

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

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

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

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

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

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

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

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

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

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

---------

Co-authored-by: Claude Sonnet 5.5 <[email protected]>
2026-12-03 19:02:47 +00:00
autocraft-bot[bot] 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] 72ef3083e7 Merge pull request #8210
With AutoCraft's conflict resolution d24d3034.
2026-12-03 15:10:05 +00:00
autocraft-bot[bot] 1ec83a1a2f Merge pull request #6578
With AutoCraft's conflict resolution 0de83145.
2026-12-03 15:10:05 +00:00
autocraft-bot[bot] 27672b2448 Merge pull request #4614
With AutoCraft's conflict resolution 7c41404c.
2026-12-03 15:10:05 +00:00
autocraft-bot[bot] 67d5297c08 Merge pull request #8599 2026-12-03 15:10:05 +00:00
Mat Strange 4c1dfa6367 Say what Ctrl+K does with a column selection
The doc said the link lands at the block's top-left corner; it says now
that insert.link inserts the link text there and leaves the block's own
text unlinked, which is what the command does (#8602).

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

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

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

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

* validate: delimit the measured DrawingML coordinate evidence

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

Both fail with their branch removed and pass on main (layout 881 passed; the
three hyphenation tests fail on a clean main too, for lack of dictionaries
in this environment).
2026-12-03 12:25:14 +03:00
Zaxaerith a2d8bbdb4d docs: explain the effective animation control state 2026-12-03 16:18:51 +08:00
autocraft-bot[bot] 98e617806b Merge pull request #6114
With AutoCraft's conflict resolution 0c03eaab.
2026-12-03 07:58:05 +00:00
autocraft-bot[bot] 4f6dbbb5fd Merge main (98e61780) into the pull request 2026-12-03 07:58:05 +00:00
autocraft-bot[bot] 882bacb858 Merge pull request #8567 2026-12-03 07:58:05 +00:00
autocraft-bot[bot] 3487354a1b Merge pull request #8519 2026-12-03 07:58:05 +00:00
Zaxaerith 991b590021 docs(ui): describe when pointer commands keep the view 2026-12-03 15:58:05 +08:00
autocraft-bot[bot] 549748efec Merge pull request #8555 2026-12-03 06:49:32 +00:00
Max MittelstädtandGPT-6-Luna bf7ce2509c Place footnotes from page anchored frames
Fixes #8531

Co-Authored-By: GPT-6-Luna <[email protected]>
2026-12-03 06:49:32 +00:00
midasmatterhorn f5c9da1b70 Merge main into fix/issue-7143-topbottom-space-before 2026-12-03 09:38:18 +03:00
autocraft-bot[bot] a6d1534889 Part 1: the Outline view fuzz in outline_level_changes_are_undoable (c
Part 1: the Outline view fuzz in `outline_level_changes_are_undoable` (crates/engine/src/tests.rs) now keeps the `Session::run` result instead of discarding it. It builds the registry once and asserts `!caught_panic(&reg, &r)`, with the command id, the junk input and the result in the failure message. The message format matches the one in `hostile_params_never_panic`. `cargo fmt --check` and `cargo clippy` on `wordcraft-engine` are clean. `outline_level_changes_are_undoable` and `caught_panic_flags_a_command_that_panics` both pass. I did not run the full engine test suite.
2026-12-03 05:35:02 +00:00
autocraft-bot[bot] c8c78e0fab Merge pull request #6519
With AutoCraft's conflict resolution 18acfd9e.
2026-12-03 05:32:56 +00:00
autocraft-bot[bot] dd42e032fc Merge pull request #6628
With AutoCraft's conflict resolution 44182e7f.
2026-12-03 05:32:56 +00:00
autocraft-bot[bot] 438223240c Merge pull request #5546
With AutoCraft's conflict resolution 6679a251.
2026-12-03 05:32:56 +00:00
autocraft-bot[bot] 6c80ff1de1 Merge pull request #8521 2026-12-03 05:32:56 +00:00
autocraft-bot[bot] 6585dbbfca Merge pull request #6979 2026-12-03 05:32:56 +00:00
dotCooCoo 83a2e63257 Tests: compare the separator frame shape with ShapeKind::Frame
main now has ShapeKind::Frame, so the test compares the kind directly
instead of its debug text.
2026-12-02 21:32:56 -08:00
dotCooCoo e3a913a4d3 Merge main into fix/footnote-separator-frame 2026-12-02 21:27:52 -08:00
dotCooCoo 25f126f48b Layout: a frame beside the column blocks text with a negative indent
The fresh-column check looked for page-anchored text frames only across
the column itself. A paragraph whose negative indent takes its text
past the column's edge over a frame was then pushed below the frame
while the column still counted as fresh, so the line was placed past
the page bottom. The check now widens the column by the indents of the
lines still to place, on the sides the paragraph's direction puts them.
2026-12-02 21:08:45 -08:00
dotCooCoo ba8bc15d89 Layout: body text wraps around page-anchored text frames
A body paragraph framed at a page anchor (#6535) was drawn at its
position without a wrap area, so the text after it ran through the
frame. The frame now adds the wrap area its mode gives, as text frames
in text boxes and cells do: `notBeside` keeps the following text below
it and `around` keeps it beside it. Text at the top of a column that
such a frame reaches into moves on to the next page when no line fits,
instead of overflowing the page.
2026-12-02 20:33:59 -08:00
autocraft-bot[bot] 30792edab8 Merge pull request #6457
With AutoCraft's conflict resolution 1e877a37.
2026-12-03 04:16:33 +00:00
autocraft-bot[bot] 2094505e3a Merge pull request #8344
With AutoCraft's conflict resolution 1fbca6b7.
2026-12-03 04:16:33 +00:00
autocraft-bot[bot] 7db2784719 Merge pull request #6581
With AutoCraft's conflict resolution 422633cf.
2026-12-03 04:16:33 +00:00
autocraft-bot[bot] cbea96e5e9 Merge pull request #3833
With AutoCraft's conflict resolution d46b3593.
2026-12-03 04:16:33 +00:00
autocraft-bot[bot] 0d04e94422 Merge pull request #7877
With AutoCraft's conflict resolution c3e4e986.
2026-12-03 04:16:33 +00:00
autocraft-bot[bot] e26c73df7a Merge pull request #7998 2026-12-03 04:16:33 +00:00
autocraft-bot[bot] ed33f21784 Merge pull request #8520 2026-12-03 04:16:33 +00:00
dotCooCoo 6b021d557d DOCX corpus: refuse a report path the summary would overwrite
`cargo xtask docx-corpus` writes its Markdown summary to the --out path
with an .md extension. When --out already ended in .md (for example
`--out report.md`), the summary replaced the JSON report and the command
still printed that it wrote both files. The command now refuses such a
path before the run starts. Trailing dots and spaces, which Windows
drops from a file name, and letter case are ignored in the check, so
`report.MD` and `report.md ` are refused too.

The harness came in with cee47681 (M15 #1: add opt-in DOCX corpus
harness).
2026-12-02 20:16:33 -08:00
autocraft-bot[bot] 5bfdfc3bf6 The batch failed because main now opens a frame shape as Frame, whil
The batch failed because main now opens a `frame` shape as `Frame`, while the PR's test expected `Rectangle` in the note separators. The CI log shows `left: [(Frame, 40.0)]`, `right: [(Rectangle, 40.0)]`. The PR's code change is correct and only its test expectation was stale. In `crates/docx/tests/it/fixtures.rs` the test now puts the same frame shape in the body. It asserts the body shape's width is 40.0 and its kind is `Frame`, and that the footnote and endnote separators give the same `(kind, width)` as the body. The kind is compared by its debug text. An earlier attempt hard-coded `ShapeKind::Frame`, and AutoCraft's clippy check rejected it as having no such variant. Comparing the debug text avoids that and still pins the kind. I kept the test name, which a rename check requires, and a doc comment notes that the name is old. On this tree the test passes, clippy with `-D warnings` on `wordcraft-docx --all-targets` is clean, and `cargo fmt --check` is clean. I didn't run the rest of the docx suite.
2026-12-03 04:12:54 +00:00
dotCooCoo 2ed77bdb93 Mail merge: ODS times keep seconds fractions finer than a nanosecond
An ODS date-time or clock time read its seconds through chrono, which
keeps nine fraction digits and drops the rest. A value such as
2024-03-05T00:00:00.0000000001 then merged as the bare date, and
13:45:00.1234567891 lost its last digit, while the same fraction in a
duration (PT...S) was kept as written.

Clock times now keep their fraction digits as written, trailing zeros
dropped, like durations. A fraction is accepted only after whole
seconds. Typed values are also held to the cell size limit, as cell
text already was.

Follows up #6732, which added the ODS typed-value helpers.
2026-12-02 20:11:48 -08:00
autocraft-bot[bot] d01c843aa2 Merge pull request #8342
With AutoCraft's conflict resolution a5d3b88b.
2026-12-03 03:25:56 +00:00
autocraft-bot[bot] cde21126d2 Merge pull request #7608 2026-12-03 03:25:56 +00:00
autocraft-bot[bot] 42f157b53f Merge pull request #7897
With AutoCraft's conflict resolution b6df7dd2.
2026-12-03 03:25:56 +00:00
autocraft-bot[bot] 34a93e9123 Merge pull request #8495 2026-12-03 03:25:56 +00:00
Max MittelstädtandGPT-6-Luna 9f7fcb88a7 Gate the confined session test on native targets
Fixes #8478

Co-Authored-By: GPT-6-Luna <[email protected]>
2026-12-03 03:25:56 +00:00
autocraft-bot[bot] da69216eeb Merge pull request #8494 2026-12-03 03:23:00 +00:00
Martin BallandClaude Sonnet 5.5 a668eba449 fix(ui): Shapes gallery cells about 33 pt (#7828)
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx
2026-12-03 03:23:00 +00:00
autocraft-bot[bot] b7c34c3e1e Merge pull request #8482 2026-12-03 02:45:57 +00:00
autocraft-bot[bot] 3c9c0219b8 Merge pull request #8481 2026-12-03 02:41:27 +00:00
Martin BallandClaude Sonnet 5.5 b185aaf839 fix(link): never retype the selection with the placeholder (#8286)
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx
2026-12-03 02:41:27 +00:00
Martin BallandClaude Sonnet 5.5 03439ff33f fix(link): show a placeholder in Text to display for a selection that is not one plain line (#8286)
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx
2026-12-03 02:38:57 +00:00
autocraft-bot[bot] 93573f56e6 Merge pull request #8475 2026-12-03 02:21:27 +00:00
autocraft-bot[bot] cb1c530240 Merge pull request #8215 2026-12-03 02:21:27 +00:00
autocraft-bot[bot] dc5f5852dd The test typing_after_a_table_grid_pick_goes_into_the_new_table failed i
The test typing_after_a_table_grid_pick_goes_into_the_new_table failed in the merge batch because main now labels the Table size picker's grid squares "2x2 Table" (the CI log's accessibility tree shows "1x1 Table", "2x1 Table", ...), while the test looked for "2 × 2" at tests/ribbon.rs:188. The test itself was wrong, so I changed that one lookup to "2x2 Table". No assertion was weakened and the focus fix in insert.rs is unchanged. The test passes in the pod and cargo fmt --all --check is clean. I did not run clippy or the rest of the lib suite.
2026-12-03 02:21:27 +00:00
autocraft-bot[bot] b4cb84ea5d Merge pull request #8331 2026-12-03 02:15:29 +00:00
autocraft-bot[bot] faebf07b9a Merge pull request #7262 2026-12-03 02:15:29 +00:00
autocraft-bot[bot] acc1233da0 Part 1 is fixed. layout_table no longer takes an align_room argument
Part 1 is fixed. `layout_table` no longer takes an `align_room` argument, and the `TURNED_MAX` visibility change is reverted. A merge's text is now aligned against the room left on the page where its restart row actually lands, not the room from the table's start.

- **Table layout (`table.rs`):** the first layout of a table is uncapped again, so a merge that doesn't cross a page end keeps its alignment and its rotated text length. I added `merge_rows_after`, which counts the rows a merge starting in a given row runs on over. I also added `layout_table_row_in`, which lays out one row again with its merged cells capped to a given room. It restores the list and equation counters afterwards. The cap now applies only to restart cells of the row being laid out again, which also drops the odd turned-text clamp from the PR.
- **Placement (`table_flow.rs`):** at the start of each pass over a row in `place_table`, if a merge starting there is taller than the room left on the page, the row is laid out again for that room and the new version is placed. This repeats after a move to the next page, so rows pushed down by header rows, space before the table or floats are measured at their real landing. Floating tables that fit a page need no cap, and ones that fall back to normal flow go through the same path.
- **Tests (`tests.rs`):**
  - Added `a_vertical_merge_that_starts_on_a_later_page_is_aligned_within_its_rows`. It centres a merge over rows 20–24 of an exact-height table on page 2 and checks both horizontal and rotated text stay inside the merge's rect.
  - Moved the "1×3 table" doc comment back onto `turned_table`.
  - The PR's own `a_vertical_merge_aligns_its_text_with_the_first_page` was failing because it looked for path `[1,0,0,0]`. The table is block 0 in that test, so I changed it to `[0,0,0,0]`.

`cargo fmt --check` and clippy with `-D warnings` on `wordcraft-layout` pass, and the four merge tests pass. In the full layout test run, 852 passed and 3 failed. `a_megabyte_long_word_lays_out_quickly` and `a_word_with_alternating_advances_lays_out_in_linear_time` failed on timing under load; they don't touch tables. The third was the path bug above, now fixed. I did not re-run the full suite after that fix.
2026-12-03 02:15:29 +00:00
midasmatterhorn c1a0484d81 engine: use Jänner/Jän for de-AT and add German date-field integration tests 2026-12-03 05:03:09 +03:00
Max MittelstädtandGPT-6-Luna f6f7e9414e Join page anchored frames in table cells
Fixes #8450

Co-Authored-By: GPT-6-Luna <[email protected]>
2026-12-03 02:01:31 +00:00
midasmatterhorn 1de5a93974 layout: check Top-and-Bottom floats only within applied space before 2026-12-03 04:59:11 +03:00
autocraft-bot[bot] 9f43aa6ec1 Merge pull request #6446 2026-12-03 01:41:20 +00:00
autocraft-bot[bot] f2e2c78c4b Merge pull request #6520
With AutoCraft's conflict resolution 6eedb778.
2026-12-03 01:41:20 +00:00
autocraft-bot[bot] fe22b29c5f Merge pull request #7177 2026-12-03 01:41:20 +00:00
autocraft-bot[bot] 7f86031339 Merge pull request #6535 2026-12-03 01:41:20 +00:00
autocraft-bot[bot] 10fcb05b15 Merge main (d885a9d9) into the pull request
Resolved the only conflict, in crates/layout/src/tests.rs, by keeping th

Resolved the only conflict, in crates/layout/src/tests.rs, by keeping the PR's a_body_text_frame_respects_its_anchors test together with main's env_hash_memoizes_styles_and_invalidates_on_change and evict_unused_caps_stale_entries_across_repeated_edits tests, and closing the first test's brace. No conflict markers remain and cargo fmt --check is clean. I ran two of the three tests and both pass; I did not run the third (evict_unused_caps_stale_entries_across_repeated_edits) or the rest of the layout suite.
2026-12-03 01:41:20 +00:00
batistalucasv 1a05479d99 fix(keys): use fired modifiers for paste-format fallback across windows 2026-12-02 22:28:50 -03:00
batistalucasv fc0acd93b9 fix(keys): preserve paste suppression order and Mod+Shift+V origin 2026-12-02 22:28:50 -03:00
batistalucasv 5c2e7eb296 fix(keys): ignore paired browser paste after Mod+Shift+V (#7608) 2026-12-02 22:28:50 -03:00
batistalucasv cc7f9e2688 test(keys): restore the_ignored_paste_event_never_reaches_an_open_equation test (#7317) 2026-12-02 22:27:11 -03:00
autocraft-bot[bot] a67df42aa8 Merge pull request #8410 2026-12-03 01:20:17 +00:00
autocraft-bot[bot] 27dea96335 Merge pull request #8345
With AutoCraft's conflict resolution 2b524486.
2026-12-03 01:20:17 +00:00
autocraft-bot[bot] 3c5aeef936 Merge pull request #6732 2026-12-03 01:20:17 +00:00
autocraft-bot[bot] bcf2aa3b03 The formats crate's tests failed to compile on merged main: main's craft
The formats crate's tests failed to compile on merged main: main's craft-libs update (rev d73e274) puts craft_ods::testing behind craft-ods's test-support feature, and nothing enables it. The tests in crates/formats/src/sheet.rs now use a small local spreadsheet() helper that builds the same .ods package with craft_odf::PackageWriter (craft-odf is already a normal dependency); no dependency or Cargo.toml change, and no test or assertion weakened. cargo test -p wordcraft-formats sheet passes (9 tests), clippy -p wordcraft-formats --all-targets -D warnings is clean, and rustfmt --check on sheet.rs is clean. The CI logs were empty, so I did not run the Print job's own commands (cargo test and clippy on wordcraft and wordcraft-ui-egui), and the Print failure may have another cause.
2026-12-03 01:08:48 +00:00
autocraft-bot[bot] 87d5e537e2 In resolve_all (crates/engine/src/cmd/review/changes.rs), a paragraph is
In resolve_all (crates/engine/src/cmd/review/changes.rs), a paragraph is now trailing only when no block follows it in its container, instead of using !has_next_para, which is also true before a table. An empty revision paragraph between two tables is therefore not removed, and its mark is just cleared. I added the test reject_all_keeps_an_empty_inserted_paragraph_between_tables in crates/engine/src/cmd/tools/tests.rs, covering table, empty inserted paragraph, table, paragraph. fmt --check passed and clippy finished without errors. The engine compare tests were still running when the workspace backend dropped, so their result is unconfirmed.
2026-12-03 00:35:54 +00:00
yoriswind 9386f754f4 test(engine): qualify caret regression selection type 2026-12-02 15:24:09 -08:00
autocraft-bot[bot] 175d2eabe6 The new test failed only on the merge with main. The test opened the Bul
The new test failed only on the merge with main. The test opened the Bullets menu by clicking the last button labelled exactly "Bullets". Main now names the split button's arrow "Bullets options", and `bullets_dropdown_renders_compact_bullet_tiles` already uses that name. So the click hit a different node, the menu never opened, and the assertion "Bullets shows ○" at tests.rs:967 failed. The font change itself was fine. I changed the test's lookup to "Bullets options" and updated its comment. Every assertion is unchanged. The test passes now. `cargo fmt --check` and `cargo clippy -p wordcraft-ui-egui --all-targets -- -D warnings` are clean. I did not run the rest of the ui-egui suite. I also removed the debug printing an earlier session had added.
2026-12-02 23:08:16 +00: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
Reuben Grinberg 1405e7e8cb Review: remove a trailing paragraph whose mark resolves to removal (#3750) 2026-12-02 12:49:32 -06:00
Muse f1e8793b7a tests(engine): pin document creation date in markup PDF colour test 2026-12-02 09:35:19 -06:00
dfgodvan 951e6b230d Merge main into w1/multiple-of-tallest-run
# Conflicts:
#	crates/layout/src/para/lines.rs
#	crates/layout/src/tests.rs
#	docs/layout-parity.md
2026-12-02 16:55:02 +03:00
dfgodvan f55fabaac6 Merge main into w1/line-end-kern
# Conflicts:
#	crates/layout/src/tests.rs
#	docs/layout-parity.md
2026-12-02 16:54:16 +03:00
dfgodvan faa032ec12 Merge main into w1/times-twin-fallback-height
# Conflicts:
#	docs/layout-parity.md
2026-12-02 16:53:47 +03:00
dfgodvan 989a377de9 Merge main into w1/leading-past-footer
# Conflicts:
#	docs/layout-parity.md
2026-12-02 16:52:23 +03:00
dfgodvan 78b0a6929c Layout: the right-tab rule applies to right tabs only, and not beside a float
A decimal tab keeps main's fit: its digits after the point run on to the right
of the stop, so taking text up to the stop let a number run past the margin.
Where a floating object narrows the line, text after a right tab keeps to the
narrowed edge instead of running into the object.
2026-12-02 16:05:51 +03:00
dfgodvan 870bec1839 Merge main into fix/right-tab-beyond-indent 2026-12-02 16:02:02 +03:00
dfgodvan e819a03435 Layout: the list-number kerning test loads the test fonts; Word for Mac in the comments
The test now uses the test fonts, whose kerning pairs make it fail without the
change whatever fonts the machine has. The comments name Word for Mac, where the
measurement was made, as the description does; the Kerning parity row mentions
list numbers.
2026-12-02 15:56:26 +03:00
dfgodvan 77c0a29922 Merge main into w1/list-number-no-kern
# Conflicts:
#	crates/layout/src/para/paragraph.rs
#	docs/layout-parity.md
2026-12-02 15:55:52 +03:00
dfgodvan d66a7d3bf9 Layout: the layout cache follows a change of compatibility mode
Paragraph layout depends on the compatibility mode (widow control in table
cells before Word 2013 layout), so the mode is part of the cache environment.
2026-12-02 15:52:51 +03:00
dfgodvan 5efc89e5ea Tests: cells of a table without a style drop widow control before Word 2013 layout too
The cell layout gives every cell's paragraphs a cell text environment, an empty
one when the table has no style (boxes.rs), so the compatibility-mode rule
applies to tables without w:tblStyle as well.
2026-12-02 15:51:51 +03:00
dfgodvan 010134fb8e Merge main into fix/legacy-tables-at-page-foot
# Conflicts:
#	crates/layout/src/tests.rs
2026-12-02 15:51:46 +03:00
codeiouandClaude Code 08b8d71ece docs: distinguish deferred input replies from completed edits
A deferred control reply can arrive during the final input pass, before
that pass updates the document. Describe the observed deferral without
promising that the edit has already been applied. Keep the queued typing
example and tell clients to check the resulting state without replaying
an edit merely because its effect is not yet visible.

This corrects the existing protocol documentation follow-up; runtime
behaviour and the method table are unchanged.

Co-Authored-By: Claude Code <[email protected]>
2026-12-02 22:17:32 +11:00
Max MittelstädtandGPT-6-Luna d05c629fc0 Keep merged-cell text within the first page body
Fixes #7932

Co-Authored-By: GPT-6-Luna <[email protected]>
2026-12-02 10:25:25 +00:00
codeiouandClaude Opus 5.5 f33b5f8551 Docs: ui.clickText replies before its click is processed
The input-reply paragraph said every input method replies null once the app has processed the
input. ui.clickText replies at once with the window point it clicks ({"screen": [x, y]}) while
its click waits in the input queue, so a request sent next, such as engine.execute, can run
before the click lands. The paragraph now names the methods whose reply waits, says what
ui.clickText replies and what can run before its click, and points to ui.click with document
coordinates for a click that waits. The ui.clickText row says what it replies.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-02 19:32:11 +11:00
autocraft-bot[bot] 4bac1b4da0 Merge main (647e7261) into the pull request 2026-12-02 07:39:07 +00:00
Max MittelstädtandGPT-6-Luna 17a13fd901 Place body text frames at page anchors
Fixes #6531

Co-Authored-By: GPT-6-Luna <[email protected]>
2026-12-02 06:25:42 +00: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
fluorineandClaude Haiku 5.5 aeba356814 xtask: gate the stats test imports that only unix tests use
On Windows the one test that uses Counts and walk is compiled out, so
clippy -D warnings fails with unused imports.

Co-Authored-By: Claude Haiku 5.5 <[email protected]>
2026-11-30 14:39:43 -04:00
0c7ad0e0f0 Insert › Table and Symbol: typing after a pick on the grid goes into the page
Picking a size on Insert › Table's grid inserted the table and put the
caret in its first cell, but the keyboard stayed on the Table button,
so the next text typed was lost. Picking a symbol on Insert › Symbol's
grid lost the typing the same way. Each grid runs its command itself
and closes its menu with a plain close request, and a menu closed that
way hands focus back to its opener.

After a successful insertion each grid now gives the page the
keyboard, as the WordArt gallery does after a style pick. A failed
insertion leaves the focus where it was. The test from the previous
commit passes.

Co-Authored-By: GPT-6.2 Astra <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 20:25:38 +11:00
91cb502355 test(ui-egui): typing after a table grid pick goes into the new table
The test picks 2 × 2 on Insert › Table's grid with the pointer and
then, in a fresh window, with the keys (Enter on the focused Table
button, the arrows, Enter). Each time it checks that the page has the
keyboard and that typed text lands in the new table's first cell. It
fails without the fix in the next commit.

Co-Authored-By: GPT-6.2 Astra <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 20:25:33 +11:00
batistalucasv d46ecf3ab1 test(icons): verify stroke clearance and rendered bounds for dictate icon 2026-11-30 01:43:28 -03:00
FredApps 869160692f Merge origin/main into fix/fuzz-panics-autosave 2026-11-28 10:16:45 +07:00
8286638f79 fix(ui-egui): gallery symbols draw in Inter again without the font pack
Without the optional craft-fonts pack, where no installed font has them,
Home › Bullets drew boxes for ○ ▪ ◆ ✓ and Insert › Symbol for ✓ ★ ♥;
under kittest's strict missing-glyph policy the first of them panicked.
Before #7101 the interface's first face was WordCraft's own Inter, which
has them. The shared stack leads with the suite's Inter, the same 4.001
release cut to Latin, Greek and Cyrillic, and ui_fonts added none of
WordCraft's own faces behind it.

ui_fonts now adds WordCraft's own Inter Regular and SemiBold behind the
suite's faces, from the bytes the document fonts already embed
(wordcraft_fonts::bundled_inter), so the binary gains no font data.
Full Inter has every character of the cut and the same metrics: only
characters no bundled interface face had change face, and rows keep
their height. The macOS key symbols (⌘ ⌥ ⌃ ⌫ ⌦ ⏎ ⎋) are among them.

Co-Authored-By: GPT-6.2 Astra <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-28 10:24:21 +10:00
batistalucasv dd2d40a5f5 test(icons): verify dictate.svg viewBox, attribute boundary, and 16-22 pt rendering 2026-11-27 08:36:52 -03:00
batistalucasv ee05e88fa0 Address review feedback on dictate icon test (#7450) 2026-11-27 00:27:40 -03:00
batistalucasv 81aae389b3 Icons: adjust Dictate microphone icon geometry to prevent capsule cutting across U-stand (#7450) 2026-11-27 00:25:15 -03:00
Martin BallandClaude Opus 5.5 8803a95a2d #7171: Print settings buttons stay clear of the scroll bar and the preview
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 02:18:15 +00:00
codeiouandClaude Opus 5.5 adef1253bb Docs: the control protocol lists the methods and parameters the channel takes since #7101
The craft framework port (#7101) moved synthetic input and dialog answers to craft-automation, but docs/control-protocol.md kept the old names: ui.press, ui.drag and ui.text reply "unknown command", and cmd, the wheel units point, line and page, and phase are refused. The Methods table now gives the methods and parameters main answers and adds the ones it lacked. It also corrects the screenshot reply (base64), the input reply (null once the input is processed), the 30 s idle close, the ui.language values and the ui.paneDock panes. docs/typing-parity.md's How to compare now names ui.type, and the control module's docs no longer say that a screenshot replies with png. A test sends every method in the table through the control handler and fails on one the channel doesn't answer; it reads the doc line by line, so a checkout with CRLF line endings passes too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 08:59:34 +10:00
pakiat ff271a34e8 Merge commit '5687172000d1432f6b00e61a09fafd2f3a2059d4' into m/7177
# Conflicts:
#	crates/engine/src/cmd/paste.rs
2026-11-27 05:58:04 +07:00
jayzed80 52d50bd830 Port File > Export copy handling onto the host Files service (#6131) 2026-11-26 22:18:39 +00:00
codeiouandClaude Opus 5.5 6ebd483b14 Fonts: in small capitals a letter and its combining marks are drawn together (#7865)
A combining mark isn't a lower-case letter, so in small capitals a mark after a lower-case letter
started a shaping run of its own at full size. The next mark then left the letter out of cluster
matching (x with U+0301 and U+0336, in a font with U+0301 but no U+0336, drew U+0336 apart in
another face), and a mark that moved with its letter was still shaped apart from it. A mark now
takes its letter's small-capital size, as it already takes its complex-script formatting.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 07:55:54 +10:00
jayzed80 be2d9021bf Merge remote-tracking branch 'upstream/main' into HEAD
# Conflicts:
#	crates/ui-egui/src/app/commands.rs
2026-11-26 18:46:56 +00:00
codeiouandClaude Opus 5.5 3f9fc816bf Fonts: a combining mark its letter's font lacks is drawn with the letter in a face that has both (#7865)
A combining mark the face of its letter couldn't draw was shaped in that face anyway and
drawn as the face's missing-glyph box (∞ with U+0338 in Source Serif 4, or in Carlito for a
Calibri run), and strict export refused the file. segment_keys now keeps a mark with its
letter only while that face draws it, or composes the pair (= with U+0338 is ≠). Otherwise
the letter and its marks go together to a face that draws them all, as CSS Fonts 4 §5.3
(cluster matching) describes. With no such face, a mark in left-to-right text that isn't
complex script is drawn on its own from a face that has it; in right-to-left and
complex-script text it stays with its letter, so harakat are never split from their letter.
A cluster is matched once, at its first mark the face lacks, so a long run of marks lays out
in linear time.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 01:37:35 +10:00
skylartaylor 5d658dc033 Release: WordCraft v0.19.1 (main 09faec42ec, pre-UI-port) 2026-11-25 19:28:58 +01:00
skylartaylor 6b7788d8e0 Release: bump WordCraft to v0.19.1 (on 09faec42, the pre-UI-port candidate) 2026-11-25 19:27:28 +01:00
Kevin Joseph 8654ed1319 Merge remote-tracking branch 'origin/main' into fix/footnote-continued-bottom
# Conflicts:
#	docs/layout-parity.md
2026-11-24 09:46:34 +01:00
ljkx 7777eba6e4 Merge remote-tracking branch 'origin/main' into fix/createdate-keeps-date
# Conflicts:
#	docs/layout-parity.md
2026-11-23 03:04:48 +01:00
pakiat 64960989a1 Merge commit 'c369c3a20befef8742f8913128cacd79002435d6' into m/6943
# Conflicts:
#	docs/layout-parity.md
2026-11-23 07:41:22 +07:00
midasmatterhorn 4722d7d2fe A Top-and-Bottom object in a paragraph's space before pushes it down
Exclusions were relative to the first line's top and dropped when they
ended above it, so an object wholly inside the paragraph's space
before never moved the paragraph; and when an object reached into the
first line, the line moved to the object's bottom without the space
before being laid out again under it. Exclusion filtering keeps
Top-and-Bottom areas above the first line now, and the line breaker
looks one space before above its top for them and starts the line
below the object plus the space before. Objects in the previous
paragraph's space after stay where they were.
2026-11-22 00:02:35 +03:00
midasmatterhorn 81a367be13 German date fields use German month and weekday names
date_names mapped only Portuguese, so a de-DE DATE field rendered
English months and weekdays and defaulted to M/d/yyyy. German joins
the table (de-DE, de-AT, de-CH): full names, Word's short forms for
MMM and ddd (Mrz, the two-letter day forms), and dd.MM.yyyy when a
field carries no picture. The short names are explicit per-language
arrays now, so Portuguese and English keep exactly the first-three-
letter forms they had.
2026-11-21 23:24:12 +03:00
Mauro MazzieriandClaude Opus 5.5 989fa17544 Merge main into claude/continuous-section-first-page-header (#5543)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-21 18:52:40 +01:00
pakiatandClaude Opus 5.5 eccf146bca Merge Formatting keeps the emphasis a character style gives, not a paragraph style's
Measured in Word for Windows (Paste with Merge Formatting, PasteAndFormat
20): bold, italic, underline and strikethrough from the source's
character style are kept as direct formatting, for Latin and for Thai in a
w:cs run; a paragraph style's are dropped. Merge Formatting now judges a
run's emphasis by its own formatting over its character style chain, and
still not by the paragraph style.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-21 10:41:03 +07:00
Michael Higgins 1a0b33f671 Merge branch 'storytold:main' into fix/6517-typographic-apostrophe-word 2026-11-20 22:36:33 -05:00
pakiatandClaude Opus 5.5 523c905c6d Merge Formatting keeps only the emphasis the source shows
A run marked w:cs is bold and italic only by w:bCs and w:iCs (#4852), so
one with w:b and w:i alone is drawn plain, but Merge Formatting pasted it
bold and italic. It now keeps a toggle when the source shows it anywhere,
as the resolved formatting draws it.

Also moves #4852's 2026-10-29 progress-log row in
docs/file-format-parity.md next to the other 2026-10-29 rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-21 06:40:13 +07:00
Michael Higgins ce2f7789f4 Merge storytold/wordcraft main into fix/6516-toggle-first-character 2026-11-20 17:05:13 -05:00
Michael Higgins 539d9ce9d6 Merge storytold/wordcraft main into fix/6517-typographic-apostrophe-word 2026-11-20 17:05:09 -05:00
Michael Higgins ccf6340262 Merge storytold/wordcraft main into fix/6517-typographic-apostrophe-word 2026-11-20 09:45:38 -05:00
dfgodvan 41e2164cd0 Merge branch 'main' into w1/list-number-no-kern 2026-11-19 23:22:36 +03:00
dfgodvan 861bed3fdd Merge main into fix/legacy-tables-at-page-foot 2026-11-19 23:17:29 +03:00
jayzed80 6010893891 Merge branch 'agyreview/6446' into HEAD
# Conflicts:
#	crates/ui-egui/src/app/commands.rs
2026-11-19 16:25:25 +00:00
jayzed80 8427de0edb Address review: require explicit path for copies and compare host copy basename (#6131) 2026-11-19 16:14:05 +00:00
jayzed80 1789fd7b4d #6463: an all-blank row keeps its TR and cells in a tagged table 2026-11-19 16:07:59 +00:00
jayzed80 83676d584a Merge remote-tracking branch 'upstream/main' into fix/pdf-table-tags-6463 2026-11-19 15:49:47 +00:00
jayzed80 ec29711caf Merge branch 'agyreview/6628' into HEAD
# Conflicts:
#	docs/layout-parity.md
2026-11-19 10:25:31 +00:00
jayzed80 2bce6ed613 Docs: qualify wrapped-tab float-skip parity entry with 50-span limit (#6577) 2026-11-19 10:09:54 +00:00
jayzed80 f674177095 Layout: binary-search the run when checking East Asian font coverage (#6591) 2026-11-19 04:34:29 +00:00
jayzed80 03b20a6ca9 #6577: limit the clear-of-float tab skip to stops past the right indent
A left tab whose stop is inside the right indent but past a span narrowed
by a float could take the new skip too, moving its text to a line clear of
the object. The guard now also requires the stop to be past the paragraph's
right text edge, which is the scope the change describes.

Test: a_left_tab_inside_the_right_indent_beside_a_float_keeps_its_line.
The parity row no longer claims the Word comparison was made.
2026-11-19 03:54:39 +00:00
jayzed80 e27a3bbdfc Merge upstream/main into fix/tab-past-indent-float-6577 2026-11-19 03:40:46 +00:00
jayzed80 c93359d997 Merge remote-tracking branch 'upstream/main' into fix/export-copy-6131
# Conflicts:
#	crates/engine/src/cmd/file.rs
#	crates/engine/src/tests.rs
#	crates/ui-egui/src/app/commands.rs
#	crates/ui-egui/src/file_dialogs.rs
2026-11-19 00:11:41 +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 2e9699c519 Merge remote-tracking branch 'upstream/main' into HEAD
# Conflicts:
#	docs/layout-parity.md
2026-11-18 21:30:04 +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
Kevin Joseph 4afcb2812f docs: widow/orphan control in a split footnote, and the page's first note that gives it up 2026-11-18 15:58:28 +01:00
Kevin Joseph 834c8054cf Footnotes: the beneath-text test asserts the separator's gap; docs say the bottom margin is for page-bottom notes 2026-11-18 15:48:40 +01:00
FredApps d789f82465 Merge remote-tracking branch 'origin/main' into pr-2340 2026-11-18 21:05:53 +07:00
Kevin Joseph 540bd57931 Layout: a page of continued notes is aligned once, before its notes go on it
A centred or bottom-aligned section whose last note continued over pages of notes alone moved
each such page down again when the next one started, its notes past the bottom margin.
finish_pages now finishes every page through finish_page, which aligns it and then leaves it
top-aligned. Tests: the bottom-margin test also runs with widow control and checks every note
line is placed once; a note beneath the text stays under it when it continues.
2026-11-18 14:22:41 +01: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
Kevin Joseph 11790205d1 Merge remote-tracking branch 'origin/main' into fix/footnote-continued-bottom
# Conflicts:
#	docs/layout-parity.md
2026-11-18 14:04:31 +01:00
dotCooCoo b73210feeb DOCX: a frame shape in a note separator opens as a rectangle
A footnote or endnote separator is now converted through the same block
mapping as the body, so a picture frame shape in a separator opens as a
rectangle. Before, the file failed to open with "unknown variant `frame`".
2026-11-17 22:46:40 -08: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 <[email protected]>
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
Martin Ball af9dca95de Merge branch 'main' into fix/right-tab-beyond-indent 2026-11-17 16:59:34 +01:00
Mauro MazzieriandClaude Opus 5.5 6eb03bf4ea Merge storytold/wordcraft main
Resolves the docs/layout-parity.md status line and revision history.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JesQG7ckr7g2qSfBwGkTqM
2026-11-17 15:50:22 +00:00
Michael Higgins 9d005a6a40 Merge branch 'fix/6516-toggle-first-character' of https://github.com/Higgs32584/wordcraft into fix/6516-toggle-first-character 2026-11-17 09:58:23 -05: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 <[email protected]>
2026-11-17 21:49:39 +07:00
dotCooCoo 0bef53685f Mail merge: note that an ODS float merges its value, not its formatted text 2026-11-17 06:41:27 -08:00
Michael Higgins f0b5298dc4 Merge storytold/wordcraft main into fix/6517-typographic-apostrophe-word 2026-11-17 09:35:35 -05:00
Michael Higgins 95d1c1b4be Merge storytold/wordcraft main into fix/6516-toggle-first-character 2026-11-17 09:35:27 -05:00
dotCooCoo b664721fb1 Mail merge: test that an ODS date with two zones reads its text
An OpenDocument date cell whose office:date-value ends in both an
offset and Z, in either order, reads as the cell's text through
read_rows. A date with one offset still reads its value.
2026-11-17 05:06:52 -08:00
dotCooCoo 1abb47e788 Mail merge: a date value with two timezone suffixes is rejected
A time that ends in both an offset and Z (13:45:00+02:00Z) now falls
back to the cell text instead of reading as 13:45. A zone offset must
be two-digit hh:mm, so +2:00 also falls back. The table test unwraps
craft_ods::testing::spreadsheet, which returns a Result since the
craft-libs update on main.
2026-11-17 05:00:50 -08:00
Martin Ball 2c7df2fb96 Merge branch 'main' into fix/ods-typed-values 2026-11-17 13:43:03 +01:00
Martin Ball f2c9880298 Merge branch 'main' into w1/list-number-no-kern 2026-11-17 11:36:41 +01:00
Martin Ball 1392290eec Merge branch 'main' into fix/right-tab-beyond-indent 2026-11-17 08:53:46 +01:00
Martin Ball afaea9484c Merge branch 'main' into fix/ods-typed-values 2026-11-17 08:26:51 +01:00
Martin Ball 609aa80e5e Merge branch 'main' into fix/6516-toggle-first-character 2026-11-17 07:25:19 +01:00
Martin Ball cdec6b459f Merge branch 'main' into w1/list-number-no-kern 2026-11-17 07:23:13 +01:00
Martin Ball 3310e9f5ee Merge branch 'main' into fix/right-tab-beyond-indent 2026-11-17 05:33:56 +01:00
ljkx 554a7d689e #6331: CREATEDATE reads a creation date without seconds
W3CDTF allows hh:mm without seconds (2019-05-05T12:00Z), which
parse_from_rfc3339 refuses, so such a file kept its cached result.
created_at now reads that form too, with Z or an offset.
2026-11-17 04:32:55 +01:00
ljkx 2c32076416 #6331: layout-parity status line and revision row for CREATEDATE at the top 2026-11-17 04:32:54 +01:00
ljkx 19b8dfece6 Merge remote-tracking branch 'upstream/main' into fix/createdate-keeps-date 2026-11-17 04:32:14 +01:00
Michael Higgins 82567c2c61 Merge storytold/wordcraft main into fix/6517-typographic-apostrophe-word 2026-11-16 08:50:04 -05:00
Michael Higgins 376a714e73 Merge storytold/wordcraft main into fix/6516-toggle-first-character 2026-11-16 08:50:01 -05:00
dotCooCoo 9a81b9a88d Mail merge: an ODS zone offset past 14:00 falls back to the cell text
A date or time zone offset is at most 14:00, as XML Schema allows, so `2024-03-05+14:01` and `13:45:00-15:00` keep the cell's text, and `+14:00` still reads.
2026-11-14 13:42:45 -08:00
dotCooCoo 100dfb3c42 Mail merge: ODS dates keep a zone-suffixed date, and leap seconds and an empty T fall back
A date alone may carry a Z or +hh:mm zone, which is left out. A leap second (23:59:60) and a duration with nothing after T (P1DT) are not times, so the cell's text is used.
2026-11-14 13:28:01 -08:00
dotCooCoo e88b44df12 Mail merge: OpenDocument cells read their typed values
An OpenDocument recipient list showed each cell's displayed text
whenever it had any, so dates, times, floats and booleans came out in
the file's locale format, and a covered cell showed its hidden text.

Floats and booleans read their values again, dates and times read as
ISO 8601 (a duration's days counted as hours), strings, percentages
and currencies keep their text, and a covered cell is blank. A value
that is not a valid date, time or duration falls back to the text.
2026-11-14 13:12:47 -08:00
FredApps 2cde91a869 Release: WordCraft v0.19.0 (main 323cf78232) 2026-11-14 21:48:03 +01:00
FredApps 76e5732355 Release: WordCraft v0.19.0 2026-11-14 21:48:00 +01:00
dfgodvan bc0c9e4da5 Lists: a list number is never kerned, as in Word
A list number took the kerning of its paragraph mark or level. Word never kerns
it: "11)" in Times New Roman 12 pt with kerning on is 16 pt wide in Word, not
the 15.55 pt of the kerned digits, so it passes a hanging indent the kerned one
would fit in and the text moves on to the next tab stop.

Test: a_list_number_is_never_kerned (fails before this change).
2026-11-14 19:16:10 +03: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 7f8283a77f Layout: a left tab past the right indent beside a float moves clear of it (#6577)
A left tab whose stop is past the right indent wraps to start the next
line. When that line was the span on a floating object's far side, the
tab took no room there and its text started beside the object. Like
Word, the tab now goes on to the first line clear of the object, where
its text starts at the indent.

Test: left_tab_past_the_right_indent_beside_a_float_moves_clear_of_it.
2026-11-14 06:48:10 +00:00
jayzed80 833082618a Address review: refuse a copy with no path, and a host copy named like the opened file (#6131) 2026-11-14 01:36:18 +00:00
jayzed80 b687f1cd6f Address review: keep separated link runs in separate Link elements (#6464) 2026-11-14 01:18:00 +00:00
jayzed80 c7b4310dc1 Address review: keep a TD/TH for blank table cells (#6463) 2026-11-14 01:07:13 +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 778ccf6db3 pdf: tag tables with Table, TR, TH and TD structure elements (#6463) 2026-11-13 23:28:06 +00:00
jayzed80 8f8bec4ad7 Tag PDF link annotations with Link and OBJR (#6464) 2026-11-13 23:04:30 +00:00
Michael Higgins da295eb0c5 #6517: a chosen synonym keeps the quotes around the word
The thesaurus lookup and the context menu's synonym replacement now share
one range, review::thesaurus_word: the word unit without the spaces after
it or the quotes around it. Replacing good in ‘good’ gives ‘fine’, not
‘fine (review on #6520).
2026-11-13 11:22:03 -05:00
Michael HigginsandClaude Opus 5.5 022be202c1 #6517: the thesaurus looks up a quoted word without its quotes
The word unit now keeps a typographic quote at its ends, so the caret word
in ‘good’ is good’. The thesaurus lookup trims enclosing quotes and keeps
an apostrophe inside the word (review on #6520).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 11:08:43 -05:00
Michael HigginsandClaude Opus 5.5 824a5e2c1d #6516: pin that a selection from an empty paragraph follows its first text
Word ignores an empty paragraph's mark at the start of the selection and
decides from the first text character (review on #6519).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 11:01:00 -05:00
Michael HigginsandClaude Opus 5.5 a620ad3587 #6517: a typographic apostrophe is part of the word at the caret
Bold and the other character formats at a caret, and double-click's word
unit (Paragraph::word_at), now treat U+2019 like a straight apostrophe, as
Word does. is_word_char is unchanged, so Ctrl+Arrow and Ctrl+Backspace/Delete
keep their behaviour.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 10:51:20 -05:00
Michael HigginsandClaude Opus 5.5 7612fe17db #6516: toggles on a partly formatted selection follow its first character
Word decides Bold, Italic, Underline and the other character toggles on a
selection from its first character in document order: if it has the format,
the whole selection loses it; otherwise the whole selection gets it.
WordCraft turned the format on unless every selected character had it.
A caret keeps its existing rule, explicit values still set, and the ribbon
state is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 10:48:08 -05:00
dfgodvan f4862c6b0e Line spacing: a multiple adds a multiple of the tallest run, not of a mixed line
A line mixing fonts is as tall as the tallest ascent over the deepest descent of its runs, more
than any one run's own height. At multiple spacing Word adds (m - 1) x the tallest run's own
height to it, not (m - 1) x the mixed line's: 10pt Times New Roman with a 10pt Courier New run
steps 18.09pt at 1.5 spacing and 23.84pt at double in Word for Windows, where multiplying the
12.34pt line gives 18.51 and 24.68; in Word for Mac the 12.24pt line steps 17.97 and 23.69pt
(12.24 + 0.5 x 11.49 and + 11.49, Times New Roman being the taller run). The paragraph mark's
font doesn't matter.

Test: multiple_spacing_adds_a_multiple_of_the_tallest_run_not_of_the_mixed_line (fails before
this change).
2026-11-13 00:08:35 +03:00
dfgodvan 7fd2dc9127 layout: a letter ending a line keeps the half of its kerning pair with the letter before
A shaper splits a pair from an old-style kern table between its two letters, half in the first
one's advance and half in the second one's advance and offset. The kerning kept for the line-end
measure (a letter ending a line inside a word is measured without its pair with the next) took the
second letter's half for its pair with the next letter, so a letter after a kerned pair was measured
wider than it is at the end of a line. Word for Windows, a font with only a kern table: Word set
"...3Vy" of a base64 token on one line, WordCraft moved the "y" on.

Test: a_letter_ending_a_line_keeps_its_pair_with_the_letter_before (fails before this change).
2026-11-12 23:53:33 +03:00
dfgodvan f420ef4d6a Fonts: a character Times New Roman's twin lacks keeps the twin's line height
Liberation Serif 2.1 lacks "₽", and 1.07 also "‒", which Times New Roman has: Word sets them
in Times New Roman and the line is as tall as its, while WordCraft drew them from the UI sans
fallback (1.326 em against 1.150), 2.5-3.3pt taller at 14pt. The glyph still comes from the
fallback (Source Sans 3 "₽" and "‒" are 0.497 em wide against Times New Roman's 0.5); the
line takes the run's font metrics. East Asian fallback faces keep their own height.

Test: times_twin_fallback::a_twin_fallback_keeps_the_twins_line_height (fails before this
change).
2026-11-12 23:51:38 +03:00
dfgodvan 6a35fc23a7 Layout: a multiple-spaced line's leading may run past a footer above the margin
Word lets the leading of a page's last line with multiple spacing above single run into the
bottom margin (fit_height). It lets it run past the top of a footer that reaches above the
margin just the same: only the text has to end above the footer, whatever the footer holds (a
page number, several lines of text, an empty exact-height paragraph). WordCraft kept the whole
line clear of such a footer and moved it to the next page.

Measured in Word for Mac and Windows: a 1.5-spaced 12pt line pushed down by half a point at a
time stays on the page while its text ends above the footer, with a one-line page-number footer
6.6pt and 28pt above the margin, a four-line footer and an empty 120pt exact-height paragraph;
with a title-page footer, the first page's own footer counts there.

The page builder keeps the leading's floor as the page starts: the bottom margin, or the top of
that page's footer when it is higher.

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

Test: a_word_broken_by_letters_ends_without_its_kerning_pair (fails before this change).
2026-11-12 23:46:48 +03:00
dfgodvan 979077101f Layout: tables at the foot of a page before Word 2013 layout
Measured in Word for Mac with synthetic documents in compatibility modes 12
and 14 (and a document that doesn't state one): a row split across pages
divides its cells' text at any line, with no widow/orphan control in the
cells; the repeated header rows stay alone at the foot of a page when no line
of the first row fits under them; and a paragraph kept with the table keeps
with the header rows only (and the border below them, as placing them needs).
Mode 15 (Word 2013 layout) is as before.
2026-11-12 23:22:02 +03:00
dfgodvan c120c09423 Layout: a right tab past the right indent takes its text up to the stop, as in Word
A TOC entry in Word's TOC styles has a right indent and a right tab with a dot leader at
the margin, past that indent. Word keeps the page number on the entry's line whenever it
fits between the text and the stop, so the number ends past the indent. WordCraft checked
the first character after the tab against the right indent (the tab has no room yet), and
moved the tab and its number to the next line when the text ended less than a digit short
of the indent.

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

Text after a right or decimal tab now fits while it ends before the stop. The running
shift of the tab also no longer counts the tab's own room as text: it dropped back to
nothing after every second character, so those characters were checked against the
indent as well. A tab whose text is pending starts with no room on the line it goes to.
2026-11-12 23:12:43 +03:00
jayzed80 61ef4aab3c #6131: File > Export to DOCX, ODT or RTF writes a copy and keeps the document's file
Export ran a plain Save As, which made the exported file the document's file and cleared its unsaved changes, so the next Save went to the copy. file.save and file.saveAs take "copy": true, which writes the file and leaves the document's path, unsaved state and save stamps alone. Export uses it on the desktop and in the browser.
2026-11-12 15:25:09 +00:00
ljkx 1336bc27cb #6331 review: CREATEDATE in documents from templates, opened files without a date, date-only values
A document made from a template no longer inherits the template's creation
date: it has none until it is saved, so CREATEDATE shows today. A file
opened without a creation date keeps the field's cached result, as one with
an unreadable date already did; only a new, never-saved document uses
today. A date-only creation date (2019-05-05, which W3CDTF allows) shows as
that calendar day in every time zone. The test's expected date for
12:00 UTC now follows the local offset, so it passes east of UTC+12 too.
2026-11-12 14:16:39 +01:00
Dylan M. Taylor 079f478bd8 Merge tested main for v0.18.1 2026-11-11 18:38:09 -05:00
FredApps 7296cf64de Merge main into release for WordCraft v0.18.0 2026-11-11 19:36:24 +01:00
ljkx a525210f48 #6331: Updating fields keeps CREATEDATE on the document's creation date
CREATEDATE is formatted from the document's creation date (dcterms:created) in local time, not from the clock. A creation date that can't be read keeps the field's result; a document never saved (no creation date yet) still shows today.
2026-11-11 19:03:44 +01:00
Mauro MazzieriandClaude Opus 5.5 892235af06 Different first page: a continuous section whose first paragraph runs over still began on the page before
Addresses the CodeRabbit review: the run-over case (with a regression test) and the even-page header in docs/layout-parity.md.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JesQG7ckr7g2qSfBwGkTqM
2026-11-11 16:53:42 +00:00
Mauro MazzieriandClaude Opus 5.5 e14f85661b Merge storytold/wordcraft main
Resolves the docs/layout-parity.md status line and revision history.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JesQG7ckr7g2qSfBwGkTqM
2026-11-11 16:44:02 +00:00
Kevin Joseph 6997afcc34 Word for Mac 16.114.4 is the version these were measured in, not 16.113.4
The commit messages before this one name 16.113.4 too; the measurements were made in the Word
for Mac installed here, which reports 16.114.4.
2026-11-09 16:11:28 +01:00
Mauro Mazzieri d3096ed0fb Merge remote-tracking branch 'origin/main' into claude/continuous-section-first-page-header
# Conflicts:
#	crates/layout/src/table_flow.rs
#	docs/layout-parity.md
2026-11-09 15:48:45 +01:00
Kevin Joseph 0074cb6ac6 Layout: orphan control in a footnote split across pages
Rather than leave a note paragraph's first line alone at the bottom of a page, Word for Mac
16.113.4 moves the line holding the reference on to the next page with it. WordCraft kept the
line and one note line on the page. The least of a note that stays with its reference is now
two lines of a paragraph with widow/orphan control (or the paragraph whole); the page's first
note still splits where it must rather than overrun the page.

Found by the word-compare footnotes probe, which now matches Word line for line (it differed
by up to 37.6 pt on page 1, one body line on the wrong page). The 30 footnote-split probes
still match.

Test: orphan_control_keeps_two_lines_of_a_split_footnote_with_its_reference, failing without
the change.
2026-11-09 13:49:31 +01:00
Kevin Joseph 3c44fc6443 Layout: a continued footnote ends on the bottom margin; widow control in it
When a footnote continues on the next page, Word for Mac 16.113.4 keeps the note area's last
line on the page's bottom margin and leaves the room above the separator; WordCraft placed the
notes right under the text. With widow control in the note's paragraph, Word takes one more line
along rather than leave its last line alone on the next page; WordCraft left it alone.

Measured with cargo xtask word-compare: a long footnote whose reference moves down the page one
body line at a time (Georgia 11, notes 9, widow control on and off), 30 documents; all 30 now
match Word's PDFs line for line (9 differed in the note area's position, 1 in its line breaks).

Tests: a_footnote_continuing_on_the_next_page_ends_on_the_bottom_margin and
widow_control_leaves_two_lines_of_a_split_footnote_on_the_next_page, each failing without its
half of the fix.
2026-11-09 13:30:03 +01:00
Dylan M. Taylor 5574b32600 Release 0.17.0 2026-11-09 06:34:22 -05: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
Mauro MazzieriandClaude Opus 5.5 dc515b6128 Different first page: no first-page header on a continuous section's second page
A page is its section's first page, the one a different first page's header and footer go on,
only if the section begins on it. A page's section is the one at its top, so a section that
starts continuously part-way down a page was taken to begin on the next page, which then showed
the section's first-page header. Word shows the earlier section's header on the page where the
section starts and the section's default header from the next page on: the first-page header of
such a section is never seen (checked in Word for Windows 365 on a synthetic file).

begins_section compares the section's first block with the page's first block, and serves the
drawn headers and footers, header-table obstacles and footer-table wraps alike.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 10:36:33 +01:00
VoiceLessQ 1603a5f34f AutoSave: only an open that read a file records it
file.open with a null path only asks for the Open picker, and its
result has no alreadyOpen, so the check recorded the shown document's
path as read from disk: a document opened from bytes then passed the
AutoSave switch's check. The path must now be a string and alreadyOpen
false. A data value that isn't a string is ignored by the engine,
which reads the file from disk, so it no longer clears the record.
2026-10-29 16:25:01 -02:00
VoiceLessQ d5239891f6 AutoSave: switching it off holds for that document
The AutoSave preference is shared by all documents, but each keeps its
own go-ahead (the file it may write). Switching AutoSave off cleared
only the preference, so turning it on in another document brought it
back for the first one too, which then wrote its file with its switch
showing off. Switching off now also withdraws the document's go-ahead.
Turning it back on covers the same file again without a save, since
the document was read from or saved to it.
2026-10-29 15:30:43 -02:00
VoiceLessQ 9c7ec843b6 AutoSave: the switch covers only a file the document was read from
file.open with data only names the file (the bytes come with the call),
but the name becomes the document's path, and since #3307 the AutoSave
switch gave the go-ahead to write it. A control-channel caller could
open any bytes under the name of an existing .docx, and turning AutoSave
on then wrote over that file. The window now notes, per document, the
file it was read from or saved to, and the switch's go-ahead needs the
path to be that file. A document opened from bytes still gets AutoSave
after an explicit save.
2026-10-29 15:30:34 -02:00
VoiceLessQ 777fedb14a Engine tests: the fuzz also fails on a panic in a command another ran
Review of #4207. Commands run other commands through Session::run
(outline.promote runs para.promote), and the inner guard names the inner
command: "para.promote panicked: ...". run_junk only looked for the
fuzzed command's own id, so such a panic passed. caught_panic now takes
any registered command's id before " panicked: "; an error that only
echoes those words (developer.control quoting its input) still doesn't
count.
2026-10-29 14:23:50 -02:00
VoiceLessQ 02de1488cb Merge origin/main 2026-10-29 14:21:19 -02:00
VoiceLessQ 9c05751014 Merge origin/main
Main split lib.rs and chrome.rs, so the AutoSave changes now live in app/files.rs, state.rs, tests.rs and chrome/tests.rs.
2026-10-27 16:39:42 -02:00
VoiceLessQ 6d51d93bb6 AutoSave: a value that isn't true or false is an error (#3307)
`file.autosave` read `value` with as_bool and toggled when that gave nothing. Since the switch can now turn AutoSave on for a file only opened here, `{"value":"false"}` on such a file turned it on and gave AutoSave the go-ahead to rewrite it. A missing value still toggles; anything other than a bool is now refused, the way the focus ribbon and other ui commands already do it. Found in review.

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

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

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

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

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

Tests: making edit.repeat panic on null params fails the fuzz with
"edit.repeat panicked: mutation"; before this change the same mutation
passed.
2026-10-24 21:00:37 -01:00
Divyanshu Gupta ab35bfa946 fix(doc): format hex number format as uppercase hex and support millions in cardinal text 2026-10-16 07:27:30 +05:30
145 changed files with 10402 additions and 1083 deletions
Generated
+131 -145
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 = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
wordcraft-engine = { path = "crates/engine" }
wordcraft-mcp = { path = "crates/mcp" }
wordcraft-zotero = { path = "crates/zotero" }
wordcraft-control-key = { path = "crates/control-key" }
wordcraft-ui-egui = { path = "crates/ui-egui" }
wordcraft-validate = { path = "crates/validate" }
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", default-features = false }
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", default-features = false }
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
# foundation
kurbo = { version = "0.13", features = ["serde"] }
@@ -85,28 +85,28 @@ wuff = "0.2.9"
brotli-decompressor = "5"
vello_cpu = "0.2"
image = { version = "0.25", default-features = false }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", default-features = false, features = ["write"] }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", default-features = false, features = ["write"] }
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", features = ["doc"] }
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", features = ["text"] }
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", features = ["flow"] }
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", features = ["detect"] }
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", features = ["doc"] }
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", features = ["text"] }
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", features = ["flow"] }
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", features = ["detect"] }
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
# zlib streams (compressed metafile pictures in `.doc` drawings); already in the lock as a dependency of other crates.
miniz_oxide = "0.9"
cfb = "0.15"
@@ -174,27 +174,27 @@ debug = 0
# The framework's patches, which Cargo does not carry over to dependents: its vendored crates from craft-libs,
# and the egui and winit forks it builds with.
[patch.crates-io]
krilla = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
hayro = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
emath = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
winit = { git = "https://github.com/storytold/winit.git", rev = "0dfcec0eb62fda5904137a63a6dd0c3d83295f45" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
hayro = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
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" }
+128 -14
View File
@@ -10,6 +10,7 @@ use std::net::TcpListener;
use std::path::{Path, PathBuf};
use std::sync::mpsc::Receiver;
use craft::automation::AutomationError;
use craft::automation::args::ControlOptions;
use craft::automation::control::ControlRequest;
use craft::automation::server::{Listening, serve};
@@ -38,6 +39,22 @@ fn remove(path: Option<&Path>) {
}
}
/// Why starting the control server did not succeed.
enum StartError {
/// Windows external-tool timeout while creating or checking the owner-only token file.
TokenTimeout(String),
/// Any other bind, token, or accept-thread error.
Other(String),
}
impl StartError {
fn message(&self) -> &str {
match self {
Self::TokenTimeout(msg) | Self::Other(msg) => msg,
}
}
}
/// Bind `127.0.0.1:port`, settle the token and serve. `None` when the port cannot be bound or
/// the token cannot be set up (the control channel is off); a taken port leaves no token file.
///
@@ -45,35 +62,49 @@ fn remove(path: Option<&Path>) {
/// `port` in `settings`; a file left by a run that did not exit cleanly is replaced. Without a
/// settings folder a fresh token is generated and reported by the log.
pub fn start(options: &ControlOptions, port: u16, host: WindowHost, settings: Option<&Path>) -> Option<(Receiver<ControlRequest>, Control)> {
let listener = match TcpListener::bind(("127.0.0.1", port)) {
Ok(l) => l,
Err(e) => {
log::error!("control server failed to bind 127.0.0.1:{port}: {e}");
return None;
match start_with(options, port, host, settings, ControlOptions::server_token) {
Ok(started) => Some(started),
Err(err) => {
log::error!("{}", err.message());
None
}
};
}
}
fn start_with(
options: &ControlOptions,
port: u16,
host: WindowHost,
settings: Option<&Path>,
token_for: impl FnOnce(&ControlOptions) -> Result<String, AutomationError>,
) -> Result<(Receiver<ControlRequest>, Control), StartError> {
let listener =
TcpListener::bind(("127.0.0.1", port)).map_err(|e| StartError::Other(format!("control server failed to bind 127.0.0.1:{port}: {e}")))?;
let created = settings.filter(|_| options.token.is_none() && options.token_file.is_none()).map(|dir| wordcraft_control_key::key_path(dir, port));
// The port was free, so no other run owns a file left here.
remove(created.as_deref());
let effective = ControlOptions { token_file: created.clone().or_else(|| options.token_file.clone()), ..options.clone() };
let token = match effective.server_token() {
let token = match token_for(&effective) {
Ok(t) => t,
Err(e) => {
remove(created.as_deref());
log::error!("control server off: {e}");
return None;
let msg = format!("control server off: {e}");
return Err(if matches!(&e, AutomationError::Io(text) if text.contains("did not finish within ")) {
StartError::TokenTimeout(msg)
} else {
StartError::Other(msg)
});
}
};
let notice = effective.token_notice(&token);
match serve(listener, token, host) {
Ok((rx, listening)) => {
log::info!("control server listening on {}, {notice}", listening.addr);
Some((rx, Control { listening, created }))
Ok((rx, Control { listening, created }))
}
Err(e) => {
remove(created.as_deref());
log::error!("control server off: cannot start the accept thread ({e})");
None
Err(StartError::Other(format!("control server off: cannot start the accept thread ({e})")))
}
}
}
@@ -87,6 +118,41 @@ mod tests {
WindowHost::of(&egui::Context::default())
}
/// Attempts for `start_with` when Windows `owner_only` hits its 10 s external-tool limit on
/// a busy CI runner (#8556). Non-timeout failures stop on the first attempt.
const TOKEN_TIMEOUT_ATTEMPTS: usize = 3;
fn try_start_retrying_token_timeout(
options: &ControlOptions,
port: u16,
host: WindowHost,
settings: Option<&Path>,
mut token_for: impl FnMut(&ControlOptions) -> Result<String, AutomationError>,
) -> Result<(Receiver<ControlRequest>, Control), (usize, StartError)> {
let mut attempt = 1;
loop {
match start_with(options, port, host.clone(), settings, &mut token_for) {
Ok(started) => return Ok(started),
Err(StartError::TokenTimeout(msg)) if attempt < TOKEN_TIMEOUT_ATTEMPTS => {
log::warn!("retrying control server start after Windows token-file timeout ({attempt}/{TOKEN_TIMEOUT_ATTEMPTS}): {msg}");
attempt += 1;
}
Err(err) => return Err((attempt, err)),
}
}
}
fn start_retrying_token_timeout(
options: &ControlOptions,
port: u16,
host: WindowHost,
settings: Option<&Path>,
token_for: impl FnMut(&ControlOptions) -> Result<String, AutomationError>,
) -> (Receiver<ControlRequest>, Control) {
try_start_retrying_token_timeout(options, port, host, settings, token_for)
.unwrap_or_else(|(attempt, err)| panic!("control server start failed on attempt {attempt}: {}", err.message()))
}
#[test]
fn the_token_file_is_written_after_the_bind_and_removed_on_exit() {
let dir = std::env::temp_dir().join(format!("wordcraft-control-life-{}", std::process::id()));
@@ -101,7 +167,7 @@ mod tests {
drop(taken);
// Bound: the default file holds the token that opens the port.
let (_rx, control) = start(&options, 0, host(), Some(&dir)).unwrap();
let (_rx, control) = start_retrying_token_timeout(&options, 0, host(), Some(&dir), ControlOptions::server_token);
let path = control.created.clone().unwrap();
assert_eq!(path, wordcraft_control_key::key_path(&dir, 0));
let token = std::fs::read_to_string(&path).unwrap();
@@ -117,13 +183,61 @@ mod tests {
// A token file the user supplied stays.
let supplied = dir.join("supplied-token");
let options = ControlOptions { token_file: Some(supplied.clone()), ..ControlOptions::default() };
let (_rx, control) = start(&options, 0, host(), Some(&dir)).unwrap();
let (_rx, control) = start_retrying_token_timeout(&options, 0, host(), Some(&dir), ControlOptions::server_token);
assert!(control.created.is_none());
control.shut_down();
assert!(supplied.exists());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_transient_token_file_timeout_retries_while_other_errors_stop() {
let dir = std::env::temp_dir().join(format!("wordcraft-control-retry-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let options = ControlOptions::default();
// A Windows `owner_only` external-tool timeout retries and recovers on a later attempt.
let mut timeout_then_ok = 0usize;
let (_rx, control) = start_retrying_token_timeout(&options, 0, host(), Some(&dir), |effective| {
timeout_then_ok += 1;
if timeout_then_ok == 1 {
let path = effective.token_file.as_ref().unwrap();
Err(AutomationError::Io(format!(
"{}: cannot create the control token file for its owner only: powershell.exe did not finish within 10 s and was ended",
path.display()
)))
} else {
Ok(TOKEN.to_string())
}
});
assert_eq!(timeout_then_ok, 2);
control.shut_down();
// Repeated timeouts stop after `TOKEN_TIMEOUT_ATTEMPTS` instead of looping forever.
let mut exhausted = 0usize;
let Err((attempt, err)) = try_start_retrying_token_timeout(&options, 0, host(), Some(&dir), |_| {
exhausted += 1;
Err(AutomationError::Io("powershell.exe did not finish within 10 s and was ended".into()))
}) else {
panic!("exhausted timeouts must fail");
};
assert_eq!((attempt, exhausted), (TOKEN_TIMEOUT_ATTEMPTS, TOKEN_TIMEOUT_ATTEMPTS));
assert!(matches!(err, StartError::TokenTimeout(_)));
// Non-timeout failures stop on the first attempt.
let mut other = 0usize;
let Err((attempt, err)) = try_start_retrying_token_timeout(&options, 0, host(), Some(&dir), |_| {
other += 1;
Err(AutomationError::Io("permission denied".into()))
}) else {
panic!("non-timeout error must fail");
};
assert_eq!((attempt, other), (1, 1));
assert!(matches!(err, StartError::Other(msg) if msg.contains("permission denied")));
let _ = std::fs::remove_dir_all(&dir);
}
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
fn boot() -> (u16, Receiver<ControlRequest>, Control) {
+195 -134
View File
@@ -152,6 +152,21 @@ impl eframe::App for App {
}
}
/// Files dropped on a document window. eframe hands `raw_input_hook` only the root's and deferred
/// viewports' input, and document windows are immediate viewports (every one under the windowless
/// root), so their drops come through this hook. It runs first and takes the batch, so nothing reads
/// it twice.
struct ChildDrops(IntakeSender);
impl eframe::ViewportHooks for ChildDrops {
fn raw_input(&self, _ctx: &egui::Context, raw: &mut egui::RawInput) {
if raw.viewport_id != egui::ViewportId::ROOT && !raw.dropped_files.is_empty() {
self.0.dropped(dropped_files(raw));
raw.dropped_files.clear();
}
}
}
/// The files dropped in this frame's input, as the intake carries them: a file with a path by its
/// path, a file without one by its bytes.
fn dropped_files(raw: &egui::RawInput) -> Vec<DroppedFile> {
@@ -463,6 +478,46 @@ fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
Some(launch_profile::passthrough_args(early.passthrough_args, had_separator))
}
/// Runs the app with the windowless root when `windowless` is set, and with the visible root when it is not. eframe
/// refuses a windowless root on a session that cannot run it before it calls the creator, which then stays in its
/// cell for a retry with the visible root: the app always starts.
fn run_with_visible_root_fallback(
creator: eframe::AppCreator<'static>,
windowless: Arc<std::sync::atomic::AtomicBool>,
mut options: eframe::NativeOptions,
) -> eframe::Result {
use std::sync::atomic::Ordering::Relaxed;
let creator = std::rc::Rc::new(std::cell::RefCell::new(Some(creator)));
let name = wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity());
let run = |options: eframe::NativeOptions| {
let creator = creator.clone();
eframe::run_native(
name,
options,
Box::new(move |cc| match creator.borrow_mut().take() {
Some(create) => create(cc),
None => Err("the app was already created".into()),
}),
)
};
let on = windowless.load(Relaxed);
// The clone keeps no event-loop hook, which only the X11 start sets and that start is windowed.
let mut visible_root = on.then(|| options.clone());
if on {
options.root_viewport_mode = eframe::RootViewportMode::Windowless;
}
let result = run(options);
if let Err(eframe::Error::UnsupportedConfiguration(reason)) = &result
&& let Some(options) = visible_root.take()
&& creator.borrow().is_some()
{
log::warn!("windowless root unavailable ({reason}); starting with a visible root window");
windowless.store(false, Relaxed);
return run(options);
}
result
}
/// Parses the command line, installs logging and the panic hook, restores preferences and window
/// geometry, opens requested documents or the Start screen, starts the control server when
/// asked, and runs the eframe event loop.
@@ -676,6 +731,7 @@ fn main() -> eframe::Result {
// Registered before the event loop starts, so it catches the Finder event that launched us as
// well as later ones. Lives until the event loop returns.
let drops = intake.sender();
options.viewport_hooks = Some(Arc::new(ChildDrops(drops.clone())));
#[cfg(target_os = "macos")]
let _apple_events = craft::platform::open::apple_events::install(sender);
#[cfg(not(target_os = "macos"))]
@@ -705,147 +761,152 @@ fn main() -> eframe::Result {
let noticed_for_exit = unclean_notice_shown.clone();
let noticed_in_window = unclean_notice_shown.clone();
let exit_settings = settings.clone();
let result = eframe::run_native(
wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity()),
options,
Box::new(move |cc| {
let ctx = cc.egui_ctx.clone();
let _ = repaint.set(ctx.clone());
let wake = {
let ctx = ctx.clone();
move || ctx.request_repaint()
};
// The interface language: the saved choice, else the system's.
let lang = wordcraft_ui_egui::i18n::Lang::from_pref(&settings.lock().get().language);
let (file_service, panels) = FileService::new(Wake::new(wake.clone()));
let host = Arc::new(
Host::builder(wordcraft_ui_egui::APP)
.i18n(wordcraft_ui_egui::i18n::catalogs())
.files(Arc::new(file_service))
.settings(Arc::new(settings.clone()))
.lang(lang.craft_lang())
.build(),
);
let shell = ShellInfo::current().backend(if x11 { Backend::X11 } else { Backend::from_env() });
let spec = InstallSpec::new(shell, Arc::new(SystemWindows))
.app_id(wordcraft_ui_egui::os_window::app_id())
.system(SystemReader::start(wake))
.clipboard(Clipboard::new(SystemClipboard::new().decoder(decode_png)))
.placement(placement);
// PLAN: assumed `wordcraft_ui_egui::ui_fonts` re-exports sh.A10's `app::fonts::ui_fonts` (`mod app` is private; app-hub/shell-w11).
embed::install(&ctx, spec, &wordcraft_ui_egui::ui_fonts(lang)).map_err(|e| format!("the runtime could not be installed: {e}"))?;
// The system region picks the new document's paper, the units and the decimal
// separator (#838).
let region = region::system();
let doc = if sample { wordcraft_engine::sample::sample_document() } else { wordcraft_engine::blank_document(&region) };
let mut session = Session::new(doc);
session.system_region = region;
// The custom dictionary's words (#40) count as loaded settings.
if prefs::enabled()
&& let Some(path) = prefs::user_dict_path()
{
prefs::load_user_dictionary(&mut session, &settings, path);
// The root window is never shown (ADR 0001): eframe runs a windowless root and every document is a child
// window. X11, XWayland and BSD on X11 cannot, so they keep the visible root (the ADR's amendment). The mode
// is read by the app creator, which runs once the mode is settled.
let windowless = Arc::new(std::sync::atomic::AtomicBool::new(!x11));
let windowless_in_app = windowless.clone();
let creator: eframe::AppCreator<'static> = Box::new(move |cc| {
let ctx = cc.egui_ctx.clone();
let _ = repaint.set(ctx.clone());
let wake = {
let ctx = ctx.clone();
move || ctx.request_repaint()
};
// The interface language: the saved choice, else the system's.
let lang = wordcraft_ui_egui::i18n::Lang::from_pref(&settings.lock().get().language);
let (file_service, panels) = FileService::new(Wake::new(wake.clone()));
let host = Arc::new(
Host::builder(wordcraft_ui_egui::APP)
.i18n(wordcraft_ui_egui::i18n::catalogs())
.files(Arc::new(file_service))
.settings(Arc::new(settings.clone()))
.lang(lang.craft_lang())
.build(),
);
let shell = ShellInfo::current().backend(if x11 { Backend::X11 } else { Backend::from_env() });
let mut spec = InstallSpec::new(shell, Arc::new(SystemWindows))
.app_id(wordcraft_ui_egui::os_window::app_id())
.system(SystemReader::start(wake))
.clipboard(Clipboard::new(SystemClipboard::new().decoder(decode_png)))
.placement(placement);
// The runtime and eframe must agree on the root.
if windowless_in_app.load(std::sync::atomic::Ordering::Relaxed) {
spec = spec.windowless_root();
}
// PLAN: assumed `wordcraft_ui_egui::ui_fonts` re-exports sh.A10's `app::fonts::ui_fonts` (`mod app` is private; app-hub/shell-w11).
embed::install(&ctx, spec, &wordcraft_ui_egui::ui_fonts(lang)).map_err(|e| format!("the runtime could not be installed: {e}"))?;
// The system region picks the new document's paper, the units and the decimal
// separator (#838).
let region = region::system();
let doc = if sample { wordcraft_engine::sample::sample_document() } else { wordcraft_engine::blank_document(&region) };
let mut session = Session::new(doc);
session.system_region = region;
// The custom dictionary's words (#40) count as loaded settings.
if prefs::enabled()
&& let Some(path) = prefs::user_dict_path()
{
prefs::load_user_dictionary(&mut session, &settings, path);
}
let spool = Spool::new(host.jobs_shared().clone());
let mut app = WordApp::new(session, services(spool.clone(), intake, nightly)).with_host(host).with_settings(settings.clone());
// Drawn by the processor (WARP, llvmpipe; #2221), animations that follow the system stop.
if let Some(state) = &cc.wgpu_render_state {
let info = state.adapter.get_info();
let software = info.device_type == eframe::wgpu::DeviceType::Cpu;
if software {
log::warn!("graphics: drawing in software on {} ({:?}): animations that follow the system are off", info.name, info.backend);
}
let spool = Spool::new(host.jobs_shared().clone());
let mut app = WordApp::new(session, services(spool.clone(), intake, nightly)).with_host(host).with_settings(settings.clone());
// Drawn by the processor (WARP, llvmpipe; #2221), animations that follow the system stop.
if let Some(state) = &cc.wgpu_render_state {
let info = state.adapter.get_info();
let software = info.device_type == eframe::wgpu::DeviceType::Cpu;
if software {
log::warn!("graphics: drawing in software on {} ({:?}): animations that follow the system are off", info.name, info.backend);
}
app.set_software_drawing(software);
app.set_software_drawing(software);
}
// PLAN: writer note 9 puts `with_settings` after `with_control`; it comes first here because
// the region check below reads the saved region the settings apply.
if std::env::var("WORDCRAFT_FILE_DIALOG").is_ok_and(|v| v.trim().eq_ignore_ascii_case("builtin")) {
app = app.with_fallback_chooser(true);
}
if nightly {
// The Launcher installs Nightly; Help › Check for Updates says so instead.
app.use_launcher_updates();
} else {
app.set_startup_update_check(true);
// After the preferences, so the reason it gives is in the interface language.
if updates_unsafe {
app.disable_self_update();
}
// PLAN: writer note 9 puts `with_settings` after `with_control`; it comes first here because
// the region check below reads the saved region the settings apply.
if std::env::var("WORDCRAFT_FILE_DIALOG").is_ok_and(|v| v.trim().eq_ignore_ascii_case("builtin")) {
app = app.with_fallback_chooser(true);
}
// Language packs from the suite's font store; an Install click is the person's own.
// Nightly keeps its own store in the profile, so a pack installed there is not a
// change to the stable apps' shared fonts.
match launch_profile::current().root() {
Some(root) => wordcraft_engine::packs::use_font_store_in(root.join("FontStore"), true),
None => {
wordcraft_engine::packs::use_font_store(true);
}
if nightly {
// The Launcher installs Nightly; Help › Check for Updates says so instead.
app.use_launcher_updates();
} else {
app.set_startup_update_check(true);
// After the preferences, so the reason it gives is in the interface language.
if updates_unsafe {
app.disable_self_update();
}
}
// A region chosen in File › Options replaces the system's for the first blank
// document too (#838).
if !sample && app.session.prefs.region.is_some() {
let doc = app.session.blank_document();
app.replace_startup_document(doc);
}
app.tell_about_font_downloads();
if prefs::enabled()
&& let Some(dir) = wordcraft_control_key::settings_dir()
{
let ctx = ctx.clone();
if let Err(e) = app.session.enable_recovery(dir.join("recovery"), Arc::new(move || ctx.request_repaint())) {
log::warn!("local recovery unavailable: {e}");
}
// Language packs from the suite's font store; an Install click is the person's own.
// Nightly keeps its own store in the profile, so a pack installed there is not a
// change to the stable apps' shared fonts.
match launch_profile::current().root() {
Some(root) => wordcraft_engine::packs::use_font_store_in(root.join("FontStore"), true),
None => {
wordcraft_engine::packs::use_font_store(true);
}
}
let mut control_server = None;
if !nightly
&& let Some(port) = control.port
&& let Some((rx, started)) = control_server::start(&control, port, WindowHost::of(&ctx), wordcraft_control_key::settings_dir().as_deref())
{
app = app.with_control(ControlChannel::new(rx));
control_server = Some(started);
}
// Nothing to open (no files, no sample, no control channel driving the editor): start
// on File › Home, as Word does (#766), unless the Start screen option is off. Files
// the OS hands over later open on top of it and close it.
if files.is_empty() && other_files.is_empty() && !sample && control.port.is_none() {
app.start_screen();
}
// A Word template named here starts a new document based on it (#3433).
for f in files {
if let Err(e) = app.open_from_platform(&f, None) {
app.report_open_failure(&f, &e);
}
// A region chosen in File › Options replaces the system's for the first blank
// document too (#838).
if !sample && app.session.prefs.region.is_some() {
let doc = app.session.blank_document();
app.replace_startup_document(doc);
}
app.tell_about_font_downloads();
if prefs::enabled()
&& let Some(dir) = wordcraft_control_key::settings_dir()
{
let ctx = ctx.clone();
if let Err(e) = app.session.enable_recovery(dir.join("recovery"), Arc::new(move || ctx.request_repaint())) {
log::warn!("local recovery unavailable: {e}");
}
}
let mut control_server = None;
if !nightly
&& let Some(port) = control.port
&& let Some((rx, started)) =
control_server::start(&control, port, WindowHost::of(&ctx), wordcraft_control_key::settings_dir().as_deref())
{
app = app.with_control(ControlChannel::new(rx));
control_server = Some(started);
}
// Nothing to open (no files, no sample, no control channel driving the editor): start
// on File › Home, as Word does (#766), unless the Start screen option is off. Files
// the OS hands over later open on top of it and close it.
if files.is_empty() && other_files.is_empty() && !sample && control.port.is_none() {
app.start_screen();
}
// A Word template named here starts a new document based on it (#3433).
for f in files {
if let Err(e) = app.open_from_platform(&f, None) {
app.report_open_failure(&f, &e);
}
}
for f in other_files {
open_non_unicode(&mut app, &f);
}
// The personal agent files, the session record and the control token all live in the
// profile; the app's own services are built with the nightly rule in mind.
if let Some(warning) = &session_health_warning {
app.status_long(warning.clone());
}
if previous_nightly_unclean {
app.status_long(
}
for f in other_files {
open_non_unicode(&mut app, &f);
}
// The personal agent files, the session record and the control token all live in the
// profile; the app's own services are built with the nightly rule in mind.
if let Some(warning) = &session_health_warning {
app.status_long(warning.clone());
}
if previous_nightly_unclean {
app.status_long(
"The previous WordCraft Nightly session did not finish normally. You can report a problem from Help › About. No diagnostics have been sent.",
);
noticed_in_window.store(true, std::sync::atomic::Ordering::Relaxed);
}
Ok(Box::new(App {
#[cfg(target_os = "macos")]
native_menu: native_menu::install(&ctx, &app),
app,
panels,
drops,
settings,
spool,
control: control_server,
exit: Some(Box::new(move || {
nightly_session::finish_once(&session_for_exit, noticed_for_exit.load(std::sync::atomic::Ordering::Relaxed));
})),
}))
}),
);
noticed_in_window.store(true, std::sync::atomic::Ordering::Relaxed);
}
Ok(Box::new(App {
#[cfg(target_os = "macos")]
native_menu: native_menu::install(&ctx, &app),
app,
panels,
drops,
settings,
spool,
control: control_server,
exit: Some(Box::new(move || {
nightly_session::finish_once(&session_for_exit, noticed_for_exit.load(std::sync::atomic::Ordering::Relaxed));
})),
}))
});
let result = run_with_visible_root_fallback(creator, windowless, options);
// The exit hook has run; this is the no-op fallback for a start that created no window.
nightly_session::finish_once(&nightly_watch, unclean_notice_shown.load(std::sync::atomic::Ordering::Relaxed));
// The app is dropped by now: whatever it saved on the way out is in the store.
+19 -2
View File
@@ -6,13 +6,22 @@ use wordcraft_ui_egui::{WordApp, i18n};
const APP_NAME: &str = "WordCraft";
const ABOUT: &str = "About WordCraft";
const QUIT: &str = "Quit WordCraft";
/// The application menu, with `tr` the translation of an English string.
pub(super) fn layout(tr: &dyn Fn(&'static str) -> String) -> Layout {
let about = Item::new(CommandRef::with_params("ui.dialog", json!({"name": "about"})), tr(ABOUT)).role(ItemRole::About);
let bar = MenuBar::new(vec![Menu::new(APP_NAME, vec![about.into()]).role(MenuRole::App)]);
// Without its own Quit `mac_layout` adds one whose click only closes the root window: it must ask about every document.
let quit = Item::new(CommandRef::new("ui.quit"), tr(QUIT)).role(ItemRole::Quit);
let bar = MenuBar::new(vec![Menu::new(APP_NAME, vec![about.into(), quit.into()]).role(MenuRole::App)]);
// `mac_layout` words About as the template; WordCraft's catalogs translate the whole label.
let label = |s: &'static str| tr(if s == "About {app}" { ABOUT } else { s });
let label = |s: &'static str| {
tr(match s {
"About {app}" => ABOUT,
"Quit {app}" => QUIT,
s => s,
})
};
let mut layout = mac_layout(&bar, &LayoutOptions::new(APP_NAME).label(&label));
// WordCraft's document menus live in its ribbon; keep only the application menu.
layout.bar.menus.retain(|menu| menu.role == MenuRole::App);
@@ -61,4 +70,12 @@ mod tests {
let about = layout.bar.items().into_iter().find(|item| item.role == Some(ItemRole::About)).unwrap();
assert_eq!(about.label, "Über WordCraft");
}
/// ⌘Q and the menu's Quit run `ui.quit`, which asks about unsaved documents; craft's built-in Quit only closes the root window (#8709).
#[test]
fn quit_runs_the_command_that_asks_about_documents() {
let layout = layout(&|s| s.to_owned());
let quit = layout.bar.items().into_iter().find(|item| item.role == Some(ItemRole::Quit)).unwrap();
assert_eq!(quit.command.id, "ui.quit");
}
}
+17 -1
View File
@@ -619,7 +619,8 @@ impl Paragraph {
/// The word around `off` (double-click): (start, end) without trailing space.
pub fn word_at(&self, off: usize) -> (usize, usize) {
let off = self.clamp(off);
let is_w = |c: char| crate::bidi::is_word_char(c);
// Word's word unit takes a typographic apostrophe (’) like `'`, at either end too (#6517).
let is_w = |c: char| crate::bidi::is_word_char(c) || c == '’';
let mut a = off;
for (i, c) in self.text.get(..off).unwrap_or("").char_indices().rev() {
if !is_w(c) {
@@ -852,6 +853,21 @@ mod tests {
assert_eq!(p.prev_boundary(0), 0);
}
#[test]
fn word_at_takes_a_typographic_apostrophe_like_a_straight_one() {
// Byte offsets: `’` is three bytes. Word: `don’t ` (#6517).
let p = Paragraph::with_text("don’t stop", CharProps::default());
assert_eq!(p.word_at(1), (0, 8));
assert_eq!(p.word_at(2), (0, 8));
let p = Paragraph::with_text("the dogs’ bone", CharProps::default());
assert_eq!(p.word_at(5), (4, 12));
let p = Paragraph::with_text("’tis here", CharProps::default());
assert_eq!(p.word_at(3), (0, 7));
assert_eq!(p.word_at(4), (0, 7));
let p = Paragraph::with_text("well-known", CharProps::default());
assert_eq!(p.word_at(1), (0, 4));
}
proptest::proptest! {
#[test]
fn edits_keep_runs_consistent(ops in proptest::collection::vec((0u8..4, 0usize..40, 0usize..40, "[a-zé ]{0,5}"), 0..40)) {
+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() {
+15 -2
View File
@@ -177,6 +177,19 @@ fn glossary_value_from_shared(
})
}
fn note_separators_from_shared(
source: craft_wordmodel::NoteSeparators,
graphics: &mut GraphicCache,
) -> Result<wordcraft_doc::NoteSeparators, DocxError> {
let craft_wordmodel::NoteSeparators { separator, continuation_separator, continuation_notice } = source;
let mut blocks = |b: Option<craft_wordmodel::Blocks>| b.map(|b| blocks_from_shared(b, graphics)).transpose();
Ok(wordcraft_doc::NoteSeparators {
separator: blocks(separator)?,
continuation_separator: blocks(continuation_separator)?,
continuation_notice: blocks(continuation_notice)?,
})
}
fn missing_pictures_from_shared(source: craft_wordmodel::MissingPictures) -> Result<wordcraft_doc::MissingPictures, DocxError> {
let mut target = wordcraft_doc::MissingPictures::default();
target.truncated = source.truncated;
@@ -239,8 +252,8 @@ pub fn from_shared_model(mut source: craft_wordmodel::Document) -> Result<wordcr
document.core = convert(core)?;
document.sources = convert(sources)?;
document.custom_props = convert(custom_props)?;
document.footnote_separators = convert(footnote_separators)?;
document.endnote_separators = convert(endnote_separators)?;
document.footnote_separators = note_separators_from_shared(footnote_separators, &mut graphics)?;
document.endnote_separators = note_separators_from_shared(endnote_separators, &mut graphics)?;
document.media = media;
document.passthrough = passthrough;
document.glossary = glossary.into_iter().map(|g| glossary_value_from_shared(g, &mut graphics)).collect::<Result<_, _>>()?;
+50
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,6 +2446,54 @@ fn note_separators_and_continuation_notice_round_trip() {
check(&wordcraft_docx::read(&out).unwrap());
}
/// 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 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>{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>{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 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 = 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!(flattened(sep), in_body);
}
}
/// Issue #534: East Asian number formats are read, labelled and written back as they were; a
/// value the format doesn't define is decimal, and a level without `w:ind` has no indent.
#[test]
+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),
+68 -37
View File
@@ -3,7 +3,7 @@
use serde_json::Value;
use wordcraft_doc::math_edit::MathPos;
use wordcraft_doc::para::OBJ;
use wordcraft_doc::{InlineObject, Pos, StoryRef};
use wordcraft_doc::{InlineObject, Paragraph, Pos, StoryRef};
use wordcraft_layout::ViewMode;
use super::{parse_pos, sel_result};
@@ -110,7 +110,8 @@ fn bidi_para(s: &Session) -> bool {
/// Left/Right: with a selection and no Shift, collapse to its edge.
fn lr(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
if !extend(v) && !s.sel.is_collapsed() {
let ext = extend(v);
if !ext && !s.sel.is_collapsed() {
let (a, b) = s.sel.ordered();
// The left edge of a selection in right-to-left text is its logical end.
let to_start = is_left != rtl_para(s);
@@ -121,26 +122,32 @@ 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 edge = logical_edge(s, &from, is_left);
if !ext
&& !s.math_left
&& let Some(r) = into_equation(s, is_left)
&& let Some(r) = into_equation(s, &from, edge, is_left)
{
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) -> 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 { .. })) || (!s.view.show_markup && para.props_of_char(off).del.is_some()) {
return None;
}
s.sel = Selection::caret(Pos { off, ..f });
s.sel = Selection::caret(Pos { off, ..from.clone() });
s.goal_x = None;
s.pending = None;
Some(super::equation::edit_at(s, (!is_left).then(MathPos::default)))
@@ -159,62 +166,86 @@ fn visual_lr(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
Some(wordcraft_layout::VisualStep::Edge { start, stop, last_line, rtl }) => {
let at = |off| Pos { off, ..from.clone() };
if is_left != rtl {
match s.doc.para_at(&from) {
Some(para) if start > 0 => at(para.prev_boundary(start)),
_ => left(s, &at(0)),
}
logical_step(s, &at(start), true)
} else if !last_line {
at(stop)
} else {
let len = s.doc.para_at(&from).map_or(stop, |p| p.len());
right(s, &at(len))
logical_step(s, &at(len), false)
}
}
None if is_left => left(s, &from),
None => right(s, &from),
None => logical_step(s, &from, is_left),
};
apply(s, to, ext);
sel_result(s)
}
fn left(s: &mut Session, p: &Pos) -> Pos {
if let Some(para) = s.doc.para_at(p)
&& p.off > 0
{
return Pos { off: para.prev_boundary(p.off), ..p.clone() };
/// The two ends of a hidden deletion share a caret position. Cross the hidden
/// span before taking the normal grapheme step, including adjacent deletions.
fn hidden_deletion_edge(para: &Paragraph, off: usize, is_left: bool) -> usize {
// At a run boundary, inspect the byte on the side the caret is moving toward.
let Some(byte) = off.checked_sub(usize::from(is_left)).filter(|&byte| byte < para.len()) else { return off };
// Runs store lengths, so find the containing run from the nearer end of the paragraph.
let found = if byte < para.len() / 2 {
para.run_ranges().enumerate().find_map(|(i, (range, _))| range.contains(&byte).then_some((i, range)))
} else {
let mut end = para.len();
para.runs.iter().enumerate().rev().find_map(|(i, run)| {
let range = end - run.len..end;
end = range.start;
range.contains(&byte).then_some((i, range))
})
};
let Some((i, range)) = found else { return off };
if para.runs[i].props.del.is_none() {
return off;
}
match s.doc.prev_para(p.story, &p.path) {
Some(q) => {
let off = s.doc.para(p.story, &q).map(|x| x.len()).unwrap_or(0);
Pos { story: p.story, path: q, off }
}
None => p.clone(),
if is_left {
range.start - para.runs[..i].iter().rev().take_while(|run| run.props.del.is_some()).map(|run| run.len).sum::<usize>()
} else {
range.end + para.runs[i + 1..].iter().take_while(|run| run.props.del.is_some()).map(|run| run.len).sum::<usize>()
}
}
fn right(s: &mut Session, p: &Pos) -> Pos {
if let Some(para) = s.doc.para_at(p)
&& p.off < para.len()
fn logical_edge(s: &Session, from: &Pos, is_left: bool) -> usize {
if !s.view.show_markup
&& 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);
}
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 {
step_from_edge(s, from, logical_edge(s, from, is_left), is_left)
}
fn step_from_edge(s: &Session, from: &Pos, edge: usize, is_left: bool) -> Pos {
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() };
}
}
let neighbor = if is_left { s.doc.prev_para(from.story, &from.path) } else { s.doc.next_para(from.story, &from.path) };
let Some(path) = neighbor else { return from.clone() };
let off = if is_left { s.doc.para(from.story, &path).map_or(0, Paragraph::len) } else { 0 };
Pos { story: from.story, path, off }
}
fn word_left(s: &mut Session, p: &Pos) -> Pos {
match s.doc.para_at(p) {
Some(para) if p.off > 0 => Pos { off: para.word_start(p.off), ..p.clone() },
_ => left(s, p),
_ => logical_step(s, p, true),
}
}
fn word_right(s: &mut Session, p: &Pos) -> Pos {
match s.doc.para_at(p) {
Some(para) if p.off < para.len() => Pos { off: para.word_end(p.off), ..p.clone() },
_ => right(s, p),
_ => logical_step(s, p, false),
}
}
+21
View File
@@ -703,3 +703,24 @@ fn a_math_name_is_corrected_by_any_character_that_cannot_continue_it() {
s.run("equation.type", &json!({"text": r"\alpha+"})).unwrap();
assert_eq!(linear(&s), r"\alpha+");
}
/// Paste Formatting keeps an open equation open (matching other formatting commands and
/// `cmd::column`), whereas content-pasting commands leave the equation first.
#[test]
fn paste_formatting_keeps_an_open_equation_open() {
let mut s = session();
s.run("text.insert", &json!({"text": "source "})).unwrap();
s.run("select.text", &json!({"text": "source"})).unwrap();
s.run("format.bold", &json!({})).unwrap();
s.run("edit.copyFormat", &json!({})).unwrap();
s.run("caret.docEnd", &json!({})).unwrap();
s.run("insert.equation", &json!({"linear": "x"})).unwrap();
let before = s.math.clone();
assert!(before.is_some());
s.run("edit.pasteFormat", &json!({})).unwrap();
assert_eq!(s.math, before, "edit.pasteFormat keeps the open equation open");
s.run("edit.pasteText", &json!({"text": "y"})).unwrap();
assert!(s.math.is_none(), "edit.pasteText closes the open equation");
}
+23 -7
View File
@@ -94,9 +94,9 @@ pub fn specs() -> Vec<CommandSpec> {
.pure(),
CommandSpec::new("file.save", "Save", "File", save)
.key("Mod+S / Shift+F12 / Alt+Shift+F2")
.params(r#"{"path"?: string, "password"?: string (encrypt this and later saves with it, as file.encrypt does), "markup"?: bool (Print Markup for a PDF, PNG, HTML, Markdown or text copy: comments shown; default file.printMarkup), "format"?: "wordml2003" (an .xml file as a Word 2003 XML Document) | "flatopc" (as a Word XML Document, the default; saving over a Word 2003 XML file keeps that format), "strict"?: bool (a .pdf or .png only: refuse, writing nothing, if a character can't be drawn or a picture is missing; see file.strictReport)}"#)
.params(r#"{"path"?: string (required with `copy`), "password"?: string (encrypt this and later saves with it, as file.encrypt does), "markup"?: bool (Print Markup for a PDF, PNG, HTML, Markdown or text copy: comments shown; default file.printMarkup), "format"?: "wordml2003" (an .xml file as a Word 2003 XML Document) | "flatopc" (as a Word XML Document, the default; saving over a Word 2003 XML file keeps that format), "strict"?: bool (a .pdf or .png only: refuse, writing nothing, if a character can't be drawn or a picture is missing; see file.strictReport), "copy"?: bool (write a copy at `path`, as File › Export does: the document keeps its own file, unsaved changes and save stamps; not with `password`)}"#)
.pure(),
CommandSpec::new("file.saveAs", "Save As", "File", save_as).key(super::mac_or("F12 / Mod+Shift+S", "F12 / Alt+F2")).params(r#"{"path": string, "password"?: string, "markup"?: bool, "format"?: string (as file.save), "strict"?: bool (as file.save)}"#).pure(),
CommandSpec::new("file.saveAs", "Save As", "File", save_as).key(super::mac_or("F12 / Mod+Shift+S", "F12 / Alt+F2")).params(r#"{"path": string, "password"?: string, "markup"?: bool, "format"?: string (as file.save), "strict"?: bool (as file.save), "copy"?: bool (as file.save)}"#).pure(),
// Pure: the password must not land in Repeat or a recorded macro, and it isn't an edit
// to undo; it marks the document as changed itself.
CommandSpec::new("file.encrypt", "Encrypt with Password", "File › Info › Protect Document", encrypt)
@@ -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"#)
@@ -342,6 +342,8 @@ pub(crate) fn new_from_template(s: &mut Session, v: &Value) -> CmdResult {
let path = p::req_str(v, "path")?;
let (mut doc, _) = read_document(s, path, v)?;
doc.settings.attached_template = Some(path.to_string());
// A new document: not created when the template was. Saving stamps its creation date.
doc.core.created.clear();
if p::bool(v, "replaceBlank") == Some(true) && s.used_because().is_none() {
s.set_document(doc);
} else {
@@ -393,6 +395,14 @@ fn encrypt(s: &mut Session, v: &Value) -> CmdResult {
/// Executes `file.save`: writes the document or text to disk, preserving exact file text for
/// unedited Markdown files, and updating session path and dirty state.
fn save(s: &mut Session, v: &Value) -> CmdResult {
// A copy (File › Export, #6131) is written and nothing else: the document keeps its own file,
// its unsaved changes and its save stamps, so the next Save still goes to the original.
// It never falls back to the document's own file or opens the Save As picker (whose answer is
// an ordinary save that adopts the file).
let as_copy = p::bool(v, "copy") == Some(true);
if as_copy && p::str(v, "path").is_none() {
return Err(CmdError::Params("`copy` needs a `path`: the copy has to go somewhere".into()));
}
let path = match p::str(v, "path").map(std::path::PathBuf::from).or_else(|| s.path.clone()) {
Some(p) => p,
None => {
@@ -401,6 +411,9 @@ fn save(s: &mut Session, v: &Value) -> CmdResult {
}
};
check_strict_output(p::bool(v, "strict").unwrap_or(false), &path.to_string_lossy())?;
if as_copy && v.get("password").is_some_and(|pw| !pw.is_null()) {
return Err(CmdError::Params("`password` changes the document's own saves, so it can't come with `copy` (use file.encrypt)".into()));
}
if let Some(pw) = v.get("password").filter(|pw| !pw.is_null()) {
let Some(pw) = pw.as_str().filter(|pw| !pw.is_empty()) else {
return Err(CmdError::Params("`password` must be a non-empty string (file.encrypt removes a password)".into()));
@@ -443,11 +456,14 @@ fn save(s: &mut Session, v: &Value) -> CmdResult {
Some(text) => crate::io::save_text_path(&path, text),
None => crate::io::save_path_with(&path, copy.as_ref().unwrap_or(&s.doc), password, &opts),
};
if let Err(e) = written {
(s.doc.settings.zoom, s.doc.core.last_modified_by, s.doc.core.created, s.doc.core.modified, s.doc.core.revision) = before_stamp;
return Err(CmdError::Failed(e));
}
let encrypted = password.is_some() && crate::io::can_encrypt(&path.to_string_lossy());
if written.is_err() || as_copy {
(s.doc.settings.zoom, s.doc.core.last_modified_by, s.doc.core.created, s.doc.core.modified, s.doc.core.revision) = before_stamp;
}
written.map_err(CmdError::Failed)?;
if as_copy {
return Ok(json!({"saved": true, "path": path.to_string_lossy(), "encrypted": encrypted, "copy": true}));
}
// A save in a format that doesn't keep everything (plain text, Markdown, a page image) is a
// copy, except over the document's own file: a note.txt opened and saved is saved (#2376).
// A Markdown file saved as another one loses nothing its own save wouldn't: it moves there.
+18 -3
View File
@@ -209,7 +209,8 @@ fn target(s: &Session) -> Option<(Pos, Pos)> {
return Some((a, b));
}
let p = s.doc.para_at(&a)?;
let is_w = |c: char| c.is_alphanumeric() || c == '\'' || c == '_';
// Word takes a typographic apostrophe (’) like `'` here (#6517).
let is_w = |c: char| c.is_alphanumeric() || matches!(c, '\'' | '’' | '_');
let before = p.text.get(..a.off)?.chars().next_back();
let after = p.text.get(a.off..)?.chars().next();
if before.is_some_and(is_w) && after.is_some_and(is_w) {
@@ -351,6 +352,19 @@ fn resolved(s: &Session) -> Vec<ResolvedChar> {
out
}
/// 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() {
return !chars.first().is_some_and(has);
}
!chars.iter().all(has)
}
/// Bold as drawn: a run marked complex script (`w:cs`) or right to left (`w:rtl`) shows its
/// complex-script bold.
fn shown_bold(r: &ResolvedChar) -> bool {
@@ -366,7 +380,7 @@ fn shown_italic(r: &ResolvedChar) -> bool {
fn toggle(s: &mut Session, v: &Value, get: fn(&ResolvedChar) -> bool, set: fn(&mut CharProps, bool)) -> CmdResult {
let on = match p::bool(v, "value") {
Some(b) => b,
None => !resolved(s).iter().all(get),
None => turns_on(s, get),
};
apply(s, &|c| set(c, on))
}
@@ -376,7 +390,7 @@ fn underline(s: &mut Session, v: &Value) -> CmdResult {
let on = match (p::bool(v, "value"), style) {
(Some(b), _) => b,
(None, Some(_)) => true,
(None, None) => !resolved(s).iter().all(|r| r.underline != Underline::None),
(None, None) => turns_on(s, |r| r.underline != Underline::None),
};
let u = if on { style.unwrap_or(Underline::Single) } else { Underline::None };
apply(s, &|c| c.underline = Some(u))
@@ -413,6 +427,7 @@ fn font(s: &mut Session, v: &Value) -> CmdResult {
}
if let Some(n) = &ea {
c.font_ea = Some(n.clone());
c.font_ea_theme = None;
}
})
}
+1 -1
View File
@@ -21,7 +21,7 @@ pub use items::{
};
use items::{cover_page, date_time, drop_cap, drop_cap_off, field, page_number, symbol};
use links::{bookmark, delete_bookmark, link, link_targets};
pub use links::{bookmark_name_ok, bookmark_range, bookmark_span};
pub use links::{bookmark_name_ok, bookmark_range, bookmark_span, selection_is_one_line};
pub use objects::{MAX_TABLE_ROWS, base64_decode, base64_encode};
use objects::{icon, shape, table, text_box};
pub(crate) use objects::{image_ext, picture};
+88 -11
View File
@@ -205,21 +205,26 @@ pub fn format_date_at_in(fmt: &str, lang: Option<&str>, unix: u64, offset_secs:
format_date_parts_in(fmt, lang, y, m as usize, d, hms, days)
}
/// Month and weekday names of a language, as Word writes them in date fields: full names, the
/// three-letter forms (`MMM`, `ddd`) being their first three letters, without a full stop.
/// Weekdays start on Thursday (1970-01-01).
/// Month and weekday names of a language, as Word writes them in date fields: full names and the
/// abbreviations used by `MMM` and `ddd`. Weekdays start on Thursday (1970-01-01).
struct DateNames {
/// Full month names (January through December).
months: [&'static str; 12],
/// Abbreviated month names for `MMM` (January through December).
months_short: [&'static str; 12],
/// Weekday names starting on Thursday (1970-01-01).
days: [&'static str; 7],
/// Abbreviated weekday names for `ddd`, starting on Thursday (1970-01-01).
days_short: [&'static str; 7],
/// The picture of a `DATE` field without `\@`.
default: &'static str,
}
const ENGLISH: DateNames = DateNames {
months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
months_short: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
days: ["Thursday", "Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday"],
days_short: ["Thu", "Fri", "Sat", "Sun", "Mon", "Tue", "Wed"],
default: "M/d/yyyy",
};
@@ -227,14 +232,46 @@ const ENGLISH: DateNames = DateNames {
/// `ddd` = `qui`, and `dd/MM/yyyy` for a field without a picture.
const PORTUGUESE: DateNames = DateNames {
months: ["janeiro", "fevereiro", "março", "abril", "maio", "junho", "julho", "agosto", "setembro", "outubro", "novembro", "dezembro"],
months_short: ["jan", "fev", "mar", "abr", "mai", "jun", "jul", "ago", "set", "out", "nov", "dez"],
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",
};
/// Choose month and weekday names according to the primary language subtag.
/// German (Word's Windows NLS forms): `MMMM` = `März`, `MMM` = `Mrz`, `ddd` = `Fr` (two
/// letters), and `dd.MM.yyyy` for a field without a picture. Covers de-DE, de-CH and bare `de`.
const GERMAN: DateNames = DateNames {
months: ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
months_short: ["Jan", "Feb", "Mrz", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"],
days: ["Donnerstag", "Freitag", "Samstag", "Sonntag", "Montag", "Dienstag", "Mittwoch"],
days_short: ["Do", "Fr", "Sa", "So", "Mo", "Di", "Mi"],
default: "dd.MM.yyyy",
};
/// Austrian Standard German: January is `Jänner`, abbreviated `Jän` (Österreichisches
/// Wörterbuch; Windows NLS `de-AT`). Every other month and weekday matches [`GERMAN`].
const GERMAN_AUSTRIA: DateNames = DateNames {
months: ["Jänner", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
months_short: ["Jän", "Feb", "Mrz", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"],
days: ["Donnerstag", "Freitag", "Samstag", "Sonntag", "Montag", "Dienstag", "Mittwoch"],
days_short: ["Do", "Fr", "Sa", "So", "Mo", "Di", "Mi"],
default: "dd.MM.yyyy",
};
/// Choose month and weekday names from the language tag: the primary subtag picks the language,
/// and a region subtag refines it (`de-AT` writes `Jänner`). Tags compare case-insensitively, as
/// `w:lang` values do.
fn date_names(lang: Option<&str>) -> &'static DateNames {
let primary = lang.and_then(|l| l.trim().split(['-', '_']).next()).unwrap_or("");
if primary.eq_ignore_ascii_case("pt") { &PORTUGUESE } else { &ENGLISH }
let mut subtags = lang.unwrap_or("").trim().split(['-', '_']);
let primary = subtags.next().unwrap_or("");
if primary.eq_ignore_ascii_case("pt") {
&PORTUGUESE
} else if primary.eq_ignore_ascii_case("de") {
// Austria keeps `Jänner` / `Jän`; Germany and Switzerland keep `Januar` / `Jan`.
if subtags.any(|region| region.eq_ignore_ascii_case("AT")) { &GERMAN_AUSTRIA } else { &GERMAN }
} else {
&ENGLISH
}
}
/// The picture Word gives a `DATE` field that has no `\@` switch, in the field's language.
@@ -252,9 +289,12 @@ pub fn format_date_parts(fmt: &str, y: i64, m: usize, d: u32, hms: (u32, u32, u3
#[allow(clippy::too_many_arguments)]
pub fn format_date_parts_in(fmt: &str, lang: Option<&str>, y: i64, m: usize, d: u32, (hh, mm, ss): (u32, u32, u32), days_since: i64) -> String {
let names = date_names(lang);
let month = names.months.get(m.saturating_sub(1)).copied().unwrap_or(names.months[0]);
let day = names.days.get(days_since.rem_euclid(7) as usize).copied().unwrap_or(names.days[0]);
let three = |s: &str| -> String { s.chars().take(3).collect() };
let mi = m.saturating_sub(1);
let di = days_since.rem_euclid(7) as usize;
let month = names.months.get(mi).copied().unwrap_or(names.months[0]);
let month_short = names.months_short.get(mi).copied().unwrap_or(names.months_short[0]);
let day = names.days.get(di).copied().unwrap_or(names.days[0]);
let day_short = names.days_short.get(di).copied().unwrap_or(names.days_short[0]);
let mut out = String::new();
let chars: Vec<char> = fmt.chars().collect();
let mut i = 0;
@@ -296,11 +336,11 @@ pub fn format_date_parts_in(fmt: &str, lang: Option<&str>, y: i64, m: usize, d:
('y' | 'Y', 4..) => out.push_str(&format!("{y:04}")),
('y' | 'Y', _) => out.push_str(&format!("{:02}", y % 100)),
('M', 4..) => out.push_str(month),
('M', 3) => out.push_str(&three(month)),
('M', 3) => out.push_str(month_short),
('M', 2) => out.push_str(&format!("{m:02}")),
('M', 1) => out.push_str(&m.to_string()),
('d' | 'D', 4..) => out.push_str(day),
('d' | 'D', 3) => out.push_str(&three(day)),
('d' | 'D', 3) => out.push_str(day_short),
('d' | 'D', 2) => out.push_str(&format!("{d:02}")),
('d' | 'D', 1) => out.push_str(&d.to_string()),
('H', 2..) => out.push_str(&format!("{hh:02}")),
@@ -574,6 +614,43 @@ mod date_time_locale_tests {
assert_eq!(format("MMMM", 20), "outubro");
}
/// German month and weekday names, and the default picture, are chosen by the language tag
/// (de-DE, de-AT, de-CH), as in Word (#7146).
#[test]
fn german_date_names_render_for_de() {
assert_eq!(format_date_parts_in("dddd, d. MMMM yyyy", Some("de-DE"), 2026, 11, 21, (12, 0, 0), 2), "Samstag, 21. November 2026");
assert_eq!(default_date_picture(Some("de-CH")), "dd.MM.yyyy");
}
/// Windows NLS short forms: two-letter weekdays (`Mo`, `Di`…) and `Mrz` for March, with no
/// trailing full stop (#7146).
#[test]
fn german_short_names_match_windows_nls() {
let format = |pic| format_date_parts_in(pic, Some("de-DE"), 2026, 3, 15, (12, 0, 0), 3);
assert_eq!(format("ddd, d. MMM yyyy"), "So, 15. Mrz 2026");
assert_eq!(format("dddd"), "Sonntag");
assert_eq!(format("MMM"), "Mrz");
}
/// Austrian Standard German writes January as `Jänner` (`Jän`), while Germany, Switzerland
/// and bare `de` keep `Januar` (`Jan`); every other name is shared (#7146).
#[test]
fn austrian_german_january_is_jaenner() {
let january = |lang, pic| format_date_parts_in(pic, 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", "MMMM"), "Jänner", "region subtags compare case-insensitively");
for lang in ["de-DE", "de-CH", "de"] {
assert_eq!(january(lang, "MMMM"), "Januar", "{lang}");
assert_eq!(january(lang, "MMM"), "Jan", "{lang}");
}
// Only January differs: February and March read the same in Austria and Germany.
for month in [2, 3] {
let names = |lang| format_date_parts_in("MMMM MMM", Some(lang), 2026, month, 1, (12, 0, 0), 0);
assert_eq!(names("de-AT"), names("de-DE"));
}
}
/// A pt-BR dynamic field keeps its result after DOCX round-trip and refresh.
#[test]
fn pt_br_date_time_dialog_inserts_dynamic_field() {
+30 -10
View File
@@ -84,25 +84,45 @@ pub(super) fn link(s: &mut Session, v: &Value) -> CmdResult {
sel_result(s)
}
/// The `text` to retype a selection with before linking it: only when it differs from the selected
/// text and both fit in one line of one paragraph without pictures or fields, outside any field's
/// result. Otherwise (as Word shows `<<Selection in Document>>`) the selection keeps its text.
fn retyped_text(s: &Session, v: &Value) -> Option<String> {
/// What can't stand in one line of text: breaks, and pictures or fields.
const NOT_ONE_LINE: [char; 7] = {
use wordcraft_doc::para::{COLUMN_BREAK, LINE_BREAK, OBJ, PAGE_BREAK};
/// What can't stand in one line of text: breaks, and pictures or fields.
const NOT_ONE_LINE: [char; 7] = [LINE_BREAK, '\r', '\u{2029}', '\u{b}', PAGE_BREAK, COLUMN_BREAK, OBJ];
let text = p::str(v, "text").filter(|t| !t.is_empty() && t.len() <= 4096)?;
if text.contains(NOT_ONE_LINE) {
[LINE_BREAK, '\r', '\u{2029}', '\u{b}', PAGE_BREAK, COLUMN_BREAK, OBJ]
};
/// The raw text of the selection when it is one run of one paragraph without breaks, pictures or fields.
fn one_line_selection(s: &Session) -> Option<&str> {
// A column (block) selection has both ends in one paragraph but holds a piece of each line it
// covers: it isn't one line of text (#8581).
if s.column_segments().is_some_and(|segs| !segs.is_empty()) {
return None;
}
let (a, b) = s.sel.ordered();
if a.story != b.story || a.path != b.path {
return None;
}
let shown = s.doc.para(a.story, &a.path)?.text.get(a.off..b.off)?;
if shown.contains(NOT_ONE_LINE) || shown == text {
s.doc.para(a.story, &a.path)?.text.get(a.off..b.off).filter(|t| !t.contains(NOT_ONE_LINE))
}
/// Whether the selection is plain text in one line of one paragraph: otherwise (as Word shows
/// `<<Selection in Document>>`) Text to display can't show it and linking keeps its content (#8286).
pub fn selection_is_one_line(s: &Session) -> bool {
one_line_selection(s).is_some()
}
/// The `text` to retype a selection with before linking it: only when it differs from the selected
/// text and both fit in one line of one paragraph without pictures or fields, outside any field's
/// result. Otherwise (as Word shows `<<Selection in Document>>`) the selection keeps its text.
fn retyped_text(s: &Session, v: &Value) -> Option<String> {
let text = p::str(v, "text").filter(|t| !t.is_empty() && t.len() <= 4096)?;
if text.contains(NOT_ONE_LINE) {
return None;
}
let shown = one_line_selection(s)?;
if shown == text {
return None;
}
let (a, b) = s.sel.ordered();
// A selection in a field's result (between its markers, which it doesn't hold) is retyped by
// the next update of the field, not here.
if s.doc.field_ranges(a.story).iter().any(|r| r.start < b && a <= r.end) {
+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);
}
}
+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),
+37 -8
View File
@@ -373,21 +373,22 @@ pub fn merge_formatting(s: &Session, frag: &mut Fragment) {
p.props = para.clone();
for run in &mut p.runs {
let src = std::mem::replace(&mut run.props, base.clone());
// Emphasis in either script is kept for both, as the Bold and Italic buttons set
// it: text pasted into a run marked `w:cs` (Thai from a WPS or Word file) is drawn
// with the complex-script bold and italic.
if src.bold == Some(true) || src.bold_cs == Some(true) {
let e = emphasis_of(s, &src);
// Emphasis the source shows in either script is kept for both, as the Bold and
// Italic buttons set it: text pasted into a run marked `w:cs` (Thai from a WPS or
// Word file) is drawn with the complex-script bold and italic.
if shown(e.bold, e.bold_cs, &e) {
run.props.bold = Some(true);
run.props.bold_cs = Some(true);
}
if src.italic == Some(true) || src.italic_cs == Some(true) {
if shown(e.italic, e.italic_cs, &e) {
run.props.italic = Some(true);
run.props.italic_cs = Some(true);
}
if src.underline.is_some_and(|u| u != wordcraft_doc::props::Underline::None) {
run.props.underline = src.underline;
if e.underline.is_some_and(|u| u != wordcraft_doc::props::Underline::None) {
run.props.underline = e.underline;
}
if src.strike == Some(true) {
if e.strike == Some(true) {
run.props.strike = Some(true);
}
run.props.link = src.link;
@@ -400,6 +401,34 @@ pub fn merge_formatting(s: &Session, frag: &mut Fragment) {
}
}
/// The formatting a pasted run's emphasis is judged by: its own, over its character style
/// chain's. Word keeps the bold, italic, underline and strikethrough a character style gives the
/// source, as direct formatting, but not a paragraph style's (measured in Word for Windows), so
/// the paragraph style isn't consulted.
fn emphasis_of(s: &Session, src: &wordcraft_doc::CharProps) -> wordcraft_doc::CharProps {
use wordcraft_doc::styles::StyleKind;
let mut e = wordcraft_doc::CharProps::default();
if let Some(id) = src.style.as_deref() {
for st in s.doc.styles.chain(id) {
if st.kind == StyleKind::Character || st.kind == StyleKind::Paragraph {
e.overlay(&st.chr);
}
}
}
e.overlay(&wordcraft_doc::CharProps { style: None, ..src.clone() });
e
}
/// Whether a run with these Latin and complex-script values of a toggle (bold or italic) shows
/// it anywhere, as the resolved formatting draws it: a run marked `w:cs` or `w:rtl` draws all
/// its text with the complex-script value, which borrows the Latin one unless the run is marked
/// `w:cs`; other runs draw their Latin text with the Latin value.
fn shown(latin: Option<bool>, complex: Option<bool>, run: &wordcraft_doc::CharProps) -> bool {
let complex_shown = complex.or(latin.filter(|_| run.cs != Some(true))) == Some(true);
let all_complex = run.cs == Some(true) || run.rtl == Some(true);
complex_shown || (!all_complex && latin == Some(true))
}
/// Paste `frag` at the selection. A copied table pasted with the caret in a table cell goes the way
/// Word's Paste does it (rows inserted or cells overwritten, #6739; see [`super::paste_cells`]);
/// anything else is [`insert_as_is`].
+35 -2
View File
@@ -402,7 +402,7 @@ pub fn update_fields_in(s: &mut Session, all: bool) -> Result<(), CmdError> {
}
let mut updates: Vec<(usize, String)> = Vec::new();
for (k, o) in p.objects.iter().enumerate() {
let InlineObject::Field { instr, locked: false, .. } = o else { continue };
let InlineObject::Field { instr, result, locked: false, .. } = o else { continue };
// A table formula reads the cells around its own cell again.
if instr.trim_start().starts_with('=') {
if let Some((tp, r, c)) = path.cell()
@@ -422,7 +422,22 @@ pub fn update_fields_in(s: &mut Session, all: bool) -> Result<(), CmdError> {
"DATE" | "TIME" | "CREATEDATE" | "SAVEDATE" | "PRINTDATE" => {
let lang = field_lang(&s.doc, p, k);
let pic = date_picture(instr).unwrap_or_else(|| default_picture(&name, lang.as_deref()));
updates.push((k, text_result(instr, crate::cmd::insert::format_date_in(&pic, lang.as_deref()))));
let created = s.doc.core.created.trim();
// CREATEDATE shows when the document was created (ECMA-376 §17.16.5.11). A new
// document, never saved, has no creation date yet and saving stamps now. A
// file opened without one, or with one that can't be read, keeps any result
// it already has; when inserted with none, it shows today's date (the date
// a save would stamp).
let text = if name == "CREATEDATE"
&& let Some((unix, offset)) = created_at(created)
{
crate::cmd::insert::format_date_at_in(&pic, lang.as_deref(), unix, offset)
} else if name != "CREATEDATE" || result.is_empty() || (created.is_empty() && s.path.is_none()) {
crate::cmd::insert::format_date_in(&pic, lang.as_deref())
} else {
continue;
};
updates.push((k, text_result(instr, text)));
}
"REF" | "PAGEREF" => {
let f = FieldCode::parse(instr);
@@ -572,6 +587,24 @@ fn field_lang(doc: &wordcraft_doc::Document, p: &wordcraft_doc::Paragraph, k: us
doc.styles.resolve_char(p.props.style.as_deref(), p.props_of_char(off)).lang
}
/// A core-properties creation date as seconds since the epoch and the UTC offset to show it at:
/// an instant (`2019-05-05T12:00:00Z`, any offset or fraction, or without the seconds,
/// `2019-05-05T12:00Z`, as W3CDTF allows) at the local offset, or a calendar date (`2019-05-05`)
/// at its own midnight, whatever the time zone. `None` for another form or a date before 1970.
fn created_at(stamp: &str) -> Option<(u64, i64)> {
let instant = chrono::DateTime::parse_from_rfc3339(stamp).ok().or_else(|| {
// `%:z` takes `+01:00` but not `Z`.
let utc = stamp.strip_suffix(['Z', 'z']).map(|t| format!("{t}+00:00"));
chrono::DateTime::parse_from_str(utc.as_deref().unwrap_or(stamp), "%Y-%m-%dT%H:%M%:z").ok()
});
if let Some(t) = instant {
let unix = u64::try_from(t.timestamp()).ok()?;
return Some((unix, crate::cmd::local_offset_secs(unix)));
}
let day = chrono::NaiveDate::parse_from_str(stamp, "%Y-%m-%d").ok()?;
Some((u64::try_from(day.and_hms_opt(0, 0, 0)?.and_utc().timestamp()).ok()?, 0))
}
/// Word's default date or time picture when a field instruction carries no `\@` picture switch.
fn default_picture(name: &str, lang: Option<&str>) -> String {
if name == "TIME" { "h:mm am/pm".into() } else { crate::cmd::insert::default_date_picture(lang).into() }
+160
View File
@@ -506,6 +506,76 @@ fn update_fields_all_covers_every_story() {
s.run("references.updateFields", &json!({"all": "yes"})).unwrap();
}
/// CREATEDATE shows when the document was created (ECMA-376 §17.16.5.11), not today's date.
#[test]
fn createdate_keeps_the_creation_date_on_update() {
let mut s = Session::new(wordcraft_doc::Document::new());
s.doc.core.created = "2019-05-05T12:00:00Z".into();
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#, "result": "2019-05"})).unwrap();
s.run("insert.field", &json!({"instr": "CREATEDATE"})).unwrap();
s.run("references.updateFields", &json!({})).unwrap();
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
// 12:00 UTC is 5 May from UTC-12 to UTC+11:59, the next day east of that.
let unix = 1_557_057_600;
let (_, _, day, _, _) = crate::cmd::local_civil(unix, crate::cmd::local_offset_secs(unix));
assert_eq!(results, ["2019-05".to_string(), format!("5/{day}/2019")]);
assert!(day == 5 || day == 6, "{day}");
// W3CDTF may leave out the seconds; that is the same instant.
for minutes in ["2019-05-05T12:00Z", "2019-05-05T14:00+02:00", "2019-05-05T07:00-05:00"] {
// From another date first, so an unread stamp, which keeps the result, shows.
s.doc.core.created = "2001-02-03".into();
s.run("references.updateFields", &json!({})).unwrap();
assert_eq!(fields(&s)[1].1, "2/3/2001");
s.doc.core.created = minutes.into();
s.run("references.updateFields", &json!({})).unwrap();
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
assert_eq!(results, ["2019-05".to_string(), format!("5/{day}/2019")], "{minutes}");
}
// A date without a time is that calendar day in every time zone.
s.doc.core.created = "2019-06-07".into();
s.run("references.updateFields", &json!({})).unwrap();
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
assert_eq!(results, ["2019-06", "6/7/2019"]);
}
/// A creation date that can't be read leaves the field's result as it was; a document that has
/// never been saved is created now (saving stamps that time as its creation date).
#[test]
fn createdate_without_a_readable_creation_date() {
let mut s = Session::new(wordcraft_doc::Document::new());
s.doc.core.created = "sometime in May".into();
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#, "result": "2019-05"})).unwrap();
assert_eq!(fields(&s)[0].1, "2019-05");
// A file opened without a creation date keeps the result too.
s.doc.core.created.clear();
s.path = Some(std::env::temp_dir().join("opened.docx"));
s.run("references.updateFields", &json!({})).unwrap();
assert_eq!(fields(&s)[0].1, "2019-05");
s.path = None;
s.run("references.updateFields", &json!({})).unwrap();
assert_eq!(fields(&s)[0].1, crate::cmd::insert::format_date("yyyy-MM"));
}
/// Inserting CREATEDATE into an opened file that has no creation date (plain text, Markdown, or a
/// DOCX without `dcterms:created`) shows today's date rather than an empty result, while an
/// existing field with a cached result keeps it.
#[test]
fn createdate_inserted_into_opened_file_without_creation_date() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Notes"));
s.path = Some(std::env::temp_dir().join("notes.txt"));
s.doc.core.created.clear();
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#, "result": "2019-05"})).unwrap();
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#})).unwrap();
let expected = crate::cmd::insert::format_date("yyyy-MM");
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
assert_eq!(results, ["2019-05".to_string(), expected.clone()]);
// An unreadable creation date behaves the same way: cached results stay, empty ones fill in.
s.doc.core.created = "sometime in May".into();
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#})).unwrap();
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
assert_eq!(results, ["2019-05".to_string(), expected.clone(), expected]);
}
#[test]
fn toc_tabs_ignore_nonentries() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Before\nContents\nOld\t9\nAfter"));
@@ -627,6 +697,96 @@ fn a_toc_replaced_right_before_a_table_still_lands_the_caret_in_a_paragraph() {
assert!(matches!(&*s.doc.body[new_end + 1], Block::Para(_)));
}
/// Inserting a table of contents in the middle of a document places the caret in the paragraph
/// right after the table and leaves the text above and below it unchanged.
#[test]
fn a_toc_inserted_in_the_middle_of_a_document_leaves_the_caret_after_it() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Intro\nAfter TOC\nChapter One\nBody below."));
s.run("select.text", &json!({"text": "Chapter One"})).unwrap();
s.run("styles.apply", &json!({"style": "Heading 1"})).unwrap();
s.sel = Selection::caret(Pos { story: StoryRef::Body, path: Path::top(1), off: 0 });
s.run("references.toc", &json!({"levels": 2})).unwrap();
let (start, end) = toc_range(&s).unwrap();
assert!(start > 0, "the TOC is inserted after the intro paragraph");
assert_eq!(s.doc.body[0].as_para().map(|p| p.plain_text()).as_deref(), Some("Intro"));
assert_eq!(
s.sel.focus,
Pos { story: StoryRef::Body, path: Path::top(end + 1), off: 0 },
"the caret must land in the paragraph right after the TOC"
);
let below: Vec<String> = s.doc.body[end + 1..].iter().filter_map(|b| b.as_para()).map(|p| p.plain_text()).collect();
assert_eq!(below, ["After TOC", "Chapter One", "Body below."]);
}
/// One undo removes both the table of contents and the empty paragraph `caret_after_toc` adds
/// when the table ends the document or comes right before a table, leaving no stray blank
/// paragraph behind.
#[test]
fn undoing_a_toc_removes_both_the_table_and_the_added_paragraph() {
let toc_instr = |s: &Session, i: usize| {
s.doc.body[i].as_para().and_then(|p| {
p.objects.iter().find_map(|o| match o {
InlineObject::Field { instr, .. } => Some(instr.clone()),
_ => None,
})
})
};
// Fresh insert on an empty document undoes in one step.
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("references.toc", &json!({"levels": 2})).unwrap();
assert!(toc_range(&s).is_some());
assert_eq!(s.undo_depth(), 1);
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(s.undo_depth(), 0);
assert!(toc_range(&s).is_none());
assert_eq!(s.doc.body.len(), 1);
assert_eq!(s.doc.plain_text(StoryRef::Body), "");
// Table ending the document: `caret_after_toc` appends an empty paragraph, and one undo
// removes both the replaced table and that added paragraph.
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("references.toc", &json!({"levels": 2})).unwrap();
let (start, end) = toc_range(&s).unwrap();
while s.doc.body.len() > end + 1 {
s.doc.remove_block(StoryRef::Body, &Path::top(end + 1)).unwrap();
}
let before_blocks = s.doc.body.len();
let depth = s.undo_depth();
s.run("references.toc", &json!({"levels": 3})).unwrap();
let (_, new_end) = toc_range(&s).unwrap();
assert!(s.doc.body.get(new_end + 1).is_some_and(|b| b.as_para().is_some_and(|p| p.is_empty())));
assert_eq!(s.doc.body.len(), before_blocks + 1);
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(s.undo_depth(), depth);
assert_eq!(s.doc.body.len(), before_blocks, "undo must remove the added trailing paragraph");
assert_eq!(toc_range(&s), Some((start, end)));
assert!(toc_instr(&s, start).as_deref().is_some_and(|i| i.contains(r#"\o "1-2""#)));
// Table right before another table: `caret_after_toc` inserts an empty paragraph before the
// table, and one undo removes both the replaced TOC and that added paragraph.
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("references.toc", &json!({"levels": 2})).unwrap();
s.run("insert.table", &json!({"rows": 1, "cols": 1})).unwrap();
let (start, end) = toc_range(&s).unwrap();
while s.doc.body.get(end + 1).is_some_and(|b| b.as_para().is_some_and(|p| p.is_empty())) {
s.doc.remove_block(StoryRef::Body, &Path::top(end + 1)).unwrap();
}
assert!(matches!(&*s.doc.body[end + 1], Block::Table(_)));
let before_blocks = s.doc.body.len();
let depth = s.undo_depth();
s.run("references.toc", &json!({"levels": 3})).unwrap();
let (_, new_end) = toc_range(&s).unwrap();
assert!(s.doc.body.get(new_end + 1).is_some_and(|b| b.as_para().is_some_and(|p| p.is_empty())));
assert_eq!(s.doc.body.len(), before_blocks + 1);
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(s.undo_depth(), depth);
assert_eq!(s.doc.body.len(), before_blocks, "undo must remove the added paragraph before the table");
assert_eq!(toc_range(&s), Some((start, end)));
assert!(matches!(&*s.doc.body[end + 1], Block::Table(_)));
assert!(toc_instr(&s, start).as_deref().is_some_and(|i| i.contains(r#"\o "1-2""#)));
}
/// A fresh scratch directory for the file-name tests below.
#[cfg(not(target_arch = "wasm32"))]
fn filename_scratch_dir(tag: &str) -> std::path::PathBuf {
+1
View File
@@ -12,6 +12,7 @@ use crate::{CmdError, CmdResult, CommandSpec, Selection, Session, p};
mod changes;
mod comments;
mod proofing;
pub use proofing::thesaurus_word;
pub(crate) use changes::StyleTarget;
pub use changes::{
+36 -4
View File
@@ -53,10 +53,11 @@ fn resolve_para(
}
// 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 mark at the end
// of a story or cell can't go, so it just stops being a revision. An empty paragraph whose
// mark carries a section break goes whole too: its section joins the following one, as when
// the break is deleted (#5667). Joining instead gave the next paragraph its properties.
// whole, so the next one keeps its own style and numbering, as in Word. The end mark of a
// story or cell has no follower to join here; `resolve_all` removes the whole paragraph
// instead when one is left over (see `remove_trailing_para`). An empty paragraph whose mark
// carries a section break goes whole too: its section joins the following one, as when the
// break is deleted (#5667). Joining instead gave the next paragraph its properties.
if (del.is_some() && accept) || (ins.is_some() && !accept) {
let sectioned = story == StoryRef::Body
&& path.0.len() == 1
@@ -76,6 +77,23 @@ fn resolve_para(
Ok(())
}
/// Remove the whole paragraph at `path` when a whole-paragraph revision on its mark resolved to
/// removal and it is the last paragraph in its container and carries no section break: it goes
/// away, as long as the container keeps another paragraph (a story or cell must never end up
/// with none). `false`, changing nothing, otherwise.
fn remove_trailing_para(s: &mut Session, story: StoryRef, path: &wordcraft_doc::Path) -> Result<bool, CmdError> {
let Some(p) = s.doc.para(story, path) else { return Ok(false) };
if !p.is_empty() || p.section.is_some() {
return Ok(false);
}
let Some(container) = s.doc.container(story, path) else { return Ok(false) };
if container.iter().filter(|b| b.as_para().is_some()).count() <= 1 {
return Ok(false);
}
s.doc.remove_block(story, path)?;
Ok(true)
}
/// Accept or reject the changes of the table cell `path` is in: the table's, its row's and the
/// cell's own. Returns whether there were any.
fn resolve_cell(s: &mut Session, story: StoryRef, path: &wordcraft_doc::Path, accept: bool) -> Result<bool, CmdError> {
@@ -245,8 +263,22 @@ fn resolve_all(s: &mut Session, accept: bool) -> CmdResult {
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() {
// A whole-paragraph mark that resolves to removal at the end of its container takes
// the paragraph with it (there is no follower for `resolve_para` to join). A paragraph
// followed by a table is not the end: removing it could make two tables adjacent.
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)? {
// 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() });
}
}
}
}
}
// Tables, rows, cells, sections and style definitions.
+16 -4
View File
@@ -128,6 +128,20 @@ pub(super) fn suggestions(s: &mut Session, v: &Value) -> CmdResult {
}
}
/// The word at the caret that the thesaurus looks up and a chosen synonym replaces: the word unit
/// without the spaces after it or the quotes around it, so `‘good’` is `good` and its quotes stay
/// when it is replaced; an apostrophe inside a word (`don’t`) is kept (#6517).
pub fn thesaurus_word(s: &Session) -> Option<(Pos, Pos)> {
let f = &s.sel.focus;
let p = s.doc.para_at(f)?;
let (a, b) = p.word_at(f.off);
let w = p.text.get(a..b)?;
let edge = |c: char| c.is_whitespace() || matches!(c, '’' | '‘' | '\'');
let start = a + (w.len() - w.trim_start_matches(edge).len());
let end = (a + w.trim_end_matches(edge).len()).max(start);
Some((Pos { off: start, ..f.clone() }, Pos { off: end, ..f.clone() }))
}
/// A tiny built-in thesaurus of common words (our own list).
pub(super) fn thesaurus(s: &mut Session, v: &Value) -> CmdResult {
const T: &[(&str, &[&str])] = &[
@@ -164,10 +178,8 @@ pub(super) fn thesaurus(s: &mut Session, v: &Value) -> CmdResult {
let word = match p::str(v, "word") {
Some(w) => w.to_lowercase(),
None => {
let f = s.sel.focus.clone();
let p = s.doc.para_at(&f).ok_or_else(|| CmdError::Failed("no word".into()))?;
let (a, b) = p.word_at(f.off);
p.text.get(a..b).unwrap_or("").trim().to_lowercase()
let (a, b) = thesaurus_word(s).ok_or_else(|| CmdError::Failed("no word".into()))?;
s.doc.para_at(&a).and_then(|p| p.text.get(a.off..b.off)).unwrap_or("").to_lowercase()
}
};
let syn = T.iter().find(|(w, _)| *w == word).map(|(_, l)| l.to_vec()).unwrap_or_default();
@@ -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() {
+5 -6
View File
@@ -1622,12 +1622,11 @@ fn block_text(b: &Block, depth: usize) -> String {
/// the paragraph is empty (`format` returns early for a length-0 range). Walks nested tables
/// iteratively, without recursion or depth truncation.
///
/// Known limitation: resolving a revision needs a following paragraph, so a paragraph inserted at
/// the very end (rejected) or deleted from the very end (accepted) still leaves one empty
/// paragraph. That is a separate follow-up, not handled here. A section-carrying inserted
/// paragraph is not such a case: `resolve_para` removes the section break first (#5734, issue
/// #5667), so rejecting it takes the paragraph out whole and the following paragraph keeps its
/// own properties.
/// A whole-paragraph revision on the last paragraph of a story or cell is removed together with
/// the paragraph on Accept/Reject All (see `remove_trailing_para` in `review::changes`), except
/// 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 {
let mut out = b.clone();
let mut todo = vec![&mut out];
+108 -81
View File
@@ -16,72 +16,6 @@ fn empty_paras(s: &Session) -> usize {
s.doc.body.iter().filter(|b| matches!(b.as_para(), Some(p) if p.is_empty())).count()
}
#[test]
fn compare_marks_a_whole_paragraph_and_its_mark() {
// A whole inserted paragraph carries the insertion on its mark, not just on its runs.
let mut s = Session::new(Document::from_text("A\nB"));
s.run("review.compare", &json!({"text": "A\nNEW\nB"})).unwrap();
assert_eq!(s.doc.body.len(), 3);
let mid = s.doc.body[1].as_para().unwrap();
assert_eq!(mid.plain_text(), "NEW");
assert!(mid.mark.ins.is_some(), "the inserted paragraph's mark is not marked inserted");
s.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
assert_eq!(s.doc.body.len(), 2);
assert_eq!(empty_paras(&s), 0, "rejecting an inserted paragraph left an empty paragraph behind");
let mut s = Session::new(Document::from_text("A\nB"));
s.run("review.compare", &json!({"text": "A\nNEW\nB"})).unwrap();
s.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nNEW\nB");
assert_eq!(s.doc.body.len(), 3);
assert_eq!(empty_paras(&s), 0, "accepting an inserted paragraph left an empty paragraph behind");
// A whole deleted paragraph carries the deletion on its mark.
let mut s = Session::new(Document::from_text("A\nOLD\nB"));
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
assert_eq!(s.doc.body.len(), 3);
let mid = s.doc.body[1].as_para().unwrap();
assert_eq!(mid.plain_text(), "OLD");
assert!(mid.mark.del.is_some(), "the deleted paragraph's mark is not marked deleted");
s.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
assert_eq!(s.doc.body.len(), 2);
assert_eq!(empty_paras(&s), 0, "accepting a deleted paragraph left an empty paragraph behind");
let mut s = Session::new(Document::from_text("A\nOLD\nB"));
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
s.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nOLD\nB");
assert_eq!(s.doc.body.len(), 3);
assert_eq!(empty_paras(&s), 0, "rejecting a deleted paragraph left an empty paragraph behind");
}
#[test]
fn compare_marks_an_empty_paragraphs_mark() {
// An empty inserted paragraph is stamped on its mark, though `format` skips its empty range.
let mut s = Session::new(Document::from_text("A\nB"));
s.run("review.compare", &json!({"text": "A\n\nB"})).unwrap();
assert_eq!(s.doc.body.len(), 3);
let empty = s.doc.body[1].as_para().unwrap();
assert!(empty.is_empty());
assert!(empty.mark.ins.is_some(), "the empty inserted paragraph's mark is not marked inserted");
s.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
assert_eq!(s.doc.body.len(), 2);
assert_eq!(empty_paras(&s), 0, "rejecting an empty inserted paragraph left it behind");
// An empty deleted paragraph is stamped on its mark too.
let mut s = Session::new(Document::from_text("A\n\nB"));
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
assert_eq!(s.doc.body.len(), 3);
let empty = s.doc.body[1].as_para().unwrap();
assert!(empty.is_empty());
assert!(empty.mark.del.is_some(), "the empty deleted paragraph's mark is not marked deleted");
s.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
assert_eq!(s.doc.body.len(), 2);
assert_eq!(empty_paras(&s), 0, "accepting an empty deleted paragraph left it behind");
}
#[test]
fn compare_keeps_another_authors_deletion_stamp() {
// A paragraph the original already carries as a tracked deletion by another author: Compare
@@ -105,31 +39,67 @@ fn compare_keeps_another_authors_deletion_stamp() {
}
#[test]
fn compare_pins_the_terminal_inserted_paragraph_limitation() {
// Characterizes the limitation documented on `mark_block` (compare.rs): resolving a revision
// needs a following paragraph, so a paragraph inserted at the very end is rejected but leaves
// one empty paragraph behind. Flip this test when the follow-up fix lands.
fn compare_terminal_inserted_paragraph_resolves_fully() {
// A paragraph inserted at the very end is removed whole when rejected, leaving no empty
// paragraph behind.
let mut s = Session::new(Document::from_text("A\nB"));
s.run("review.compare", &json!({"text": "A\nB\nC"})).unwrap();
assert_eq!(s.doc.body.len(), 3);
s.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB\n", "the rejected terminal paragraph still leaves a line");
assert_eq!(s.doc.body.len(), 3);
assert_eq!(empty_paras(&s), 1, "the rejected terminal paragraph is left as one empty paragraph");
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
assert_eq!(s.doc.body.len(), 2);
assert_eq!(empty_paras(&s), 0, "rejecting a terminal inserted paragraph left an empty paragraph behind");
}
#[test]
fn compare_pins_the_terminal_deleted_paragraph_limitation() {
// The mirror of `compare_pins_the_terminal_inserted_paragraph_limitation`: a paragraph deleted
// from the very end is accepted but still leaves one empty paragraph. Characterizes the
// limitation documented on `mark_block` (compare.rs); flip when the follow-up fix lands.
fn compare_terminal_deleted_paragraph_resolves_fully() {
// The mirror of `compare_terminal_inserted_paragraph_resolves_fully`: a paragraph deleted
// from the very end is removed whole when accepted, leaving no empty paragraph behind.
let mut s = Session::new(Document::from_text("A\nB\nC"));
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
assert_eq!(s.doc.body.len(), 3);
s.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB\n", "the accepted terminal deletion still leaves a line");
assert_eq!(s.doc.body.len(), 3);
assert_eq!(empty_paras(&s), 1, "the accepted terminal deletion is left as one empty paragraph");
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
assert_eq!(s.doc.body.len(), 2);
assert_eq!(empty_paras(&s), 0, "accepting a 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
// would make the tables adjacent, and they would join into one on reopen. Reject All only
// clears its mark.
use wordcraft_doc::{Block, Paragraph, para_block};
let mut doc = Document::from_text("");
doc.revisions.push(wordcraft_doc::Revision::new(RevisionKind::Insert, "Alice", ""));
let table = || std::sync::Arc::new(Block::Table(wordcraft_doc::table::Table::new(1, 1, 100.0)));
let mut between = Paragraph::default();
between.mark.ins = Some(0);
doc.body = vec![table(), para_block(between), table(), para_block(Paragraph::with_text("end", Default::default()))];
let mut s = Session::new(doc);
s.run("review.rejectAll", &json!({})).unwrap();
let kinds: Vec<bool> = s.doc.body.iter().map(|b| matches!(**b, Block::Table(_))).collect();
assert_eq!(kinds, [true, false, true, false]);
let kept = s.doc.para(StoryRef::Body, &wordcraft_doc::Path::top(1)).unwrap();
assert!(kept.is_empty() && kept.mark.ins.is_none(), "{kept:?}");
}
#[test]
@@ -201,6 +171,35 @@ fn compare_pins_accepting_a_deleted_section_keeps_the_next_paragraphs_style() {
assert_eq!(body.props.style.as_deref(), Some("Heading1"), "the following paragraph keeps its own properties (fixed on main by #5734)");
}
#[test]
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();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB\nNEW");
assert_eq!(s.doc.body.len(), 3);
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();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB\nOLD");
assert_eq!(s.doc.body.len(), 3);
assert_eq!(empty_paras(&s), 0);
}
#[test]
fn compare_keeps_the_only_paragraphs_mark() {
let mut s = Session::new(Document::from_text(""));
s.doc.revisions.push(wordcraft_doc::Revision::new(RevisionKind::Insert, s.author.clone(), ""));
s.doc.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap().mark.ins = Some(0);
s.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s.doc.body.len(), 1);
assert!(s.doc.body[0].as_para().unwrap().mark.ins.is_none());
}
#[test]
fn compare_options_ignore_case_and_white_space() {
let original = "The Cat sat.\nTwo spaces here.";
@@ -1681,7 +1680,8 @@ fn compare_lcs_window_move_past_cap_does_not_cascade_false_revisions() {
}
/// Verifies that `mark_block` records paragraph mark revisions on whole-block deletions,
/// whole-block insertions, empty paragraphs, and ensures clean resolution via `review.acceptAll`.
/// whole-block insertions, empty paragraphs, and ensures clean resolution via `review.acceptAll`
/// and `review.rejectAll`.
#[test]
fn compare_mark_block_records_paragraph_mark_revisions_on_whole_block_changes() {
// Whole block delete/insert: test with differing paragraph count so whole-block paths trigger
@@ -1699,17 +1699,34 @@ fn compare_mark_block_records_paragraph_mark_revisions_on_whole_block_changes()
assert!(del_para.mark.del.is_some(), "whole-block delete must record revision on paragraph mark");
assert_eq!(del_para.mark.bold, Some(true), "paragraph mark formatting must be preserved on deleted block");
let mut s2_rej = Session::new(s2.doc.clone());
s2_rej.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s2_rej.doc.plain_text(StoryRef::Body), orig_multi);
assert_eq!(s2_rej.doc.body.len(), 3);
assert_eq!(empty_paras(&s2_rej), 0, "rejecting a deleted paragraph left an empty paragraph behind");
// Accept all changes: deleted paragraph is removed
s2.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s2.doc.plain_text(StoryRef::Body), rev_multi);
assert_eq!(s2.doc.body.len(), 2);
assert_eq!(empty_paras(&s2), 0, "accepting a deleted paragraph left an empty paragraph behind");
// Test whole-block insertion
let mut s3 = Session::new(Document::from_text(rev_multi));
s3.run("review.compare", &json!({"text": orig_multi})).unwrap();
let ins_para = s3.doc.body[1].as_para().expect("block 1 must be paragraph");
assert!(ins_para.mark.ins.is_some(), "whole-block insert must record revision on paragraph mark");
let mut s3_rej = Session::new(s3.doc.clone());
s3_rej.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s3_rej.doc.plain_text(StoryRef::Body), rev_multi);
assert_eq!(s3_rej.doc.body.len(), 2);
assert_eq!(empty_paras(&s3_rej), 0, "rejecting an inserted paragraph left an empty paragraph behind");
s3.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s3.doc.plain_text(StoryRef::Body), orig_multi);
assert_eq!(s3.doc.body.len(), 3);
assert_eq!(empty_paras(&s3), 0, "accepting an inserted paragraph left an empty paragraph behind");
// Test empty paragraph deletion and insertion (len == 0, where only mark carries the revision)
let orig_empty = "Before.\n\nAfter.";
@@ -1721,14 +1738,24 @@ fn compare_mark_block_records_paragraph_mark_revisions_on_whole_block_changes()
assert!(empty_del.mark.del.is_some(), "empty paragraph deletion must set mark.del");
s4.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s4.doc.plain_text(StoryRef::Body), rev_empty);
assert_eq!(s4.doc.body.len(), 2);
assert_eq!(empty_paras(&s4), 0, "accepting an empty deleted paragraph left it behind");
let mut s5 = Session::new(Document::from_text(rev_empty));
s5.run("review.compare", &json!({"text": orig_empty})).unwrap();
let empty_ins = s5.doc.body[1].as_para().expect("empty paragraph block");
assert_eq!(empty_ins.len(), 0);
assert!(empty_ins.mark.ins.is_some(), "empty paragraph insertion must set mark.ins");
let mut s5_rej = Session::new(s5.doc.clone());
s5_rej.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s5_rej.doc.plain_text(StoryRef::Body), rev_empty);
assert_eq!(s5_rej.doc.body.len(), 2);
assert_eq!(empty_paras(&s5_rej), 0, "rejecting an empty inserted paragraph left it behind");
s5.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s5.doc.plain_text(StoryRef::Body), orig_empty);
assert_eq!(s5.doc.body.len(), 3);
}
#[test]
+23
View File
@@ -337,6 +337,29 @@ mod tests {
let _ = std::fs::remove_dir_all(&d);
}
/// A document made from a template is created now, not when the template was: it has no
/// creation date until it is saved, so CREATEDATE in it shows today.
#[test]
fn new_from_template_has_no_creation_date_of_its_own_yet() {
let d = scratch("created");
let path = d.join("Dated.dotx");
let mut t = Session::new(wordcraft_doc::Document::new());
t.run("document.setText", &json!({"text": "Dated"})).unwrap();
t.doc.core.created = "2019-05-05T12:00:00Z".into();
crate::io::save_path(&path, &t.doc).unwrap();
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("file.newFromTemplate", &json!({"path": path.to_string_lossy()})).unwrap();
assert_eq!(s.doc.core.created, "");
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy""#, "result": "2019"})).unwrap();
s.run("references.updateFields", &json!({})).unwrap();
assert!(s.doc.plain_text(wordcraft_doc::StoryRef::Body).contains(&crate::cmd::insert::format_date("yyyy")));
// The template itself keeps its date.
let mut again = Session::new(wordcraft_doc::Document::new());
again.run("file.open", &json!({"path": path.to_string_lossy()})).unwrap();
assert_eq!(again.doc.core.created, "2019-05-05T12:00:00Z");
let _ = std::fs::remove_dir_all(&d);
}
/// #3433: a template the platform hands the app takes an untouched blank document's place
/// (`replaceBlank`), as a file `file.open` opens does; otherwise, and without the flag, the
/// new document opens beside the others, as File › New's does. Either way the template on
+4 -1
View File
@@ -35,7 +35,10 @@ impl Session {
fn leave_math_for_command(&mut self, id: &str) {
self.math_left = false;
if self.math.is_some()
&& (id.starts_with("text.") || id.starts_with("caret.") || id.starts_with("select.") || id.starts_with("edit.paste"))
&& (id.starts_with("text.")
|| id.starts_with("caret.")
|| id.starts_with("select.")
|| (id.starts_with("edit.paste") && id != "edit.pasteFormat"))
&& let Some(m) = self.math.take()
{
let off = m.at.off + wordcraft_doc::para::OBJ.len_utf8();
+461 -2
View File
@@ -293,6 +293,7 @@ fn custom_dictionary_words_persist_through_their_file() {
let _ = std::fs::remove_dir_all(&dir);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn confined_sessions_neither_save_the_dictionary_nor_choose_folders_outside_their_roots() {
let _guard = crate::custom_dict::DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
@@ -1043,6 +1044,201 @@ fn bold_toggles_selection_and_caret_word() {
assert_eq!(p.props_of_char(9).italic, None);
}
/// A partly formatted selection toggles by its first character, as Word does (#6516).
#[test]
fn toggles_on_mixed_selection_follow_first_character() {
// `Abc abc` with `fmt` set by `cmd`, then `cmd` with `v` on the selection `from` → `to`.
let toggled = |cmd: &str, fmt: (usize, usize), from: usize, to: usize, v: serde_json::Value| -> String {
let mut s = s();
run(&mut s, "text.insert", json!({"text": "Abc abc"}));
let sel = |s: &mut Session, a: usize, b: usize| {
run(s, "select.range", json!({"anchor": {"block": 0, "off": a}, "focus": {"block": 0, "off": b}}));
};
sel(&mut s, fmt.0, fmt.1);
run(&mut s, cmd, json!({"value": true}));
sel(&mut s, from, to);
run(&mut s, cmd, v);
let p = s.doc.para_at(&Pos::body(0, 0)).unwrap();
(0..7)
.map(|i| {
let c = p.props_of_char(i);
match cmd {
"format.italic" => c.italic == Some(true),
"format.underline" => c.underline.is_some_and(|u| u != wordcraft_doc::props::Underline::None),
_ => c.bold == Some(true),
}
})
.map(|on| if on { 'F' } else { '.' })
.collect()
};
let t = || json!({});
for cmd in ["format.bold", "format.italic", "format.underline"] {
// `FFF....`: a selection starting on formatted text removes the format from all of it.
assert_eq!(toggled(cmd, (0, 3), 2, 5, t()), "FF.....", "{cmd}");
assert_eq!(toggled(cmd, (0, 3), 0, 7, t()), ".......", "{cmd}");
assert_eq!(toggled(cmd, (0, 3), 1, 7, t()), "F......", "{cmd}");
// Made right to left: still the first character in document order.
assert_eq!(toggled(cmd, (0, 3), 5, 2, t()), "FF.....", "{cmd}");
assert_eq!(toggled(cmd, (0, 3), 7, 0, t()), ".......", "{cmd}");
// `....FFF`: a selection starting on plain text applies it to all of it.
assert_eq!(toggled(cmd, (4, 7), 0, 7, t()), "FFFFFFF", "{cmd}");
// An explicit value still sets.
assert_eq!(toggled(cmd, (0, 3), 0, 7, json!({"value": true})), "FFFFFFF", "{cmd}");
assert_eq!(toggled(cmd, (4, 7), 0, 7, json!({"value": false})), ".......", "{cmd}");
}
}
/// A selection that starts in an empty paragraph: Word decides from the first text character, not
/// from the empty paragraph's mark (observed in Word for Windows, #6516 review).
#[test]
fn toggle_on_a_selection_from_an_empty_paragraph_follows_the_first_text() {
let toggled = |mark_bold: bool, text_bold: bool| -> Option<bool> {
let mut s = s();
run(&mut s, "text.newParagraph", json!({}));
run(&mut s, "text.insert", json!({"text": "abc"}));
let first = Pos::body(0, 0);
s.doc.para_mut(first.story, &first.path).unwrap().mark.bold = Some(mark_bold);
run(&mut s, "select.range", json!({"anchor": {"block": 1, "off": 0}, "focus": {"block": 1, "off": 3}}));
run(&mut s, "format.bold", json!({"value": text_bold}));
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 0}, "focus": {"block": 1, "off": 3}}));
run(&mut s, "format.bold", json!({}));
s.doc.para_at(&Pos::body(1, 0)).unwrap().props_of_char(0).bold
};
// A bold empty paragraph before plain text: Bold goes on.
assert_eq!(toggled(true, false), Some(true));
// A plain empty paragraph before bold text: Bold comes off.
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).
let bold_word = |text: &str, caret: usize| {
let mut s = s();
run(&mut s, "text.insert", json!({"text": text}));
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": caret}}));
run(&mut s, "format.bold", json!({}));
let p = s.doc.para_at(&Pos::body(0, 0)).unwrap().clone();
p.text.char_indices().filter(|&(i, _)| p.props_of_char(i).bold == Some(true)).map(|(_, c)| c).collect::<String>()
};
assert_eq!(bold_word("don’t stop", 1), "don’t");
assert_eq!(bold_word("the dogs’ bone", 5), "dogs’");
assert_eq!(bold_word("’tis here", 3), "’tis");
}
#[test]
fn select_word_takes_a_typographic_apostrophe() {
let mut s = s();
run(&mut s, "text.insert", json!({"text": "don’t stop"}));
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": 1}}));
run(&mut s, "select.word", json!({}));
let (a, b) = s.sel.ordered();
assert_eq!((a.off, b.off), (0, 8), "`don’t ` with its trailing space, as Word selects it (#6517)");
}
#[test]
fn thesaurus_at_a_caret_looks_up_a_quoted_word_without_its_quotes() {
// The word unit now takes `’`, so `‘good’` gives `good’`; the lookup drops enclosing quotes.
let mut s = s();
run(&mut s, "text.insert", json!({"text": "a ‘good’ day"}));
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": 6}}));
let r = run(&mut s, "review.thesaurus", json!({}));
assert_eq!(r["word"], json!("good"));
assert!(r["synonyms"].as_array().is_some_and(|a| !a.is_empty()), "{r}");
}
#[test]
fn a_synonym_replaces_the_word_and_keeps_its_quotes() {
// The range a chosen synonym replaces (the context menu's): the word without its quotes or the
// space after it, while an apostrophe inside a word stays part of it (#6517).
let word = |text: &str, caret: usize| {
let mut s = s();
run(&mut s, "text.insert", json!({"text": text, "raw": true}));
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": caret}}));
let (a, b) = crate::cmd::review::thesaurus_word(&s).unwrap();
s.set_selection(crate::Selection { anchor: a, focus: b });
run(&mut s, "text.insert", json!({"text": "fine", "raw": true}));
s.doc.plain_text(StoryRef::Body)
};
assert_eq!(word("a ‘good’ day", 6), "a ‘fine’ day");
assert_eq!(word("a 'good' day", 4), "a 'fine' day");
assert_eq!(word("a good day", 3), "a fine day");
assert_eq!(word("don’t go", 1), "fine go");
}
#[test]
fn border_toggles_and_saves() {
use wordcraft_doc::props::Border;
@@ -2054,6 +2250,88 @@ fn paste_merge_formatting_keeps_bold_and_italic_in_a_complex_script_run() {
assert!(r.bold_cs, "drawn bold as complex script");
}
#[test]
fn paste_merge_formatting_leaves_plain_what_the_source_draws_plain() {
// #4852 review: a run marked `w:cs` is bold and italic only by `w:bCs` and `w:iCs`, so one
// with `w:b` and `w:i` alone is drawn plain and pastes plain; one with `w:bCs` pastes bold.
let mut s = s();
run(&mut s, "document.setText", json!({"text": "x"}));
run(&mut s, "caret.docEnd", json!({}));
let pasted = |s: &Session, props: wordcraft_doc::CharProps| {
let mut frag = wordcraft_doc::edit::Fragment::from_text("ไทย");
for b in &mut frag.blocks {
crate::cmd::paste::each_para(b, 0, &mut |p| p.runs.iter_mut().for_each(|r| r.props = props.clone()));
}
crate::cmd::paste::merge_formatting(s, &mut frag);
let mut out = Vec::new();
for b in &mut frag.blocks {
crate::cmd::paste::each_para(b, 0, &mut |p| out.extend(p.runs.iter().map(|r| s.doc.styles.resolve_char(None, &r.props))));
}
out
};
let cs = wordcraft_doc::CharProps { cs: Some(true), bold: Some(true), italic: Some(true), ..Default::default() };
for r in pasted(&s, cs.clone()) {
assert!(!r.bold && !r.bold_cs && !r.italic && !r.italic_cs, "{r:?}");
}
for r in pasted(&s, wordcraft_doc::CharProps { bold_cs: Some(true), ..cs }) {
assert!(r.bold && r.bold_cs && !r.italic_cs, "{r:?}");
}
// An unmarked run shows `w:b` in both scripts.
for r in pasted(&s, wordcraft_doc::CharProps { bold: Some(true), ..Default::default() }) {
assert!(r.bold && r.bold_cs, "{r:?}");
}
}
#[test]
fn paste_merge_formatting_keeps_a_character_styles_emphasis_not_a_paragraph_styles() {
// #7177 review, measured in Word for Windows: Merge Formatting keeps the bold, italic,
// underline and strikethrough a character style gives the source, as direct formatting, but
// drops a paragraph style's.
use wordcraft_doc::props::Underline;
use wordcraft_doc::styles::{Style, StyleKind};
let mut s = s();
run(&mut s, "document.setText", json!({"text": "x"}));
run(&mut s, "caret.docEnd", json!({}));
let on = wordcraft_doc::CharProps {
bold: Some(true),
bold_cs: Some(true),
italic: Some(true),
italic_cs: Some(true),
underline: Some(Underline::Single),
strike: Some(true),
..Default::default()
};
let sheet = Arc::make_mut(&mut s.doc.styles);
sheet.upsert(Style { id: "ChEmph".into(), name: "ChEmph".into(), kind: StyleKind::Character, chr: on.clone(), ..Default::default() });
sheet.upsert(Style { id: "PEmph".into(), name: "PEmph".into(), kind: StyleKind::Paragraph, chr: on, ..Default::default() });
let pasted = |s: &Session, para_style: Option<&str>, props: wordcraft_doc::CharProps| {
let mut frag = wordcraft_doc::edit::Fragment::from_text("ไทย Thai");
for b in &mut frag.blocks {
crate::cmd::paste::each_para(b, 0, &mut |p| {
p.props.style = para_style.map(str::to_string);
p.runs.iter_mut().for_each(|r| r.props = props.clone());
});
}
crate::cmd::paste::merge_formatting(s, &mut frag);
let mut out = Vec::new();
for b in &mut frag.blocks {
crate::cmd::paste::each_para(b, 0, &mut |p| {
out.extend(p.runs.iter().map(|r| s.doc.styles.resolve_char(p.props.style.as_deref(), &r.props)));
});
}
out
};
for cs in [None, Some(true)] {
for r in pasted(&s, None, wordcraft_doc::CharProps { style: Some("ChEmph".into()), cs, ..Default::default() }) {
assert!(r.bold && r.bold_cs && r.italic && r.italic_cs && r.strike, "character style, cs {cs:?}: {r:?}");
assert_eq!(r.underline, Underline::Single, "character style, cs {cs:?}");
}
for r in pasted(&s, Some("PEmph"), wordcraft_doc::CharProps { cs, ..Default::default() }) {
assert!(!r.bold && !r.bold_cs && !r.italic && !r.italic_cs && !r.strike, "paragraph style, cs {cs:?}: {r:?}");
assert_eq!(r.underline, Underline::None, "paragraph style, cs {cs:?}");
}
}
}
#[test]
fn pasted_rtf_sections_link_their_headers_to_the_previous() {
// #1378: the RTF's own header part ids mean nothing in this document; a pasted section
@@ -4896,6 +5174,48 @@ fn no_markup_view_lays_out_the_final_text() {
assert!(gap(&mut s).abs() < 0.01);
}
#[test]
fn horizontal_caret_skips_hidden_tracked_deletions() {
let mut s = s();
let text = "Aé🧪ZUVΩT";
let before = Pos::body(0, "A".len());
let between = Pos::body(0, "Aé".len());
let after = Pos::body(0, "Aé🧪".len());
let far_start = Pos::body(0, "Aé🧪ZUV".len());
let far_end = Pos::body(0, "Aé🧪ZUVΩ".len());
run(&mut s, "document.setText", json!({"text": text}));
// Keep the adjacent deleted characters in separate formatting runs.
s.doc.format_range(&before, &between, &|c| c.bold = Some(true)).unwrap();
run(&mut s, "review.trackChanges", json!({"value": true}));
run(&mut s, "select.text", json!({"text": "é🧪"}));
run(&mut s, "text.delete", json!({}));
run(&mut s, "select.text", json!({"text": "Ω"}));
run(&mut s, "text.delete", json!({}));
assert_eq!(s.doc.para_at(&before).unwrap().deleted_ranges(), [before.off..between.off, between.off..after.off, far_start.off..far_end.off]);
s.sel = crate::Selection::caret(before.clone());
run(&mut s, "caret.right", json!({}));
assert_eq!(s.sel.focus, Pos::body(0, "Aé".len()), "visible markup still has ordinary caret stops");
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
s.sel = crate::Selection::caret(before.clone());
run(&mut s, "caret.right", json!({"extend": true}));
assert_eq!(s.sel.anchor, before);
assert_eq!(s.sel.focus, Pos::body(0, "Aé🧪Z".len()), "Right crosses the next visible character in one step");
s.sel = crate::Selection::caret(after);
run(&mut s, "caret.left", json!({}));
assert_eq!(s.sel.focus, Pos::body(0, 0), "Left crosses the previous visible character in one step");
assert!(s.sel.is_collapsed());
s.sel = crate::Selection::caret(Pos::body(0, "Aé🧪Z".len()));
run(&mut s, "caret.right", json!({}));
assert_eq!(s.sel.focus, Pos::body(0, "Aé🧪ZU".len()), "a distant deletion does not change a visible stop");
s.sel = crate::Selection::caret(far_end);
run(&mut s, "caret.left", json!({}));
assert_eq!(s.sel.focus, Pos::body(0, "Aé🧪ZU".len()), "Left also skips the later deletion");
}
#[test]
fn replace_all_is_tracked() {
let mut s = s();
@@ -7301,6 +7621,64 @@ fn saving_a_text_file_over_itself_saves_the_document() {
let _ = std::fs::remove_dir_all(&dir);
}
/// #6131: File › Export to DOCX, ODT or RTF writes a copy (`copy: true`). It made the copy the
/// document's file and cleared its unsaved changes, so the next Save went to the copy and the
/// original kept its old text. The copy has the edits; the document keeps its file, its changes
/// and its save stamps.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn exporting_a_copy_keeps_the_documents_file() {
let dir = std::env::temp_dir().join(format!("wordcraft-engine-export-copy-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let body = |p: &std::path::Path| crate::io::open_path(p).unwrap().plain_text(wordcraft_doc::StoryRef::Body);
for ext in ["docx", "odt", "rtf"] {
let original = dir.join(format!("a-{ext}.docx"));
let mut s = Session::new(wordcraft_doc::Document::new());
run(&mut s, "text.insert", json!({"text": "first"}));
run(&mut s, "file.save", json!({"path": original.to_string_lossy()}));
run(&mut s, "text.insert", json!({"text": " edited"}));
let stamps = (s.doc.core.revision, s.doc.core.modified.clone());
let copy = dir.join(format!("copy.{ext}"));
let r = run(&mut s, "file.saveAs", json!({"path": copy.to_string_lossy(), "copy": true}));
assert_eq!(r["saved"], true, "{ext}");
assert_eq!(body(&copy), "first edited", "{ext}: the copy has the edits");
assert_eq!(s.path.as_deref(), Some(original.as_path()), "{ext}: the document keeps its file");
assert!(s.dirty, "{ext}: the document keeps its unsaved changes");
assert_eq!((s.doc.core.revision, s.doc.core.modified.clone()), stamps, "{ext}: the document's save stamps are untouched");
run(&mut s, "file.save", json!({}));
assert_eq!(body(&original), "first edited", "{ext}: Save still writes the original");
assert!(!s.dirty);
}
let _ = std::fs::remove_dir_all(&dir);
}
/// A copy with no path would open the Save As picker on an untitled document (whose answer is an
/// ordinary save that adopts the file) or fall back to the open file's path and overwrite it while
/// leaving the document dirty: refused in both cases (#6131 review).
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_copy_without_a_path_is_refused() {
let mut s = Session::new(wordcraft_doc::Document::new());
run(&mut s, "text.insert", json!({"text": "first"}));
let e = s.run("file.save", &json!({"copy": true})).unwrap_err();
assert!(e.to_string().contains("copy"), "{e}");
assert!(s.ui_requests.is_empty(), "no picker opens");
let dir = std::env::temp_dir().join(format!("wordcraft-engine-copy-no-path-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let original = dir.join("doc.docx");
run(&mut s, "file.save", json!({"path": original.to_string_lossy()}));
run(&mut s, "text.insert", json!({"text": " edited"}));
let e = s.run("file.save", &json!({"copy": true})).unwrap_err();
assert!(e.to_string().contains("copy"), "{e}");
assert!(s.dirty, "the document keeps its unsaved changes");
let on_disk = crate::io::open_path(&original).unwrap().plain_text(wordcraft_doc::StoryRef::Body);
assert_eq!(on_disk, "first", "the original file on disk was not overwritten");
let _ = std::fs::remove_dir_all(&dir);
}
/// A Markdown file saved as another Markdown file is that file from now on: the next save goes
/// there and the first file stays as it was. Other formats keep the #2376 rule.
#[cfg(not(target_arch = "wasm32"))]
@@ -12352,10 +12730,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();
}
}
@@ -15895,3 +16275,82 @@ fn nested_group_text_box_survives_mutating_session_commands() {
assert_eq!(s.doc.plain_text(StoryRef::Part(id)), "nested group box");
}
}
#[test]
fn copy_refuses_to_fill_clipboard_by_halves_when_export_fails() {
let mut s = Session::new(wordcraft_doc::Document::from_text("first second"));
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, 5)}));
run(&mut s, "edit.copy", json!({}));
let prev_text = s.clipboard_text.clone();
let prev_html = s.clipboard_html.clone();
let prev_rtf = s.clipboard_rtf.clone();
let prev_history_len = s.clip_history.len();
assert_eq!(prev_text, "first");
assert!(!prev_html.is_empty() && !prev_rtf.is_empty());
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 6), "focus": Pos::body(0, 12)}));
// HTML export fails first.
let err = wordcraft_formats::with_shared_conversion_error("html failed", || s.run("edit.copy", &json!({}))).unwrap_err();
assert!(err.to_string().contains("html failed"), "{err}");
assert_eq!(s.clipboard_text, prev_text);
assert_eq!(s.clipboard_html, prev_html);
assert_eq!(s.clipboard_rtf, prev_rtf);
assert_eq!(s.clipboard.as_ref().map(|f| f.plain_text()), Some("first".to_string()));
assert_eq!(s.clip_history.len(), prev_history_len);
// HTML export succeeds and RTF export fails: clipboard still keeps "first" whole.
let err = wordcraft_formats::with_shared_conversion_error_after(1, "rtf failed", || s.run("edit.copy", &json!({}))).unwrap_err();
assert!(err.to_string().contains("rtf failed"), "{err}");
assert_eq!(s.clipboard_text, prev_text);
assert_eq!(s.clipboard_html, prev_html);
assert_eq!(s.clipboard_rtf, prev_rtf);
assert_eq!(s.clipboard.as_ref().map(|f| f.plain_text()), Some("first".to_string()));
assert_eq!(s.clip_history.len(), prev_history_len);
// Cut also refuses to delete the selection when export fails.
let err = wordcraft_formats::with_shared_conversion_error_after(1, "rtf failed", || s.run("edit.cut", &json!({}))).unwrap_err();
assert!(err.to_string().contains("rtf failed"), "{err}");
assert_eq!(text(&s), "first second");
assert_eq!(s.clipboard_text, prev_text);
assert_eq!(s.clipboard_html, prev_html);
assert_eq!(s.clipboard_rtf, prev_rtf);
assert_eq!(s.clip_history.len(), prev_history_len);
}
#[test]
fn paste_reports_or_falls_back_when_html_import_fails() {
let mut s = Session::new(wordcraft_doc::Document::from_text("kept"));
let err = wordcraft_formats::with_shared_conversion_error("html import failed", || {
s.run("edit.pasteSpecial", &json!({"as": "html", "html": "<p>new</p>"}))
})
.unwrap_err();
assert!(err.to_string().contains("html import failed"), "{err}");
assert_eq!(text(&s), "kept");
let fallback = wordcraft_formats::with_shared_conversion_error_after(0, "html import failed", || {
cmd::paste::rich_fragment(&mut s, &json!({"html": "<p>from html</p>", "rtf": "{\\rtf1 from rtf}"}))
});
assert_eq!(fallback.as_ref().map(|f| f.plain_text()), Some("from rtf".to_string()));
let none = wordcraft_formats::with_shared_conversion_error("html import failed", || {
cmd::paste::rich_fragment(&mut s, &json!({"html": "<p>from html</p>"}))
});
assert!(none.is_none());
}
#[test]
fn open_and_save_report_format_conversion_errors() {
let doc = wordcraft_doc::Document::from_text("hello");
wordcraft_formats::with_shared_conversion_error("bridge down", || {
for (name, bytes) in [("a.html", b"<p>hello</p>" as &[u8]), ("a.md", b"# hello"), ("a.tex", b"hello")] {
let err = crate::io::open_bytes(name, bytes).unwrap_err();
assert!(err.contains("bridge down"), "{name}: {err}");
}
for name in ["a.html", "a.md", "a.tex", "a.rtf"] {
let err = crate::io::save_bytes(name, &doc).unwrap_err();
assert!(err.contains("bridge down"), "{name}: {err}");
}
});
}
+21
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.
+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]
+84
View File
@@ -1653,6 +1653,38 @@ fn a_link_keeps_a_selection_it_cannot_retype() {
assert_eq!(s.doc.field_ranges(StoryRef::Body).len(), 1);
}
#[test]
fn a_column_selection_in_one_paragraph_is_not_one_line() {
// A column (block) selection over the wrapped lines of one paragraph: both its ends are in
// that paragraph, but it holds a piece of each line, so Word shows <<Selection in Document>>
// for it and the text to display can't retype it (#8581).
let mut s = typed("alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron pi rho sigma tau");
let (first, second) = {
let l = s.layout();
let len = s.doc.para_at(&Pos::body(0, 0)).unwrap().text.len();
let mut top = None;
let mut first = None;
let mut second = None;
for off in 0..=len {
let Some(c) = l.caret_on(&Pos::body(0, off), 0) else { continue };
if top.is_some_and(|t| t != c.top) && second.is_none() {
second = Some(off + 10);
break;
}
if top.is_none() {
top = Some(c.top);
first = Some(off);
}
}
(first.expect("the paragraph is laid out"), second.expect("the paragraph wraps"))
};
run(&mut s, "select.column", json!({"anchor": Pos::body(0, first), "focus": Pos::body(0, second)}));
let segs = s.column_segments().expect("the block is one paragraph's lines").to_vec();
assert_eq!(segs.len(), 2, "the block holds a piece of each of the paragraph's two lines");
assert!(segs.iter().all(|(a, b)| a.path == segs[0].0.path && b.path == segs[0].0.path), "both pieces are in one paragraph");
assert!(!crate::cmd::insert::selection_is_one_line(&s), "a column selection is not one line of text");
}
#[test]
fn typing_then_selecting_then_typing_are_two_undo_steps() {
// #419: a selection that moves the insertion point ends the typing group, like a caret move.
@@ -2439,6 +2471,58 @@ 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 (key, shift_key, equation, from, across, math_pos) in [
("Right", "Shift+Right", after, before, after + equation_width, MathPos::default()),
("Left", "Shift+Left", before, after + equation_width, before, end),
] {
let mut s = typed("aéb");
let from = Pos::body(0, from);
let equation = Pos::body(0, equation);
run(&mut s, "caret.set", json!({"pos": equation}));
run(&mut s, "insert.equation", json!({"linear": "x+y", "edit": false}));
run(&mut s, "review.trackChanges", json!({"value": true}));
run(&mut s, "select.text", json!({"text": "é"}));
run(&mut s, "text.delete", json!({}));
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
run(&mut s, "caret.set", json!({"pos": from}));
arrow(&mut s, shift_key);
assert!(editing(&s).is_none(), "{shift_key} extends the selection");
assert_eq!((s.sel.anchor.clone(), s.sel.focus.clone()), (from.clone(), Pos::body(0, across)));
run(&mut s, "caret.set", json!({"pos": from}));
arrow(&mut s, key);
assert_eq!(editing(&s), Some((equation, math_pos)));
}
}
#[test]
fn right_out_of_an_equation_steps_into_the_one_beside_it() {
let e = wordcraft_doc::para::OBJ.len_utf8();
+66
View File
@@ -129,6 +129,72 @@ fn a_date_field_in_a_header_is_refreshed_too() {
assert_eq!(found, [today], "the header's field is refreshed as well as the body's");
}
/// A document whose `docDefaults` set `lang`, so a field run that names no language inherits it,
/// as a German Word document does.
fn open_body_in_lang(lang: &str, body: &str) -> wordcraft_doc::Document {
let rels = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
let doc_rels = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rIdStyles" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>"#;
let styles = format!(
r#"<?xml version="1.0" encoding="UTF-8"?><w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:docDefaults><w:rPrDefault><w:rPr><w:lang w:val="{lang}"/></w:rPr></w:rPrDefault></w:docDefaults><w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style></w:styles>"#
);
let doc = format!(
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
);
wordcraft_engine::io::open_bytes(
"d.docx",
&zip(&[("_rels/.rels", rels), ("word/document.xml", &doc), ("word/_rels/document.xml.rels", doc_rels), ("word/styles.xml", &styles)]),
)
.expect("opens")
}
/// German documents carry their language in `docDefaults`, not on each field run. A `DATE` field
/// without `\@` therefore uses `dd.MM.yyyy`, and `MMMM`/`dddd` name the day in German, on open
/// and on an explicit refresh, for `de-DE`, `de-AT` and `de-CH` (#7146).
#[test]
fn german_date_fields_inherit_the_document_default_language() {
const PICTURE: &str = "dddd, d. MMMM yyyy";
for lang in ["de-DE", "de-AT", "de-CH"] {
let d = open_body_in_lang(
lang,
&format!(
"<w:p>{}</w:p><w:p>{}</w:p>",
field(&format!(r#"DATE \@ "{PICTURE}""#), "Wednesday, 1 January 2020", false),
field("DATE", "1/1/2020", false)
),
);
let expected = wordcraft_engine::cmd::insert::format_date_in(PICTURE, Some(lang));
let got = fields(&d);
assert_eq!(got.len(), 2, "{lang}");
assert_eq!(got[0].1, expected, "{lang}: weekday and month names come from docDefaults");
assert_ne!(got[0].1, wordcraft_engine::cmd::insert::format_date_in(PICTURE, None), "{lang}: not the English names");
assert_eq!(
got[1].1,
wordcraft_engine::cmd::insert::format_date_in("dd.MM.yyyy", Some(lang)),
"{lang}: a DATE field without a picture uses the German default"
);
// Saving and reopening keeps the inherited language, and an explicit refresh does not
// fall back to English.
let written = wordcraft_docx::write(&d).unwrap();
let mut reopened = wordcraft_engine::io::open_bytes("reopened.docx", &written).unwrap();
wordcraft_engine::cmd::references::refresh_date_fields(&mut reopened);
let got = fields(&reopened);
assert_eq!(got[0].1, expected, "{lang}: after round-trip");
assert_eq!(got[1].1, wordcraft_engine::cmd::insert::format_date_in("dd.MM.yyyy", Some(lang)), "{lang}: after round-trip");
}
}
/// 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]
fn a_german_time_field_uses_german_names() {
const PICTURE: &str = "dddd, d. MMMM yyyy 'um' HH:mm";
let d =
open_body_in_lang("de-DE", &format!("<w:p>{}</w:p>", field(&format!(r#"TIME \@ "{PICTURE}""#), "Wednesday, 1 January 2020 um 00:00", false)));
let got = fields(&d);
assert_eq!(got[0].0, format!(r#"TIME \@ "{PICTURE}""#));
assert_eq!(got[0].1, wordcraft_engine::cmd::insert::format_date_in(PICTURE, Some("de-DE")));
}
/// 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> {
+1 -1
View File
@@ -25,7 +25,7 @@ mod lookup;
mod names;
use face::{BUNDLED, FontBytes};
pub use face::{FALLBACK_FAMILY, FaceRef, FontFace, bundled};
pub use face::{FALLBACK_FAMILY, FaceRef, FontFace, bundled, bundled_inter};
#[cfg(test)]
use fallback_data::{Coverage, RUN_FALLBACK_CACHE_CHARS, SYS_FALLBACK_MAX_FILE, file_coverage, ranges_hold};
#[cfg(not(target_arch = "wasm32"))]
+12 -2
View File
@@ -13,6 +13,16 @@ pub fn bundled() -> &'static [&'static [u8]] {
BUNDLED
}
/// The bundled Inter Regular and SemiBold, each with its style name: the same bytes as in [`bundled`], so a caller
/// adds no second copy to the binary. The interface draws with them behind the suite's Inter, which is cut to Latin,
/// Greek and Cyrillic.
pub fn bundled_inter() -> [(&'static str, &'static [u8]); 2] {
[("Regular", INTER_REGULAR), ("SemiBold", INTER_SEMIBOLD)]
}
static INTER_REGULAR: &[u8] = include_bytes!("../../../../assets/fonts/Inter-Regular.ttf");
static INTER_SEMIBOLD: &[u8] = include_bytes!("../../../../assets/fonts/Inter-SemiBold.ttf");
pub(super) static BUNDLED: &[&[u8]] = &[
include_bytes!("../../../../assets/fonts/SourceSans3-Regular.ttf"),
include_bytes!("../../../../assets/fonts/SourceSans3-Semibold.ttf"),
@@ -23,9 +33,9 @@ pub(super) static BUNDLED: &[&[u8]] = &[
include_bytes!("../../../../assets/fonts/SourceSerif4-Semibold.ttf"),
include_bytes!("../../../../assets/fonts/SourceSerif4-Bold.ttf"),
include_bytes!("../../../../assets/fonts/SourceSerif4-BoldIt.ttf"),
include_bytes!("../../../../assets/fonts/Inter-Regular.ttf"),
INTER_REGULAR,
include_bytes!("../../../../assets/fonts/Inter-Medium.ttf"),
include_bytes!("../../../../assets/fonts/Inter-SemiBold.ttf"),
INTER_SEMIBOLD,
include_bytes!("../../../../assets/fonts/JetBrainsMono-Regular.ttf"),
];
+1 -1
View File
@@ -17,7 +17,7 @@ pub mod word;
pub use fontdb::{
FALLBACK_FAMILY, FONT_FILE_EXTS, FaceRef, FontDb, FontFace, FontFormat, Installed, LocalName, MAX_FONT_FILE_BYTES, UserFont, UserFontError,
base_style, bundled, decode_font_file, is_font_file_name, name_language_matches, sniff, system_font_dirs,
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};
+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())
}
+337 -9
View File
@@ -95,15 +95,7 @@ pub fn read_rows(bytes: &[u8], pick: Pick<'_>) -> Result<(Vec<String>, Vec<Vec<S
let names: Vec<String> = book.sheets.iter().map(|s| s.name.clone()).collect();
let i = resolve(&names, pick)?;
let sheet = &book.sheets[i];
let rows = cells_to_rows(&sheet.cells, |c| {
if !c.text.is_empty() {
clamp_cell(c.text.clone())
} else if let Some(v) = c.value() {
format_value(&v)
} else {
String::new()
}
});
let rows = cells_to_rows(&sheet.cells, ods_value);
return Ok((names, rows));
}
Err("not an Excel or OpenDocument spreadsheet".into())
@@ -178,6 +170,187 @@ fn format_value(v: &Value) -> String {
}
}
/// An OpenDocument cell's display string, from `office:value-type`: floats from `office:value`,
/// dates and times from `office:date-value` / `office:time-value` in ISO 8601 form (`yyyy-mm-dd`,
/// `yyyy-mm-dd hh:mm[:ss]`, `hh:mm[:ss]`), booleans as `TRUE`/`FALSE`, and strings, percentages
/// and currencies as the cell's text (their value when the text is blank). A value that does not
/// parse falls back to the text. A covered cell under a merged cell is blank.
///
/// A float merges its value, not the text its number format shows: a ZIP code `01234` shown
/// through the format `00000` merges as `1234`, and `1,234` shown with a thousands separator
/// merges as `1234`.
fn ods_value(c: &craft_ods::Cell) -> String {
use craft_ods::ValueType as T;
if c.covered {
return String::new();
}
let typed = match (c.value_type, c.raw.as_deref().map(str::trim)) {
(Some(T::Float | T::Boolean), Some(_)) => c.value().map(|v| format_value(&v)),
(Some(T::Date), Some(v)) => iso_datetime(v),
(Some(T::Time), Some(v)) => iso_time(v),
(Some(T::Percentage | T::Currency | T::String), Some(_)) if c.text.is_empty() => c.value().map(|v| format_value(&v)),
_ => None,
};
typed.map(clamp_cell).unwrap_or_else(|| clamp_cell(c.text.clone()))
}
/// An ISO 8601 date or date-time (`2024-03-05`, `2024-03-05T13:45:00.000`) as `yyyy-mm-dd`,
/// with ` hh:mm[:ss]` when the time isn't midnight. `None` unless the whole value is a valid
/// calendar date and clock time.
fn iso_datetime(v: &str) -> Option<String> {
use chrono::Datelike;
let v = v.trim();
let (date, time) = match v.split_once('T') {
Some((date, time)) => (date, Some(time)),
None => (v, None),
};
// A date alone may carry a zone (`Z` or `±hh:mm`), which is left out.
let date = match (time, date.strip_suffix('Z')) {
(None, Some(d)) => d,
(None, None) if date.len() > 6 && date.get(date.len() - 6..).is_some_and(|z| z.starts_with(['+', '-']) && z.get(3..4) == Some(":")) => {
zone_offset(date.get(date.len() - 5..)?)?;
date.get(..date.len() - 6)?
}
_ => date,
};
let date = chrono::NaiveDate::parse_from_str(date, "%Y-%m-%d").ok()?;
let mut out = format!("{:04}-{:02}-{:02}", date.year(), date.month(), date.day());
if let Some(time) = time {
let (clock, fraction) = clock_time(time)?;
if clock != chrono::NaiveTime::MIN || !fraction.is_empty() {
out.push(' ');
out.push_str(&hh_mm((clock, fraction)));
}
}
Some(out)
}
/// A clock time `hh:mm[:ss[.s…]]` with an optional `Z` or `±hh:mm` zone (one, not both), which is
/// left out. The seconds' fraction comes back as its digits as written, trailing zeros dropped,
/// so a fraction finer than a nanosecond is kept.
fn clock_time(t: &str) -> Option<(chrono::NaiveTime, String)> {
let t = match (t.strip_suffix('Z'), t.rfind(['+', '-'])) {
(Some(t), _) => t,
(None, Some(i)) => {
zone_offset(t.get(i + 1..)?)?;
t.get(..i)?
}
(None, None) => t,
};
let (clock, fraction) = match t.split_once('.') {
// A fraction needs whole seconds before it.
Some((t, frac)) => {
if frac.is_empty() || !frac.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
(chrono::NaiveTime::parse_from_str(t, "%H:%M:%S").ok()?, frac.trim_end_matches('0'))
}
None => (chrono::NaiveTime::parse_from_str(t, "%H:%M:%S").or_else(|_| chrono::NaiveTime::parse_from_str(t, "%H:%M")).ok()?, ""),
};
// A leap second (`23:59:60`) is not a time a cell holds.
(chrono::Timelike::nanosecond(&clock) < 1_000_000_000).then(|| (clock, fraction.to_string()))
}
/// A zone offset's `hh:mm`, two digits each and at most `14:00` as XML Schema allows.
fn zone_offset(z: &str) -> Option<()> {
use chrono::Timelike;
let two_digit = z.len() == 5 && z.bytes().enumerate().all(|(i, b)| if i == 2 { b == b':' } else { b.is_ascii_digit() });
if !two_digit {
return None;
}
let z = chrono::NaiveTime::parse_from_str(z, "%H:%M").ok()?;
(z.hour() < 14 || (z.hour() == 14 && z.minute() == 0)).then_some(())
}
/// `hh:mm`, with `:ss` when the seconds aren't zero and their fraction when it isn't.
fn hh_mm((t, fraction): (chrono::NaiveTime, String)) -> String {
use chrono::Timelike;
let (h, m, s) = (t.hour(), t.minute(), t.second());
if !fraction.is_empty() {
format!("{h:02}:{m:02}:{s:02}.{fraction}")
} else if s == 0 {
format!("{h:02}:{m:02}")
} else {
format!("{h:02}:{m:02}:{s:02}")
}
}
/// An ISO 8601 duration (`PT13H45M00S`, `P1DT2H`, `-PT1H`) or clock time (`13:45[:00]`) as
/// `hh:mm[:ss]`, a duration's days counted as hours and a negative one with a leading `-`.
/// `None` for anything else, years and months included.
fn iso_time(v: &str) -> Option<String> {
let t = v.trim();
let (negative, t) = match t.strip_prefix('-') {
Some(rest) => (true, rest),
None => (false, t),
};
let Some(t) = t.strip_prefix('P') else {
return if negative { None } else { clock_time(t).map(hh_mm) };
};
let (days, t, has_t) = match t.split_once('T') {
Some((days, time)) => (days, time, true),
None => (t, "", false),
};
// A `T` needs a time after it.
if has_t && t.is_empty() {
return None;
}
let mut any = !days.is_empty();
let days: u64 = if days.is_empty() { 0 } else { days.strip_suffix('D')?.parse().ok()? };
let (mut h, mut m, mut s) = (0u64, 0u64, 0u64);
// The seconds' fraction digits, kept as written.
let mut fraction = String::new();
let mut num = String::new();
// Units come in the order H, M, S, each at most once.
let mut next_unit = 0;
for c in t.chars() {
let unit = match c {
'H' => 1,
'M' => 2,
'S' => 3,
'0'..='9' | '.' if num.len() < 20 => {
num.push(c);
continue;
}
_ => return None,
};
if unit <= next_unit {
return None;
}
next_unit = unit;
let n = std::mem::take(&mut num);
match unit {
1 => h = n.parse().ok()?,
2 => m = n.parse().ok()?,
_ => {
let (whole, frac) = n.split_once('.').unwrap_or((&n, ""));
if whole.is_empty() || (n.contains('.') && frac.is_empty()) || !frac.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
s = whole.parse().ok()?;
fraction = frac.trim_end_matches('0').to_string();
}
}
any = true;
}
if !any || !num.is_empty() {
return None;
}
// A duration too long to count in hours is not a time.
m = m.checked_add(s / 60)?;
s %= 60;
h = h.checked_add(m / 60)?.checked_add(days.checked_mul(24)?)?;
m %= 60;
let sign = if negative && ((h, m, s) != (0, 0, 0) || !fraction.is_empty()) { "-" } else { "" };
Some(if !fraction.is_empty() {
format!("{sign}{h:02}:{m:02}:{s:02}.{fraction}")
} else if s == 0 {
format!("{sign}{h:02}:{m:02}")
} else {
format!("{sign}{h:02}:{m:02}:{s:02}")
})
}
fn cells_to_rows<C>(cells: &BTreeMap<CellRef, C>, fmt: impl Fn(&C) -> String) -> Vec<Vec<String>> {
let mut grid: BTreeMap<(u32, u32), String> = BTreeMap::new();
for (r, c) in cells {
@@ -208,3 +381,158 @@ fn grid_to_rows(grid: &BTreeMap<(u32, u32), String>) -> Vec<Vec<String>> {
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
/// An `.ods` package whose body is `tables` (`table:table` elements).
fn spreadsheet(tables: &str) -> Result<Vec<u8>, craft_odf::Error> {
let content = format!(
r#"<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"><office:body><office:spreadsheet>{tables}</office:spreadsheet></office:body></office:document-content>"#
);
let mut w = craft_odf::PackageWriter::new(craft_odf::mime::SPREADSHEET);
w.file("content.xml", "text/xml", content.as_bytes());
w.finish()
}
#[test]
fn ods_cells_read_their_typed_values() {
let book = spreadsheet(
r#"<table:table table:name="Guests">
<table:table-row><table:table-cell office:value-type="string"><text:p>Name</text:p></table:table-cell><table:table-cell table:number-columns-repeated="2"/><table:table-cell office:value-type="string"><text:p>When</text:p></table:table-cell><table:table-cell office:value-type="string" table:number-columns-repeated="2"><text:p>Tag</text:p></table:table-cell></table:table-row>
<table:table-row table:number-rows-repeated="2"><table:table-cell office:value-type="string" table:number-columns-spanned="2"><text:p>Ada<text:s text:c="2"/>L</text:p><text:p>x</text:p><office:annotation><text:p>note</text:p></office:annotation></table:table-cell><table:covered-table-cell office:value-type="string"><text:p>hidden</text:p></table:covered-table-cell><table:table-cell office:value-type="float" office:value="3.50"><text:p>3,5</text:p></table:table-cell><table:table-cell office:value-type="date" office:date-value="2024-03-05T00:00:00"><text:p>05/03/24</text:p></table:table-cell><table:table-cell office:value-type="boolean" office:boolean-value="false"><text:p>NO</text:p></table:table-cell><table:table-cell office:value-type="time" office:time-value="PT13H45M00S"><text:p>01:45 PM</text:p></table:table-cell></table:table-row>
<table:table-row><table:table-cell office:value-type="date" office:date-value="2024-03-05T13:45:30"><text:p>Tue</text:p></table:table-cell><table:table-cell office:value-type="date" office:date-value="not a date"><text:p>someday</text:p></table:table-cell><table:table-cell office:value-type="percentage" office:value="0.25"><text:p>25%</text:p></table:table-cell><table:table-cell office:value-type="currency" office:value="9"/></table:table-row>
</table:table>"#,
)
.unwrap();
let (_, rows) = read_rows(&book, Pick::Name("Guests")).unwrap();
assert_eq!(rows.len(), 4);
assert_eq!(rows[0], ["Name", "", "", "When", "Tag", "Tag"]);
assert_eq!(rows[1], ["Ada L\nx", "", "3.5", "2024-03-05", "FALSE", "13:45"]);
assert_eq!(rows[1], rows[2]);
assert_eq!(rows[3], ["2024-03-05 13:45:30", "someday", "25%", "9"]);
}
#[test]
fn an_ods_date_with_two_zones_reads_its_text() {
let book = spreadsheet(
r#"<table:table table:name="Dates">
<table:table-row><table:table-cell office:value-type="date" office:date-value="2024-03-05T13:45:00+02:00Z"><text:p>offset then Z</text:p></table:table-cell><table:table-cell office:value-type="date" office:date-value="2024-03-05T13:45:00Z+02:00"><text:p>Z then offset</text:p></table:table-cell><table:table-cell office:value-type="date" office:date-value="2024-03-05T13:45:00+02:00"><text:p>one zone</text:p></table:table-cell></table:table-row>
</table:table>"#,
)
.unwrap();
let (_, rows) = read_rows(&book, Pick::Name("Dates")).unwrap();
assert_eq!(rows, [["offset then Z", "Z then offset", "2024-03-05 13:45"]]);
}
#[test]
fn ods_dates_and_durations() {
assert_eq!(iso_time("PT1H59M59.6S").as_deref(), Some("01:59:59.6"));
assert_eq!(iso_time("PT0.25S").as_deref(), Some("00:00:00.25"));
assert_eq!(iso_time("PT59M60.50S").as_deref(), Some("01:00:00.5"));
assert_eq!(iso_time("PT0H0M59S").as_deref(), Some("00:00:59"));
assert_eq!(iso_time("PT1H2M3S").as_deref(), Some("01:02:03"));
assert_eq!(iso_time("PT1.S"), None);
assert_eq!(iso_time("P1000000000000000000D"), None);
}
#[test]
fn a_clock_time_keeps_its_seconds_fraction_as_written() {
assert_eq!(iso_datetime("2024-03-05T00:00:00.0000000001").as_deref(), Some("2024-03-05 00:00:00.0000000001"));
assert_eq!(iso_datetime("2024-03-05T13:45:30.1234567891Z").as_deref(), Some("2024-03-05 13:45:30.1234567891"));
assert_eq!(iso_datetime("2024-03-05T13:45:30.500+02:00").as_deref(), Some("2024-03-05 13:45:30.5"));
assert_eq!(iso_datetime("2024-03-05T00:00:00.000").as_deref(), Some("2024-03-05"));
assert_eq!(iso_time("13:45:00.1234567891").as_deref(), Some("13:45:00.1234567891"));
assert_eq!(iso_time("PT13H45M0.1234567891S").as_deref(), Some("13:45:00.1234567891"));
assert_eq!(iso_time("13:45:00."), None);
assert_eq!(iso_time("13:45:00.5x"), None);
assert_eq!(iso_time("13:45.5"), None);
assert_eq!(iso_time("23:59:60.5"), None);
assert_eq!(iso_time("13: 45.5"), None);
assert_eq!(iso_time("1:45:30.5").as_deref(), Some("01:45:30.5"));
}
#[test]
fn a_typed_ods_value_keeps_to_the_cell_limit() {
let long = format!("2024-03-05T13:45:30.{}", "1".repeat(MAX_CELL_CHARS));
let book = spreadsheet(&format!(
r#"<table:table table:name="Long"><table:table-row><table:table-cell office:value-type="date" office:date-value="{long}"><text:p>x</text:p></table:table-cell></table:table-row></table:table>"#
))
.unwrap();
let (_, rows) = read_rows(&book, Pick::Name("Long")).unwrap();
assert_eq!(rows[0][0].chars().count(), MAX_CELL_CHARS);
}
#[test]
fn a_date_alone_drops_its_zone() {
assert_eq!(iso_datetime("2024-03-05Z").as_deref(), Some("2024-03-05"));
assert_eq!(iso_datetime("2024-03-05+02:00").as_deref(), Some("2024-03-05"));
assert_eq!(iso_datetime("2024-03-05-05:00").as_deref(), Some("2024-03-05"));
assert_eq!(iso_datetime("2024-03-05+02:99"), None);
}
#[test]
fn a_zone_is_at_most_fourteen_hours() {
assert_eq!(iso_datetime("2024-03-05+14:00").as_deref(), Some("2024-03-05"));
assert_eq!(iso_datetime("2024-03-05-14:00").as_deref(), Some("2024-03-05"));
assert_eq!(iso_datetime("2024-03-05+14:01"), None);
assert_eq!(iso_datetime("2024-03-05-15:00"), None);
assert_eq!(iso_datetime("2024-03-05T13:45:00+14:00").as_deref(), Some("2024-03-05 13:45"));
assert_eq!(iso_datetime("2024-03-05T13:45:00+14:01"), None);
assert_eq!(iso_time("13:45:00-15:00"), None);
}
#[test]
fn a_zone_is_z_or_an_offset_not_both() {
assert_eq!(iso_datetime("2024-03-05T13:45:00+02:00Z"), None);
assert_eq!(iso_datetime("2024-03-05T13:45:00Z+02:00"), None);
assert_eq!(iso_datetime("2024-03-05+02:00Z"), None);
assert_eq!(iso_datetime("2024-03-05Z+02:00"), None);
assert_eq!(iso_time("13:45:00+02:00Z"), None);
assert_eq!(iso_time("13:45:00Z+02:00"), None);
assert_eq!(iso_datetime("2024-03-05T13:45:00Z").as_deref(), Some("2024-03-05 13:45"));
assert_eq!(iso_datetime("2024-03-05T13:45:00-05:00").as_deref(), Some("2024-03-05 13:45"));
assert_eq!(iso_time("13:45:00+02:00").as_deref(), Some("13:45"));
}
#[test]
fn a_zone_offset_has_two_digit_hours_and_minutes() {
assert_eq!(iso_datetime("2024-03-05T13:45:00+2:00"), None);
assert_eq!(iso_datetime("2024-03-05T13:45:00+ 2:00"), None);
assert_eq!(iso_time("13:45:00-5:00"), None);
}
#[test]
fn a_leap_second_is_not_a_time() {
assert_eq!(iso_datetime("2024-03-05T23:59:60Z"), None);
assert_eq!(iso_time("23:59:60"), None);
}
#[test]
fn a_duration_with_t_needs_a_time() {
assert_eq!(iso_time("P1DT"), None);
assert_eq!(iso_time("P0DT"), None);
assert_eq!(iso_time("P1D").as_deref(), Some("24:00"));
assert_eq!(iso_time("PT.S"), None);
assert_eq!(iso_time("13:45:00Z").as_deref(), Some("13:45"));
assert_eq!(iso_time("-PT1H").as_deref(), Some("-01:00"));
assert_eq!(iso_time("P2DT1H30M").as_deref(), Some("49:30"));
assert_eq!(iso_time("P1D").as_deref(), Some("24:00"));
assert_eq!(iso_time("P1Y2M"), None);
assert_eq!(iso_time("PT"), None);
assert_eq!(iso_time("PT5"), None);
assert_eq!(iso_time("PT1H2H"), None);
assert_eq!(iso_time("PT1S2H"), None);
assert_eq!(iso_datetime("2024-03-05T"), None);
assert_eq!(iso_datetime("2024-03-05T00:00:00.500").as_deref(), Some("2024-03-05 00:00:00.5"));
assert_eq!(iso_time("00:00:00.250").as_deref(), Some("00:00:00.25"));
assert_eq!(iso_time("25:00"), None);
assert_eq!(iso_datetime("2024-03-05T00:00:00.000").as_deref(), Some("2024-03-05"));
assert_eq!(iso_datetime("2024-03-05T13:45:30+02:00").as_deref(), Some("2024-03-05 13:45:30"));
assert_eq!(iso_datetime("2024-13-05"), None);
assert_eq!(iso_datetime("2023-02-29"), None);
assert_eq!(iso_datetime("2024-03-05junk"), None);
assert_eq!(iso_datetime("2024-03-05T13:99"), None);
}
}
+68
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);
+1 -1
View File
@@ -152,7 +152,7 @@ pub(crate) fn add(ctx: &mut Ctx, lay: &mut DocLayout) {
author_name(&cm.author),
CharProps { bold: Some(true), size: Some(9.0), color: Some(TextColor::Rgb(color)), ..Default::default() },
);
let pl = ctx.para_labelled(&head, inner, None, &[], None);
let pl = ctx.para_labelled(&head, inner, None, &[], 0.0, None);
let lead = pl.lines.first().map_or(0.0, |l| l.top.max(0.0));
push_para(&mut items, (story, &[HEADER_PATH]), &pl, (0, pl.lines.len()), (x, y + lead), inner, Edges::own(&pl, 0, pl.lines.len()));
y += pl.height + 2.0;
+38 -20
View File
@@ -160,8 +160,8 @@ fn layout_table_block(input: TableBlockContext<'_, '_, '_>) -> bool {
let layout = table::layout_table(ctx, story, t, path, width, depth + 1);
let (tx, ty) = match t.props.float {
Some(float) => {
let legacy = (ctx.doc.settings.compat_mode < 15).then(|| table::first_cell_left_margin(ctx, t));
let (rect, area) = box_float_table_rect(frame, width, *y, &layout, &float, legacy, float_tables);
let place = FloatPlace { shift: table::float_offset_shift(ctx, t), modern: ctx.doc.settings.compat_mode >= 15 };
let (rect, area) = box_float_table_rect(frame, width, *y, &layout, &float, place, float_tables);
exclusions.push((area, false, None, WrapText::BothSides, true));
float_tables.push(area);
table_areas.push(area);
@@ -276,17 +276,17 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
Block::Para(p) => {
// A paragraph after one whose mark is hidden goes on from that one's last line
// (Word, #3986; see `Joint`); one that shows nothing passes the place on.
let (mark_hidden, shows_nothing, taken) = Joint::arrive(ctx, &mut joint, (i, p), (width, frames), table);
let (mark_hidden, shows_nothing, taken) = Joint::arrive(ctx, &mut joint, (i, p), (width, frames), table, cell_frame);
let p = taken.as_ref().map_or(p, |t| &t.para);
let label = ctx.next_label(p);
let listed = label.is_some();
let mut pl = ctx.para_labelled(p, width, table, &[], label.clone());
let mut pl = ctx.para_labelled(p, width, table, &[], 0.0, label.clone());
// A text frame (a footer's page number in a frame, say) is placed apart, like a
// floating object, and the text after it wraps around it; it takes no room in
// the flow.
if let Some(fr) = pl.rp.frame.clone().filter(|fr| frames && cell_frame(fr)) {
let fw = fr.w.unwrap_or_else(|| natural_width(&pl)).clamp(1.0, 1584.0);
let pf = if (fw - width).abs() > 0.01 { ctx.para_labelled(p, fw, table, &[], label) } else { pl };
let pf = if (fw - width).abs() > 0.01 { ctx.para_labelled(p, fw, table, &[], 0.0, label) } else { pl };
let h = match fr.h {
Some(h) if fr.h_exact => h,
Some(h) => h.max(pf.height),
@@ -318,7 +318,8 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
// body path. Keep text and wrap exclusions relative to the text's actual top.
// A paragraph going on from a shared line has its origin at that line's top.
let para_top = taken.as_ref().map_or(y, |t| t.joint.top);
y += if i == 0 { before } else { before.max(0.0) };
let applied = if i == 0 { before } else { before.max(0.0) };
y += applied;
TakenUp::start(taken.as_ref(), &mut y, &mut excl);
// Floating objects anchored here: place them, then wrap the text around them.
// One left out of the layout (hidden, or deleted in the final text) takes no room.
@@ -362,9 +363,9 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
}
floats.insert(oi, r);
}
let rel = rel_exclusions(&excl, 0.0, y);
let rel = rel_exclusions(&excl, 0.0, y, applied);
if !rel.is_empty() {
pl = ctx.para_labelled(p, width, table, &rel, label);
pl = ctx.para_labelled(p, width, table, &rel, applied, label);
}
TakenUp::clear(taken.as_ref(), &mut excl);
// Bordered paragraphs: room for their borders, those of a group joined in one box.
@@ -477,7 +478,7 @@ fn natural_width(pl: &ParaLayout) -> f32 {
}
/// A text frame's placement as a floating object's (`w:framePr` → anchors, alignment, wrap).
fn frame_float(fr: &wordcraft_doc::props::TextFrame) -> Float {
pub(crate) fn frame_float(fr: &wordcraft_doc::props::TextFrame) -> Float {
let anchor = |a: &str, text: Anchor| match a {
"page" => Anchor::Page,
"margin" => Anchor::Margin,
@@ -524,17 +525,25 @@ pub(crate) struct BoxLayout {
pub(crate) last_top: f32,
}
/// How a floating table placed by an offset stands from it.
#[derive(Clone, Copy)]
struct FloatPlace {
/// How far left of the offset its edge stands ([`table::float_offset_shift`]).
shift: f32,
/// Word 2013 layout (compatibility mode 15).
modern: bool,
}
/// Where floating table `tl` goes in a box `width` wide whose next paragraph starts at `y`, and
/// the area text keeps clear of. Positions relative to the page or its margins need the box's
/// `frame`; without one (a table cell) they're relative to the box. `legacy` is the first cell's
/// left margin before Word 2013 layout, `None` in it.
/// `frame`; without one (a table cell) they're relative to the box.
fn box_float_table_rect(
frame: Option<PageFrame>,
width: f32,
y: f32,
tl: &table::TableLayout,
f: &TableFloat,
legacy: Option<f32>,
place: FloatPlace,
float_tables: &[Rect],
) -> (Rect, Rect) {
let h = tl.rows.iter().map(|r| r.height).sum::<f32>().clamp(0.0, 100_000.0);
@@ -570,8 +579,8 @@ fn box_float_table_rect(
};
// Nor is there an area to align in: the table starts where the text is.
let v_align = if frame.is_none() && matches!(f.v_rel, Anchor::Page | Anchor::Margin) { None } else { f.v_align };
let x = align_in(h_area, f.x, w, PageFrame::h_align(frame.as_ref(), f.h_align)) - if f.h_align.is_none() { legacy.unwrap_or(0.0) } else { 0.0 };
let r = clear_of_float_tables(Rect::new(x, align_in(v_area, y_off, h, v_align), w, h), f, legacy.is_none(), h_area.0, float_tables);
let x = align_in(h_area, f.x, w, PageFrame::h_align(frame.as_ref(), f.h_align)) - if f.h_align.is_none() { place.shift } else { 0.0 };
let r = clear_of_float_tables(Rect::new(x, align_in(v_area, y_off, h, v_align), w, h), f, place.modern, h_area.0 - place.shift, float_tables);
let [dl, dt, dr, db] = f.dist_from_text();
(r, r.inset(-dl, -dt, -dr, -db))
}
@@ -777,13 +786,14 @@ impl Joint {
(i, p): (usize, &Paragraph),
(width, frames): (f32, bool),
table: Option<&para::CellText>,
cell_frame: impl Fn(&wordcraft_doc::props::TextFrame) -> bool,
) -> (bool, bool, Option<TakenUp>) {
let chr = table.map(|t| &t.chr);
let mark_hidden = ctx.mark_hidden(p, chr);
let shows_nothing = mark_hidden && ctx.text_hidden(p, chr);
let came = joint.take().filter(|j| j.next == i);
*joint = came.filter(|_| shows_nothing).map(|j| Joint { next: i + 1, ..j });
let taken = came.filter(|_| !shows_nothing).and_then(|j| j.take_up(ctx, p, (width, frames), table));
let taken = came.filter(|_| !shows_nothing).and_then(|j| j.take_up(ctx, p, (width, frames), table, cell_frame));
(mark_hidden, shows_nothing, taken)
}
@@ -799,7 +809,7 @@ impl Joint {
/// taller than the text going on from it), with the room for its bottom border (Word).
pub(crate) fn fit(&self, ctx: &mut Ctx, q: &Paragraph, width: f32, table: Option<&para::CellText>) -> (f32, Vec<WrapArea>) {
let eq = ctx.eq_count;
let probe = again(ctx, eq, |ctx| ctx.para_labelled(q, width, table, &[], None));
let probe = again(ctx, eq, |ctx| ctx.para_labelled(q, width, table, &[], 0.0, None));
let (gap, height) = probe.lines.first().map_or((0.0, self.height), |l| ((self.baseline - (l.baseline - l.top)).max(0.0), l.height));
let rect = Rect::new(self.left, self.top, (self.end - self.left).max(0.0), (gap + height - 0.01).max(0.01));
let mut areas = vec![(rect, false, None, WrapText::Right, false)];
@@ -825,11 +835,19 @@ 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.
fn take_up(self, ctx: &mut Ctx, p: &Paragraph, (width, frames): (f32, bool), table: Option<&para::CellText>) -> Option<TakenUp> {
/// 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,
p: &Paragraph,
(width, frames): (f32, bool),
table: Option<&para::CellText>,
cell_frame: impl Fn(&wordcraft_doc::props::TextFrame) -> bool,
) -> Option<TakenUp> {
let own = ctx.doc.styles.resolve_para_in(&p.props, table.map(|t| &t.para));
if own.page_break_before || own.bidi || (frames && own.frame.is_some()) {
if own.page_break_before || own.bidi || own.frame.as_ref().is_some_and(|fr| frames && cell_frame(fr)) {
return None;
}
let mut para = p.clone();
+9
View File
@@ -16,6 +16,9 @@ pub(crate) struct Key {
pub(crate) table: u64,
pub(crate) notes: u64,
pub(crate) excl: u64,
/// The space before the paragraph layout applied above it, which a Top-and-Bottom object in
/// it is laid out again below ([`para::ParaEnv::space_before`]).
pub(crate) space_before: u32,
pub(crate) eq: u32,
pub(crate) read_spacing: Option<u32>,
pub(crate) grid: (u32, u32, u32, bool),
@@ -149,6 +152,12 @@ 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);
// 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);
opts.hide_deleted.hash(&mut h);
opts.hide_marked.hash(&mut h);
+23 -5
View File
@@ -113,12 +113,21 @@ struct ParaEnvInput<'a> {
label: Option<(String, Level)>,
table: Option<&'a para::CellText>,
exclusions: &'a [para::Exclusion],
space_before: f32,
eq_number: u32,
typing_word: Option<(usize, usize)>,
fitted: &'a [(usize, f32)],
joined: bool,
}
/// The flow's wrap context for a paragraph's layout, as its cache key needs it: the areas text
/// flows around (relative to its first line) and the space before it the flow laid out, which
/// reaches up to them (see [`para::ParaEnv::space_before`]).
struct WrapAreas<'a> {
exclusions: &'a [para::Exclusion],
space_before: f32,
}
/// A header or footer (`story`) laid out for page `number` of a section (`sect`, `mirror`): its
/// table cells' floats placed on the page rather than in their cell ([`Float::outside_cell`],
/// Word's picture watermark in a header that starts with a table), drawn behind the header's
@@ -252,6 +261,7 @@ impl Ctx<'_> {
typing_word: None,
numeral: self.opts.numeral,
exclusions: &[],
space_before: 0.0,
eq_number: 0,
read_line_spacing: None,
grid: para::Grid::default(),
@@ -299,16 +309,18 @@ impl Ctx<'_> {
/// Lay out `p` with its already counted `label`, so laying a paragraph out again (around
/// floating objects, or after it moved) doesn't advance the list counters twice.
/// `space_before` is the space before `p` that the flow laid out above it ([`para::ParaEnv`]).
pub(crate) fn para_labelled(
&mut self,
p: &Paragraph,
width: f32,
table: Option<&para::CellText>,
exclusions: &[para::Exclusion],
space_before: f32,
label: Option<(String, Level)>,
) -> Arc<ParaLayout> {
let fitted = self.fitted_boxes(p);
let (key, eq_number) = self.para_key(p, width, table, exclusions, label.as_ref(), &fitted);
let (key, eq_number) = self.para_key(p, width, table, WrapAreas { exclusions, space_before }, label.as_ref(), &fitted);
self.cache.used.insert(key.clone());
if let Some(pl) = self.cache.paras.get(&key) {
self.cache.hits += 1;
@@ -323,6 +335,7 @@ impl Ctx<'_> {
label,
table,
exclusions,
space_before,
eq_number,
typing_word: typing,
fitted: &fitted,
@@ -347,7 +360,7 @@ impl Ctx<'_> {
return None;
}
let kept = (self.eq_count, self.uses_totals);
let (key, eq_number) = self.para_key(p, width, None, &[], label.as_ref(), &[]);
let (key, eq_number) = self.para_key(p, width, None, WrapAreas { exclusions: &[], space_before: 0.0 }, label.as_ref(), &[]);
(self.eq_count, self.uses_totals) = kept;
if key.typing.is_some() {
return None;
@@ -365,6 +378,7 @@ impl Ctx<'_> {
label,
table: None,
exclusions: &[],
space_before: 0.0,
eq_number,
typing_word: None,
fitted: &[],
@@ -387,7 +401,7 @@ impl Ctx<'_> {
measure: impl FnOnce(&ParaLayout) -> (f32, f32),
) -> (f32, f32) {
let fitted = self.fitted_boxes(p);
let (key, eq_number) = self.para_key(p, width, table, &[], label.as_ref(), &fitted);
let (key, eq_number) = self.para_key(p, width, table, WrapAreas { exclusions: &[], space_before: 0.0 }, label.as_ref(), &fitted);
self.cache.used.insert(key.clone());
if let Some(m) = self.cache.measures.get(&key) {
self.cache.hits += 1;
@@ -402,6 +416,7 @@ impl Ctx<'_> {
label,
table,
exclusions: &[],
space_before: 0.0,
eq_number,
typing_word: typing,
fitted: &fitted,
@@ -455,10 +470,11 @@ impl Ctx<'_> {
p: &Paragraph,
width: f32,
table: Option<&para::CellText>,
exclusions: &[para::Exclusion],
wrap: WrapAreas<'_>,
label: Option<&(String, Level)>,
fitted: &[(usize, f32)],
) -> (Key, u32) {
let WrapAreas { exclusions, space_before } = wrap;
let page = if has_page_fields(p) { Some(self.fields.page_key()) } else { None };
if self.track_totals && !self.uses_totals && has_total_fields(p) {
self.uses_totals = true;
@@ -483,6 +499,7 @@ impl Ctx<'_> {
table: table.map(|t| self.table_key(t)).unwrap_or(0),
notes: if p.objects.iter().any(|o| matches!(o, InlineObject::NoteRef { .. })) { self.notes_hash } else { 0 },
excl: if exclusions.is_empty() { 0 } else { hash_of(&format!("{exclusions:?}")) },
space_before: space_before.to_bits(),
eq: if eq_here > 0 { eq_number } else { 0 },
read_spacing: if self.opts.view == ViewMode::Read { self.opts.read_line_spacing.map(f32::to_bits) } else { None },
grid: self.grid.key(),
@@ -512,7 +529,7 @@ impl Ctx<'_> {
}
fn para_env<'b>(&'b self, input: ParaEnvInput<'b>) -> para::ParaEnv<'b> {
let ParaEnvInput { width, label, table, exclusions, eq_number, typing_word, fitted, joined } = input;
let ParaEnvInput { width, label, table, exclusions, space_before, eq_number, typing_word, fitted, joined } = input;
para::ParaEnv {
doc: self.doc,
width,
@@ -526,6 +543,7 @@ impl Ctx<'_> {
typing_word,
numeral: self.opts.numeral,
exclusions,
space_before,
eq_number,
read_line_spacing: if self.opts.view == ViewMode::Read { self.opts.read_line_spacing } else { None },
grid: self.grid,
+54 -9
View File
@@ -219,8 +219,10 @@ pub(crate) fn wrap_area(r: Rect, float: &Float, outline: Option<&[(f32, f32)]>)
Some((Rect::new(r.x - side, r.y - top, r.w + side * 2.0, r.h + top + bottom), float.wrap == Wrap::TopAndBottom, None, float.wrap_text, false))
}
/// Wrap areas relative to a paragraph whose column starts at `x0` and whose top is `y0`.
pub(crate) fn rel_exclusions(excl: &[WrapArea], x0: f32, y0: f32) -> Vec<para::Exclusion> {
/// Wrap areas relative to a paragraph whose column starts at `x0` and whose top is `y0`, with
/// `space_before` the space before it that the flow laid out above it.
pub(crate) fn rel_exclusions(excl: &[WrapArea], x0: f32, y0: f32, space_before: f32) -> Vec<para::Exclusion> {
let before = if space_before > 0.0 { space_before } else { 0.0 };
excl.iter()
.map(|(r, tb, c, side, table)| para::Exclusion {
top: r.y - y0,
@@ -232,7 +234,11 @@ pub(crate) fn rel_exclusions(excl: &[WrapArea], x0: f32, y0: f32) -> Vec<para::E
side: *side,
table: *table,
})
.filter(|e| e.bottom > 0.0)
// Top-and-Bottom areas ending within the paragraph's applied space before can still take
// room, with that space laid out again below them (#7143). Any ending at or above it
// (like side-wrapping areas above the first line) cannot reach the paragraph and is
// dropped so paragraphs below keep empty exclusions and hit the cache (#8613).
.filter(|e| e.bottom > 0.0 || (e.top_bottom && e.bottom > -before))
.collect()
}
@@ -477,6 +483,7 @@ fn anchor_floats_but(
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));
@@ -513,20 +520,58 @@ fn anchor_floats_but(
// 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(&r) = rects.get(&oi) else { continue };
if float.y < 0.0 && area.map_or(r.bottom(), |(_, b)| b) < y0 + lead - 0.5 {
// Only down: across it stays where it was placed (`settle_early` may have moved it).
let moved = Rect { y: float_rect(Some(frame), (col_x, width), top + lead, r.w, r.h, float).y, ..r };
// 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;
}
rects.insert(oi, moved);
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, label.clone());
(rects, pl, rel)
}
@@ -861,7 +906,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 });
+81 -20
View File
@@ -1,9 +1,9 @@
use super::boxes::{BoxInput, BoxLayout, Edges, Joint, joined, layout_box, push_para};
use super::boxes::{BoxInput, BoxLayout, Edges, Joint, frame_float, joined, layout_box, push_para};
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, late_floats, place_late,
place_objects,
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};
@@ -19,6 +19,9 @@ use crate::WRAP_RELAYS;
/// A body paragraph. One after a paragraph whose mark is hidden goes on from that one's last line,
/// as Word shows them, on one line (#3986): see [`Joint`].
pub(crate) fn place_para(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block: usize, body_top: f32) {
if place_page_text_frame(ctx, pb, p, block) {
return;
}
let joint = pb.joint.take().filter(|j| !pb.web && j.next == block && j.page == pb.pages.len() && j.col == pb.col);
let mark_hidden = ctx.mark_hidden(p, None);
// Nothing of it is shown: the place passes on to the paragraph after it.
@@ -96,6 +99,39 @@ fn unjoin(ctx: &mut Ctx, p: &Paragraph) {
}
}
fn place_page_text_frame(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block: usize) -> bool {
if pb.web {
return false;
}
let Some(fr) = ctx.doc.styles.resolve_para_in(&p.props, None).frame else { return false };
if fr.h_anchor != "page" || fr.v_anchor != "page" {
return false;
}
let width = fr.w.unwrap_or_else(|| pb.col_w()).clamp(1.0, 1584.0);
let label = ctx.next_label(p);
let pl = ctx.para_labelled(p, width, None, &[], 0.0, label);
let notes = para_notes(ctx.doc, p, &pl);
let mut new_notes = Vec::new();
for line in &pl.lines {
new_notes.extend(notes_on_line(ctx, pb, line, &notes, &new_notes));
}
add_notes(pb, new_notes, &notes, pl.lines.last().map_or(0, |line| line.c1));
let height = fr.h.map_or(pl.height, |h| if fr.h_exact { h } else { h.max(pl.height) });
let float = frame_float(&fr);
let page = PageFrame { sect: pb.sect, margin_top: None, origin: (0.0, 0.0), number: pb.number, mirror: ctx.mirror };
let rect = float_rect(Some(page), (pb.col_x(), pb.col_w()), pb.y, width, height, &float);
let path = [block as u32];
if let Some(page) = pb.page() {
push_para(&mut page.items, (StoryRef::Body, &path), &pl, (0, pl.lines.len()), (rect.x, rect.y), width, Edges::own(&pl, 0, pl.lines.len()));
}
// The body text after the frame wraps around it as its wrap mode says.
if let Some(area) = wrap_area(rect, &float, None) {
pb.framed.push(area.0);
pb.excl.push(area);
}
true
}
/// A closing mark before a continuous section takes no room after content. An otherwise empty
/// section starting a new page retains its paragraph line.
fn place_para_alone(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block: usize, body_top: f32) {
@@ -236,6 +272,10 @@ struct Flow<'a> {
label: Option<(String, Level)>,
/// Where it was expected to start; floats anchored here are placed again if it starts elsewhere.
guess: f32,
/// The space before it that its layout (`pl`) was broken with: the declared space before
/// until the flow settles what it really lays out, then that, so a later relay keeps a
/// Top-and-Bottom object in it pushing the first line to the same place.
space_applied: f32,
excl_mark: usize,
/// Where its automatic equation numbers start: each layout of it again counts from here.
eq_start: u32,
@@ -269,6 +309,21 @@ struct Flow<'a> {
}
impl<'a> Flow<'a> {
/// [`PageBuilder::fresh`] for this paragraph's text, which its negative indents take past the
/// column's edges: the first line's indent while it is still to place, the other lines'
/// indent while lines after the first are, on the physical sides the paragraph's direction
/// puts them.
fn fresh(&self, pb: &PageBuilder) -> bool {
let rp = &self.pl.rp;
let first = rp.indent_left + rp.indent_first;
let leading = match (self.l0 == 0, self.pl.lines.len() > 1) {
(true, true) => rp.indent_left.min(first),
(true, false) => first,
(false, _) => rp.indent_left,
};
let (leading, trailing) = ((-leading).max(0.0), (-rp.indent_right).max(0.0));
pb.fresh(if rp.bidi { (trailing, leading) } else { (leading, trailing) })
}
fn new(ctx: &mut Ctx, pb: &mut PageBuilder, p: &'a Paragraph, (block, body_top): (usize, f32)) -> Self {
let width = pb.col_w();
// Floating objects anchored here join the page's wrap areas before the text is laid out; if
@@ -288,6 +343,7 @@ impl<'a> Flow<'a> {
width,
label,
guess,
space_applied: space_before,
excl_mark,
eq_start,
float_rects,
@@ -324,13 +380,14 @@ impl<'a> Flow<'a> {
});
(self.float_rects, self.pl, self.rel) = (rects, pl, rel);
self.late = LateFloats::new(&late);
self.space_applied = before;
(self.laid_page, self.laid_width) = (pb.number, pb.col_w());
}
/// Lay the paragraph out again around the wrap areas `rel`, with its fields on their pages.
fn relay(&mut self, ctx: &mut Ctx, rel: &[para::Exclusion]) -> Arc<ParaLayout> {
let (p, width, eq_start, label) = (self.p, self.laid_width, self.eq_start, &self.label);
with_page_map(ctx, &mut self.page_map, |ctx| again(ctx, eq_start, |ctx| ctx.para_labelled(p, width, None, rel, label.clone())))
let (p, width, eq_start, label, space_before) = (self.p, self.laid_width, self.eq_start, &self.label, self.space_applied);
with_page_map(ctx, &mut self.page_map, |ctx| again(ctx, eq_start, |ctx| ctx.para_labelled(p, width, None, rel, space_before, label.clone())))
}
/// The space before the paragraph, after the one between it and the previous paragraph is
@@ -367,7 +424,7 @@ impl<'a> Flow<'a> {
// space before (Word's PDFs: 0 pt and 12 pt before put the text after it at the same place).
// Only that shape is observed: later pages and columns keep theirs.
if self.block == 1
&& pb.fresh()
&& self.fresh(pb)
&& !pb.web
&& pb.pages.last().is_some_and(|pg| pg.float_tables.contains(&Path::top(0)))
&& only_markers(self.p, 0..self.p.text.len())
@@ -444,7 +501,7 @@ impl<'a> Flow<'a> {
// (Against the whole column: balanced columns grow to hold it.)
// With the 0.01 pt of slack the other fit checks take. Balancing from Word 2013's layout
// keeps the lines and the next paragraph together at the top of a column too (#6821).
if pb.y + need > pb.bottom + 0.01 && (!pb.fresh() || Self::strict_widow_control(ctx, pb)) && need <= pb.next_room(self.body_top) {
if pb.y + need > pb.bottom + 0.01 && (!self.fresh(pb) || Self::strict_widow_control(ctx, pb)) && need <= pb.next_room(self.body_top) {
pb.advance(self.block, self.body_top);
unjoin(ctx, self.p);
pb.y += rp.space_before.min(0.0);
@@ -458,7 +515,7 @@ impl<'a> Flow<'a> {
/// paragraph, together there too: asks again, and places the paragraph's floats again where it
/// ends up (#6821).
fn keep_again(&mut self, ctx: &mut Ctx, pb: &mut PageBuilder, rooms: Rooms) {
while self.l0 == 0 && (self.pl.rp.keep_lines || self.pl.rp.keep_next) && pb.fresh() && Self::strict_widow_control(ctx, pb) {
while self.l0 == 0 && (self.pl.rp.keep_lines || self.pl.rp.keep_next) && self.fresh(pb) && Self::strict_widow_control(ctx, pb) {
let (col, pages) = (pb.col, pb.pages.len());
let before = self.keep_together(ctx, pb, rooms, 0.0);
if (pb.col, pb.pages.len()) == (col, pages) {
@@ -550,7 +607,7 @@ impl<'a> Flow<'a> {
if over && fit.l1 > l0 && !split {
break;
}
if over && fit.l1 == l0 && !pb.fresh() && !split && !self.stays_at_bottom(pb, l) {
if over && fit.l1 == l0 && !self.fresh(pb) && !split && !self.stays_at_bottom(pb, l) {
break;
}
fit.notes.extend(line_notes);
@@ -608,11 +665,11 @@ impl<'a> Flow<'a> {
// one (#6821).
let strict = Self::strict_widow_control(ctx, pb);
if fit.forced.is_none() && l1 < n && self.pl.rp.widow_control && n >= 2 {
if l1 - l0 == 1 && l0 == 0 && (!pb.fresh() || strict) {
if l1 - l0 == 1 && l0 == 0 && (!self.fresh(pb) || strict) {
l1 = l0; // orphan: move the first line to the next page
} else if n - l1 == 1 && (l1 - l0 >= 3 || (l0 > 0 && l1 - l0 >= 2)) {
l1 -= 1; // widow: take one more line along
} else if n - l1 == 1 && l0 == 0 && l1 - l0 == 2 && (!pb.fresh() || strict) {
} else if n - l1 == 1 && l0 == 0 && l1 - l0 == 2 && (!self.fresh(pb) || strict) {
// Neither split of a three-line paragraph is allowed (two and a widow, or an
// orphan and two): it moves whole, as in Word.
l1 = l0;
@@ -776,6 +833,7 @@ impl<'a> Flow<'a> {
(self.float_rects, self.pl, self.rel) = (rects, relaid, relaid_rel);
(self.laid_page, self.laid_width) = (pb.number, pb.col_w());
self.anchor_y = y0;
self.space_applied = 0.0;
self.l0 = k;
}
}
@@ -890,10 +948,10 @@ fn notes_limit(pb: &PageBuilder, new_notes: &[NoteBox], line_notes: &[NoteBox])
/// the text (see `baseline_offset`), and Word lets that leading of a page's last line run into the
/// bottom margin: only the text has to fit (observed: a double-spaced 12pt line stays on the page
/// while its text ends above the margin, about half a line lower than when the whole line must
/// fit). Only the bottom margin takes that leading: a footer taller than the margin, or
/// footnotes (`free` is false), keep the whole line clear of them.
/// fit). Only the bottom margin takes that leading, or the top of a footer that reaches above it
/// (see [`PageBuilder::at_margin`]): footnotes (`free` is false) keep the whole line clear of them.
fn fit_height(pb: &PageBuilder, l: &para::Line, rp: &wordcraft_doc::resolve::ResolvedPara, free: bool) -> f32 {
let at_margin = pb.bottom >= pb.sect.page_h - pb.sect.margin_bottom - 0.01;
let at_margin = pb.at_margin();
match rp.line_spacing {
// The text (or a taller picture) ends `leading` above the line's bottom.
wordcraft_doc::props::LineSpacing::Multiple(m) if m > 1.0 && at_margin && free => (l.height - l.leading).clamp(0.0, l.height),
@@ -989,8 +1047,10 @@ fn place_para_in_flow(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block:
let mut f = Flow::new(ctx, pb, p, (block, body_top));
let spot = |pb: &PageBuilder| (pb.pages.len(), pb.col);
let placed_at = spot(pb);
// A continuous section's top mid-page is not a page top, so the break still applies.
let broke_before = f.pl.rp.page_break_before && !pb.fresh() && !pb.web;
// A continuous section's top mid-page is not a page top, so the break still applies. A
// page-anchored frame is not content above the paragraph, so it does not make the break
// apply either: the frame's wrap area moves the text below or beside it (#8577).
let broke_before = f.pl.rp.page_break_before && !pb.at_page_top() && !pb.web;
if broke_before {
pb.new_page(block, body_top);
}
@@ -1023,7 +1083,7 @@ fn place_para_in_flow(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block:
fit.l1 = end;
// On a fresh column an unfitting line can overflow. Strict widow control instead moves
// the lines on without emitting anything and must release their late floats as well.
let overflow = end == f.l0 && pb.fresh() && !widowed;
let overflow = end == f.l0 && f.fresh(pb) && !widowed;
if f.settle_late(pb, end, overflow) {
continue;
}
@@ -1085,7 +1145,7 @@ pub(crate) fn place_outline_para(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragr
let width = (pb.col_w() - indent - outline::SYMBOL_W).max(72.0);
let q = outline::outline_para(ctx.doc, p, o.view.plain);
ctx.fields.page = pb.number;
let pl = ctx.para_labelled(&q, width, None, &[], label);
let pl = ctx.para_labelled(&q, width, None, &[], 0.0, label);
pb.y += pl.rp.space_before.max(0.0);
let n = pl.lines.len();
let l1 = if o.view.first_line_only && level >= outline::BODY { n.min(1) } else { n };
@@ -1197,6 +1257,7 @@ fn next_first_line(ctx: &mut Ctx, block: usize, width: f32, depth: usize, new_pa
typing_word: None,
numeral: ctx.opts.numeral,
exclusions: &[],
space_before: 0.0,
eq_number: ctx.eq_count,
read_line_spacing: if ctx.opts.view == ViewMode::Read { ctx.opts.read_line_spacing } else { None },
grid: ctx.grid,
@@ -1311,7 +1372,7 @@ mod tests {
// Continue after the first line. The balance attempt can fit only one of the two lines left.
flow.l0 = 1;
pb.advance(0, top);
assert!(pb.fresh());
assert!(flow.fresh(pb));
assert!((pb.bottom - pb.top - height).abs() < 0.01);
flow.place_due_late(ctx, pb);
assert_eq!(pb.excl.len(), 1, "the anchor line fits before widow control");
@@ -1320,7 +1381,7 @@ mod tests {
assert_eq!(fit.l1, 2);
let (end, widowed) = flow.settled_end(ctx, pb, &fit);
assert_eq!((end, widowed), (1, true));
let overflow = end == flow.l0 && pb.fresh() && !widowed;
let overflow = end == flow.l0 && flow.fresh(pb) && !widowed;
assert!(!flow.settle_late(pb, end, overflow));
assert!(pb.excl.is_empty(), "no text is emitted here, so no wrap area may remain here");
});
+27 -9
View File
@@ -36,6 +36,28 @@ pub(crate) fn section_side(start: SectionStart, restart: Option<u32>, last: u32,
}
}
/// Whether `page` (after `prev`) is its section's first page, the one a different first page's
/// header and footer go on: the page where the section begins. A page's section is the one at its
/// top, so a section that starts continuously part-way down `prev` has no first page of its own:
/// Word shows the earlier section's header there and the section's default one from the next page
/// on; the case where its first paragraph begins on `prev` and runs over is treated the same way
/// (inferred, not measured separately in Word). `sections` as [`Document::sections`] gives them
/// (each with its last block).
pub(crate) fn begins_section(sections: &[(usize, &SectionProps)], prev: Option<&Page>, page: &Page) -> bool {
if prev.is_some_and(|p| p.section == page.section) {
return false;
}
let start = page.section.checked_sub(1).and_then(|k| sections.get(k)).map_or(0, |(end, _)| end.saturating_add(1));
// A first paragraph (or table) that begins part-way down `prev` and runs over still began
// the section there.
let began_before = prev.is_some_and(|p| {
p.items
.iter()
.any(|it| matches!(it, Placed::Lines { story: StoryRef::Body, path, .. } if path.0.first().is_some_and(|&b| b as usize >= start)))
});
start >= page.first_block && !began_before
}
/// The document's sections with their headers and footers (Word's "link to previous"), each
/// section's resolved once for the whole layout in document order rather than by looking back
/// over the sections before it whenever one is needed.
@@ -174,12 +196,12 @@ pub(crate) fn header_table_areas(ctx: &mut Ctx, pb: &PageBuilder) -> Vec<Rect> {
return Vec::new();
}
let Some(page) = pb.pages.last() else { return Vec::new() };
let first = pb.pages.iter().rev().nth(1).is_none_or(|prev| prev.section != page.section);
let hf = Arc::clone(&ctx.hf);
let first = begins_section(&hf.sections, pb.pages.iter().rev().nth(1), page);
let key = (page.section, page.number, first);
if let Some(areas) = ctx.header_tables.get(&key) {
return areas.clone();
}
let hf = Arc::clone(&ctx.hf);
let Some((_, sect)) = hf.sections.get(page.section) else { return Vec::new() };
if sect.text_direction.is_turned() {
return Vec::new();
@@ -405,13 +427,9 @@ pub(crate) fn headers_footers(ctx: &mut Ctx, pages: &mut [Page], sections: &[(us
let hf = Arc::clone(&ctx.hf);
let even_odd = ctx.doc.settings.even_odd_headers;
let styles = styleref::headers_use_styleref(ctx.doc).then(|| ctx.cache.style_index(ctx.doc));
let mut first_of_section: HashSet<usize> = HashSet::new();
let mut seen = HashSet::new();
for (i, p) in pages.iter().enumerate() {
if seen.insert(p.section) {
first_of_section.insert(i);
}
}
let first_of_section: HashSet<usize> = (0..pages.len())
.filter(|&i| pages.get(i).is_some_and(|p| begins_section(sections, i.checked_sub(1).and_then(|k| pages.get(k)), p)))
.collect();
for (i, page) in pages.iter_mut().enumerate() {
let Some((_, sect)) = sections.get(page.section) else { continue };
// Inherit header/footer references from earlier sections (Word's "link to previous").
+6
View File
@@ -1025,6 +1025,12 @@ impl DocLayout {
let here = para.x_of(li, pos.off)?;
let mut best: Option<(usize, f32)> = None;
for (off, x) in para.line_carets(li) {
// Omitted runs retain byte offsets as zero-width markers. Keep their
// visible edges as candidates without placing the caret inside a run.
let span = para.left_out.partition_point(|range| range.end <= off);
if para.left_out.get(span).is_some_and(|range| range.start < off) {
continue;
}
let Some(x) = x else { continue };
let ahead = if left { x < here - 0.01 } else { x > here + 0.01 };
let d = (x - here).abs();
+24 -3
View File
@@ -210,10 +210,31 @@ impl NoteBox {
cuts
}
/// The least of the note that must stay with its reference: its first line (all of it if it
/// can't be split).
/// Whether widow/orphan control in the note's paragraphs forbids splitting at `cut`: a
/// paragraph's first line alone above it (an orphan) or its last line alone below it (a
/// widow), as in Word for Mac 16.114.4.
pub(crate) fn breaks_widow_control(&self, cut: f32) -> bool {
self.items.iter().filter(|it| self.splittable(it)).any(|it| {
let Placed::Lines { para, l0, l1, y, .. } = it else { return false };
let Some(first) = para.lines.get(*l0) else { return false };
let ends_at = |k: usize| para.lines.get(k).is_some_and(|l| (y + l.top - first.top + l.height - cut).abs() < 0.01);
let n = para.lines.len();
para.rp.widow_control && n >= 2 && ((*l0 == 0 && *l1 >= 2 && ends_at(0)) || (*l1 == n && ends_at(n - 2)))
})
}
/// Where the note may be split with its paragraphs' widow/orphan control kept, ascending.
pub(crate) fn kept_cuts(&self) -> Vec<f32> {
let mut cuts = self.cuts();
cuts.retain(|&c| !self.breaks_widow_control(c));
cuts
}
/// The least of the note that must stay with its reference: its first line, or more under
/// widow/orphan control (all of it if it can't be split).
pub(crate) fn first_piece(&self) -> f32 {
self.cuts().first().copied().unwrap_or(self.h).min(self.h)
// Widow/orphan control may keep more lines together (two, or a short paragraph whole).
self.kept_cuts().first().copied().unwrap_or(self.h).min(self.h)
}
/// Split the note at line bottom `cut`: the part above (`cut` tall) and the rest, moved up to
+53 -5
View File
@@ -89,10 +89,16 @@ pub(crate) struct PageBuilder<'a> {
/// Top of the footer of the pages being started: a footer reaching above the bottom margin
/// pushes the body up (`f32::MAX`: no footer).
pub(crate) foot_top: f32,
/// How low the last line's leading may reach on the current page: the bottom margin, or the
/// top of a footer reaching above it (set as the page starts, from that page's footer).
pub(crate) leading_floor: f32,
/// The wrap areas pages start with ([`EarlyFloats`]) ...
pub(crate) early: &'a EarlyFloats,
/// ... and how many of the current page's `excl` they are (its first ones).
pub(crate) seeded: usize,
/// The wrap areas of the page-anchored body text frames on the current page. Text at the top
/// of a column that one of them reaches into gains room by moving on.
pub(crate) framed: Vec<Rect>,
/// No layout pass follows for floats found above their anchors: each is kept clear of the
/// text laid out before it ([`settle_early`]).
pub(crate) settle: bool,
@@ -160,7 +166,7 @@ impl PageBuilder<'_> {
// The note area starts below the text (a page of continued notes alone: at its top).
let area = self.bottom.max(self.body_floor());
let fits = total <= self.orig_bottom - area + 0.01;
let top = match (fits, self.beneath) {
let mut top = match (fits, self.beneath) {
(false, _) => area,
// Below the page's last line of text.
(true, true) => self.body_floor().min(self.orig_bottom - total),
@@ -173,12 +179,15 @@ impl PageBuilder<'_> {
let mut placed = Vec::new();
// Where the continuation notice goes, below a note that continues on the next page.
let mut notice_y = None;
// The bottom of what is placed (with the notice).
let mut end = y;
let mut rest = notes.into_iter();
while let Some(n) = rest.next() {
let room = self.orig_bottom - y;
if fits || n.h <= room + 0.01 {
let ny = y;
y += n.h;
end = y;
placed.push((n, ny));
continue;
}
@@ -186,21 +195,38 @@ impl PageBuilder<'_> {
// always leaves something here (its first line, or all of it if it can't be split),
// so continuing ends.
let first = placed.is_empty();
let cuts = n.cuts();
// Widow/orphan control in the note keeps two of a paragraph's lines on either side;
// the page's first note gives that up before it gives up the page's room.
let room = room - self.seps.notice_h();
match cuts.iter().rev().find(|&&c| c <= room + 0.01).or(cuts.first().filter(|_| first)).copied() {
let fit = |cuts: Vec<f32>| cuts.into_iter().rev().find(|&c| c <= room + 0.01);
let cut = fit(n.kept_cuts()).or_else(|| if first { fit(n.cuts()).or(n.cuts().first().copied()) } else { None });
match cut {
Some(c) => {
let (head, tail) = n.split(c);
notice_y = Some(y + head.h);
end = y + head.h + self.seps.notice_h();
placed.push((head, y));
self.carry.push(tail);
}
None if first => placed.push((n, y)),
None if first => {
end = y + n.h;
placed.push((n, y));
}
None => self.carry.push(n),
}
self.carry.extend(rest.by_ref());
break;
}
// Notes that continue on the next page still end on the bottom margin, the room left
// going above the separator (Word for Mac 16.114.4), unless they go beneath the text.
if !fits && !self.beneath {
let shift = (self.orig_bottom - end).max(0.0);
top += shift;
notice_y = notice_y.map(|ny| ny + shift);
for (_, ny) in &mut placed {
*ny += shift;
}
}
if let Some(pg) = self.pages.last_mut() {
match if cont { &self.seps.cont } else { &self.seps.sep } {
Some((items, _)) => pg.items.extend(items.iter().cloned().map(|mut it| {
@@ -351,6 +377,7 @@ impl PageBuilder<'_> {
let early = self.early;
self.excl.extend(early.get(&self.pages.len()).into_iter().flatten().map(|(_, _, a)| a.clone()));
self.seeded = self.excl.len();
self.framed.clear();
self.float_tables.clear();
if self.sect.line_numbers.as_ref().is_some_and(|l| l.restart == wordcraft_doc::section::LineNumberRestart::Page) {
self.line_no = 0;
@@ -359,6 +386,7 @@ impl PageBuilder<'_> {
self.number = self.restart_at.take().unwrap_or_else(|| self.number.saturating_add(1));
let (w, h) = if self.web { (s.page_w, f32::MAX / 4.0) } else { (s.page_w, s.page_h) };
let bottom = self.body_bottom(body_top);
self.leading_floor = (s.page_h - s.margin_bottom).min(self.foot_top);
let body = Rect::new(s.margin_left + s.gutter, body_top, s.text_width(), (bottom - body_top).max(36.0));
let mut decor = Vec::new();
if !self.web {
@@ -437,6 +465,13 @@ impl PageBuilder<'_> {
self.bottom = self.bottom.min(self.top + h);
}
}
/// Whether the body ends at the bottom margin, or at the top of a footer that reaches above
/// it: the page's last multiple-spaced line may leave its leading there (see `fit_height`).
/// Word lets it run past the footer's top as into the margin, whatever the footer holds (a
/// page number, several lines of text, an empty paragraph): only the text has to end above it.
pub(crate) fn at_margin(&self) -> bool {
self.bottom >= self.leading_floor - 0.01
}
/// The bottom of the body on a page started with its body at `body_top`: a footer taller than
/// the bottom margin pushes it up (Word: no gap), leaving it at least a little room.
fn body_bottom(&self, body_top: f32) -> f32 {
@@ -476,9 +511,22 @@ impl PageBuilder<'_> {
/// At the top with nothing above on this page, so moving on gains no room. A continuous
/// section starting mid-page is at its top but not fresh: what doesn't fit there goes to the
/// next page (#3907).
pub(crate) fn fresh(&self) -> bool {
/// `reach` is how far the text reaches past the column's left and right edges (a paragraph's
/// negative indents).
pub(crate) fn fresh(&self, reach: (f32, f32)) -> bool {
self.at_page_top() && !self.framed_here(reach)
}
/// At the top of the page's text with nothing placed above it. A page-anchored frame is not
/// content above it: a paragraph with a page break before needs no new page for one.
pub(crate) fn at_page_top(&self) -> bool {
self.at_top() && self.top <= self.page_top + 0.01
}
/// A page-anchored body text frame's wrap area reaches into the current column's text,
/// widened by `reach` on the left and right.
fn framed_here(&self, (left, right): (f32, f32)) -> bool {
let (x0, x1) = (self.col_x() - left, self.col_x() + self.col_w() + right);
self.framed.iter().any(|r| r.x < x1 && r.right() > x0 && r.y < self.bottom && r.bottom() > self.y)
}
/// Move to the next column or page.
pub(crate) fn advance(&mut self, block: usize, body_top: f32) {
if self.col + 1 < self.cols.len() {
+2
View File
@@ -367,6 +367,7 @@ mod label_spacing_tests {
field_codes: false,
grid: Grid::default(),
exclusions: &[],
space_before: 0.0,
eq_number: 0,
numeral: crate::NumeralMode::default(),
read_line_spacing: None,
@@ -513,6 +514,7 @@ mod tests {
field_codes: false,
grid: Grid::default(),
exclusions: &[],
space_before: 0.0,
eq_number: 0,
numeral: Default::default(),
read_line_spacing: None,
+152 -18
View File
@@ -5,7 +5,7 @@ use super::chars::{
};
use super::grid::east_asian;
use super::model::{ClKind, Cluster, Enclosed, Glyph, ParaEnv, RubyLayout, StyleRun, SymbolRun};
use super::{Arc, Document, FaceRef, NumeralMode, ResolvedChar, RubyAlign, SOFT_HYPHEN};
use super::{Arc, Document, FaceRef, NumeralMode, OBJ, ResolvedChar, RubyAlign, SOFT_HYPHEN};
use wordcraft_fonts::ShapeContext;
pub(super) struct Builder<'a> {
@@ -52,6 +52,25 @@ struct SegmentInput<'a> {
context: &'a [bool],
}
/// Whether `face` draws `cluster`, a character and its combining marks, with no missing glyph.
/// The shaper composes a pair the face has a precomposed glyph for (`=` and U+0338 as `≠`), so a
/// face without the mark itself can still draw the pair.
fn draws_all(face: FaceRef, cluster: &str) -> bool {
let glyphs = wordcraft_fonts::shape_in(&face, cluster, &[], |c| c, ShapeContext::default());
!glyphs.is_empty() && glyphs.iter().all(|g| g.gid != 0)
}
/// A face other than `current` that draws all of `cluster` (CSS Fonts 4 §5.3, cluster matching):
/// the run's Thai face or its own font when one does, else the first face in fallback order with
/// every character of it that draws something.
fn cluster_face(cluster: &str, current: FaceRef, run_face: Option<FaceRef>, primary: FaceRef, bold: bool, italic: bool) -> Option<FaceRef> {
if let Some(f) = run_face.into_iter().chain([primary]).filter(|f| f.id() != current.id()).find(|f| draws_all(*f, cluster)) {
return Some(f);
}
let chars: Vec<char> = cluster.chars().filter(|c| draws_something(*c)).collect();
wordcraft_fonts::FontDb::global().fallback_for_run(&chars, primary.id(), bold, italic).map(|f| FaceRef::of(&f))
}
impl<'a> Builder<'a> {
/// Displayed form of `c` at run-relative byte `at` (Word › Numeral): one char in, one
/// char out. `rtl` is the shaping direction; in Context mode `context` (from
@@ -68,6 +87,10 @@ impl<'a> Builder<'a> {
let mut seg_start = 0;
let mut cur: Option<SegKey> = None;
let mut segs = Vec::new();
// The character the marks after it belong to: where it starts, and as drawn.
let mut base: Option<(usize, char)> = None;
// The character whose cluster was matched, and whether its marks stay with it.
let mut matched: Option<(usize, bool)> = None;
for (i, c) in text.char_indices() {
let rtl = use_levels && levels.get(lbase + i).is_some_and(|l| l % 2 == 1);
let c = show(c);
@@ -78,19 +101,67 @@ impl<'a> Builder<'a> {
_ => rc_cs.is_some() && rc.uses_complex(dc),
};
let primary = if complex { primary_cs.unwrap_or(primary) } else { primary };
let face = match cur {
Some(k) if mark => k.face,
let (bold, italic) = if complex { (rc.bold_cs, rc.italic_cs) } else { (rc.bold, rc.italic) };
// A mark stays in the face of the character it belongs to (Arabic harakat with their
// letter, so the letters join) while that face draws it. When it doesn't, the
// character and its marks go together to a face that draws them all (CSS Fonts 4
// §5.3, cluster matching). With no such face, a mark in left-to-right text that isn't
// complex script is matched on its own like any other character; in right-to-left or
// complex-script text it stays with its letter (#7865). A cluster is matched once, at
// its first mark the face lacks: matching it again at every later mark would make a
// long run of marks quadratic.
let mut with_base = false;
let mut moved = None;
if let Some(k) = cur.filter(|_| mark) {
let current = k.face.unwrap_or(primary);
with_base = !draws_something(c) || current.covers(dc);
if !with_base {
match (base.filter(|(at, _)| *at >= seg_start), matched) {
(Some((at, _)), Some((done, stays))) if done == at => with_base = stays,
(Some((at, b)), _) => {
let marks = text.get(at..).unwrap_or("").chars().skip(1).map(show).take_while(|m| is_mark(*m));
let all: String = std::iter::once(b).chain(marks).inspect(|_| crate::work::steps(1)).collect();
if draws_all(current, &all) {
with_base = true;
} else if let Some(f) = cluster_face(&all, current, run_face, primary, bold, italic) {
// The character goes to that face with its marks.
if at > seg_start {
segs.push((seg_start, at, k));
seg_start = at;
}
let face = (f.id() != primary.id()).then_some(f);
cur = Some(SegKey { face, ..k });
moved = Some(face);
} else {
with_base = k.complex || k.rtl;
}
matched = Some((at, with_base || moved.is_some()));
}
(None, _) => with_base = k.complex || k.rtl,
}
}
}
if !mark {
base = (!c.is_control() && c != OBJ).then_some((i, dc));
}
let face = match (moved, cur) {
(Some(face), _) => face,
(None, Some(k)) if with_base => k.face,
_ if !complex && east_asian(c) && primary_ea.is_some_and(|f| f.covers(c)) => primary_ea,
_ if !c.is_control() && c != SOFT_HYPHEN && run_face.is_some_and(|f| f.covers(dc)) => run_face,
_ if primary.covers(dc) || c.is_whitespace() || c.is_control() || c == SOFT_HYPHEN => None,
Some(SegKey { face: Some(face), .. }) if face.covers(dc) => Some(face),
(None, Some(SegKey { face: Some(face), .. })) if face.covers(dc) => Some(face),
_ if !complex && ea_face.is_some() && crate::kinsoku::is_east_asian(c) => ea_face,
_ => {
let (bold, italic) = if complex { (rc.bold_cs, rc.italic_cs) } else { (rc.bold, rc.italic) };
wordcraft_fonts::FontDb::global().fallback_styled(dc, primary.id(), bold, italic).map(|f| FaceRef::of(&f))
}
_ => wordcraft_fonts::FontDb::global().fallback_styled(dc, primary.id(), bold, italic).map(|f| FaceRef::of(&f)),
};
let key = SegKey { face, small: rc.small_caps && !rc.caps && c.is_lowercase(), complex, rtl };
// A mark is set like the character it belongs to, as for `complex`: in small capitals at
// that character's size, so the two stay in one shaping run and its cluster is matched
// whole.
let small = match cur {
Some(k) if mark => k.small,
_ => rc.small_caps && !rc.caps && c.is_lowercase(),
};
let key = SegKey { face, small, complex, rtl };
match cur {
Some(previous) if previous.same(&key) => {}
Some(previous) => {
@@ -139,6 +210,15 @@ impl<'a> Builder<'a> {
// the height Word gives it.
let (a, d) = match wordcraft_fonts::word::symbol_line(&rc.font, &r) {
Some((a, d)) => (a * face.upem, d * face.upem),
// A character Times New Roman or its metric twin lacks: the twin lacks more than
// Times New Roman ("‒", "₽" in Liberation Serif), so the line is as tall as the run's
// font, as with Times New Roman in Word, not as the taller fallback. East Asian text
// keeps its face's height.
None if face_override.is_some() && is_times_twin(&r.face.family) && !face.is_east_asian() => {
let (a, d) = wordcraft_fonts::word::line_metrics(&r.face);
let k = face.upem / r.face.upem.max(1.0);
(a * k, d * k)
}
None => wordcraft_fonts::word::line_metrics(&face),
};
let k = size as f64 / face.upem.max(1.0);
@@ -266,13 +346,15 @@ impl<'a> Builder<'a> {
(resolved.face, resolved.substituted || !family.eq_ignore_ascii_case(&r.font))
});
let primary_cs = resolved_cs.map(|(face, _)| face);
// Chinese, Japanese and Korean characters use the run's East Asian font (`w:eastAsia`) when
// it, or the font table alternate it is drawn in (#2702), is installed and has them.
let wanted_ea = rc.font_ea.as_deref().filter(|f| !f.eq_ignore_ascii_case(&rc.font) && text.chars().any(east_asian)).map(|f| {
let family = lookup_family(self.env.doc, f);
let resolved = wordcraft_fonts::word::resolve(family, rc.bold, rc.italic);
(f, resolved, resolved.substituted || !family.eq_ignore_ascii_case(f))
});
// Chinese, Japanese and Korean characters use the run's East Asian font (`w:eastAsiaTheme`
// over `w:eastAsia`) when it, or the font table alternate it is drawn in (#2702), is
// installed and has them.
let wanted_ea =
super::chars::east_asian_font(self.env.doc, rc).filter(|f| !f.eq_ignore_ascii_case(&rc.font) && text.chars().any(east_asian)).map(|f| {
let family = lookup_family(self.env.doc, f);
let resolved = wordcraft_fonts::word::resolve(family, rc.bold, rc.italic);
(f, resolved, resolved.substituted || !family.eq_ignore_ascii_case(f))
});
let primary_ea = wanted_ea.filter(|(_, r, _)| !r.substituted).map(|(_, r, _)| r.face);
// The levels by byte of `text`, from `lbase` on.
let (levels, lbase): (&[u8], usize) = match dir {
@@ -422,12 +504,15 @@ impl<'a> Builder<'a> {
let ge = bounds.get(bi + 1).copied().unwrap_or(shape_text.len());
let g0 = self.glyphs.len() as u32;
let mut adv = 0.0f32;
// What kerning added to the last glyph's advance: its pair with the next glyph.
let mut kern = 0.0f32;
while let Some(g) = shaped.get(gi) {
if g.cluster >= ge {
break;
}
self.glyphs.push(Glyph { gid: g.gid, dx: adv + g.x_offset as f32 * k * hscale, dy: g.y_offset as f32 * k });
adv += g.x_advance as f32 * k * hscale;
kern = if rc.kerned() && !key.rtl { pair_with_next(g, st.face.advance(g.gid)) * k * hscale } else { 0.0 };
gi += 1;
}
let g1 = self.glyphs.len() as u32;
@@ -455,6 +540,7 @@ impl<'a> Builder<'a> {
obj_h: 0.0,
obj_d: 0.0,
dot: s == "." || s == ",",
kern: if kind == ClKind::Text && g1 == g0 + 1 { kern } else { 0.0 },
});
}
if matches!(dir, Dir::Para) {
@@ -497,6 +583,13 @@ impl<'a> Builder<'a> {
}
}
}
// The ligature glyph's kerning pair with the following glyph belongs after its last
// letter, not on the head inside the ligature (#8618).
if let Some((head, rest)) = self.clusters.get_mut(i..=i + n).and_then(|cs| cs.split_first_mut())
&& let Some(last) = rest.last_mut()
{
last.kern = std::mem::take(&mut head.kern);
}
i += n + 1;
}
}
@@ -527,6 +620,7 @@ impl<'a> Builder<'a> {
obj_h: 0.0,
obj_d: 0.0,
dot: false,
kern: 0.0,
});
return;
};
@@ -560,7 +654,20 @@ impl<'a> Builder<'a> {
let style = first.style;
let g1 = added.last().map(|c| c.g1).unwrap_or(g0);
self.shown.push((self.clusters.len(), text.to_string(), ranges));
self.clusters.push(Cluster { start, end, adv: x, kind: ClKind::Text, style, g0, g1, break_after: false, obj_h: 0.0, obj_d: 0.0, dot: false });
self.clusters.push(Cluster {
start,
end,
adv: x,
kind: ClKind::Text,
style,
g0,
g1,
break_after: false,
obj_h: 0.0,
obj_d: 0.0,
dot: false,
kern: 0.0,
});
}
/// Shape `texts` on top of one another as one cluster for `start..end`: each aligned within
@@ -610,11 +717,38 @@ impl<'a> Builder<'a> {
if !text.is_empty() {
self.shown.push((k, text, ranges));
}
self.clusters.push(Cluster { start, end, adv, kind: ClKind::Text, style, g0, g1, break_after: false, obj_h: 0.0, obj_d: 0.0, dot: false });
self.clusters.push(Cluster {
start,
end,
adv,
kind: ClKind::Text,
style,
g0,
g1,
break_after: false,
obj_h: 0.0,
obj_d: 0.0,
dot: false,
kern: 0.0,
});
Some(k)
}
}
/// What kerning added to a glyph's advance (in font units) for its pair with the next glyph. An
/// old-style `kern` table's pair is split between its two glyphs, the second's half in its advance
/// and its offset alike: that half is the pair with the glyph before, which stays on the line.
fn pair_with_next(g: &wordcraft_fonts::ShapedGlyph, plain_advance: f64) -> f32 {
let added = g.x_advance as f32 - plain_advance as f32;
let before = if added != 0.0 { g.x_offset as f32 } else { 0.0 };
added - before
}
/// Times New Roman or one of its metric twins.
fn is_times_twin(family: &str) -> bool {
["Times New Roman", "Liberation Serif", "Tinos"].iter().any(|f| family.eq_ignore_ascii_case(f))
}
/// Lay out an `EQ \o` field (ECMA-376 Part 1 §17.16.5.20): its arguments drawn on top of one
/// another, as one cluster. An enclosure symbol among them (○ □ △ ◇, see
/// [`wordcraft_doc::eq::EncloseShape`]) is drawn as a shape around the text rather than as a
+31 -1
View File
@@ -55,7 +55,8 @@ pub(super) fn caps_expands(c: char) -> bool {
}
/// Combining marks and joiners (bidi classes NSM, BN: harakat, ZWNJ, ZWJ) belong to the
/// character before them: same font, same shaping run, so Arabic joining isn't broken.
/// character before them: same font, same shaping run, so Arabic joining isn't broken. A mark
/// that font can't draw takes its character to a face that draws both (`segment_keys`, #7865).
pub(super) fn is_mark(c: char) -> bool {
use unicode_bidi::BidiClass::{BN, NSM};
// No ASCII character is a mark (its BN characters are controls).
@@ -212,6 +213,35 @@ pub fn substitute_face(doc: &Document, font: &str) -> Option<FaceRef> {
(r.substituted || family != font).then_some(r.face)
}
const THEME_FONTS_PASSTHROUGH: &str = "wordcraft:theme.fonts";
/// The East Asian font (`a:ea`) stored for the theme's major or minor font scheme, when the
/// document's theme names a non-empty one (`craft-docx` keeps them in `wordcraft:theme.fonts`).
fn theme_ea_face(doc: &Document, major: bool) -> Option<&str> {
let text = std::str::from_utf8(doc.passthrough.get(THEME_FONTS_PASSTHROUGH)?).ok()?;
let key = if major { "major" } else { "minor" };
text.lines().find_map(|line| {
let mut parts = line.splitn(4, '\t');
let (k, kind, which, face) = (parts.next()?, parts.next()?, parts.next()?, parts.next()?);
(k == key && kind == "face" && which == "ea" && !face.trim().is_empty()).then_some(face)
})
}
/// The East Asian font effective for a run (`w:eastAsiaTheme` takes precedence over `w:eastAsia`,
/// including an inherited `w:eastAsia`). Returns `None` when none is named or the theme slot
/// points to an East Asian theme font with no single named `a:ea` face.
pub(super) fn east_asian_font<'a>(doc: &'a Document, rc: &'a ResolvedChar) -> Option<&'a str> {
use wordcraft_doc::props::ThemeFont;
match rc.font_ea_theme {
Some(ThemeFont::MajorEastAsia) => theme_ea_face(doc, true),
Some(ThemeFont::MinorEastAsia) => theme_ea_face(doc, false),
Some(ThemeFont::MajorAscii | ThemeFont::MajorHAnsi) => Some(doc.settings.major_font.as_str()).filter(|f| !f.trim().is_empty()),
Some(ThemeFont::MinorAscii | ThemeFont::MinorHAnsi) => Some(doc.settings.minor_font.as_str()).filter(|f| !f.trim().is_empty()),
Some(ThemeFont::MajorBidi | ThemeFont::MinorBidi) => None,
None => rc.font_ea.as_deref().filter(|f| !f.trim().is_empty()),
}
}
/// The face Chinese, Japanese and Korean text is drawn in when its East Asian font (`w:eastAsia`)
/// `font_ea` isn't installed and the run's font is `font`; `None` when `font_ea` is installed. As
/// layout draws it: an East Asian font is looked up by name alone (the roman-font rule of
+15 -5
View File
@@ -70,6 +70,8 @@ pub(super) fn snap_chars(b: &mut Builder, text: &str, grid: &Grid) {
g.dx += shift;
}
c.adv = adv;
// The snapped advance no longer includes the shaped kerning adjustment.
c.kern = 0.0;
}
}
@@ -99,14 +101,17 @@ fn auto_space_room(st: &StyleRun) -> f32 {
/// size for Times New Roman, 0.2203 for Arial, 0.2575 for Calibri, 0.2980 for Courier New,
/// 0.3041 for Cambria — which is half each face's average character width. With different sizes
/// either side, the room after the Latin run takes the Latin size, not the Asian one.
pub(super) fn auto_space(b: &mut Builder, text: &str, de: bool, dn: bool) -> Vec<(usize, f32)> {
///
/// `ea_lacks(at, c)`: the run at byte `at` names an installed East Asian font that has no glyph
/// for `c`. Word adds no room beside such a character, though a substituted face draws it (#6591).
pub(super) fn auto_space(b: &mut Builder, text: &str, de: bool, dn: bool, ea_lacks: impl Fn(usize, char) -> bool) -> Vec<(usize, f32)> {
let mut out = Vec::new();
if !de && !dn {
return out;
}
let mut shown = b.shown.iter().map(|s| (s.0, s.1.as_str())).peekable();
// The previous text cluster: index and its last character.
let mut prev: Option<(usize, char)> = None;
// The previous text cluster: index, its last character and its start byte.
let mut prev: Option<(usize, char, usize)> = None;
for k in 0..b.clusters.len() {
let Some(c) = b.clusters.get(k) else { break };
match c.kind {
@@ -126,8 +131,13 @@ pub(super) fn auto_space(b: &mut Builder, text: &str, de: bool, dn: bool) -> Vec
prev = None;
continue;
};
if let Some((pk, pc)) = prev
let start = c.start;
if let Some((pk, pc, pstart)) = prev
&& let Some(side) = crate::kinsoku::auto_space(pc, first, de, dn)
&& !match side {
crate::kinsoku::AsianSide::Left => ea_lacks(pstart, pc),
crate::kinsoku::AsianSide::Right => ea_lacks(start, first),
}
{
let style = b.clusters.get(pk).map(|p| p.style as usize);
let st = style.and_then(|i| b.styles.get(i));
@@ -142,7 +152,7 @@ pub(super) fn auto_space(b: &mut Builder, text: &str, de: bool, dn: bool) -> Vec
out.push((pk, gap));
}
}
prev = Some((k, last));
prev = Some((k, last, start));
}
out
}
+79 -13
View File
@@ -14,6 +14,9 @@ const MIN_LINE_WIDTH: f32 = 1.0;
struct Breaker<'e> {
level: Option<&'e Level>,
rp: wordcraft_doc::resolve::ResolvedPara,
/// The space before the paragraph that the flow laid out above it, which a Top-and-Bottom
/// object in it is laid out again below (see [`ParaEnv::space_before`]).
space_before: f32,
mark_style: u32,
exclusions: &'e [Exclusion],
n: usize,
@@ -220,6 +223,7 @@ impl<'e> Breaker<'e> {
// Exact spacing fixes the table-contact boundary even when the mark has other metrics.
// Keep the existing estimate for shapes and for non-exact spacing.
table_h: if let LineSpacing::Exactly(h) = rp.line_spacing { h } else { est_h },
space_before: env.space_before,
rp,
first_x0: None,
hcache: Vec::new(),
@@ -262,6 +266,26 @@ impl<'e> Breaker<'e> {
let mut guard = 0;
loop {
let lo = self.row_left(pl);
// A Top-and-Bottom object ending in the paragraph's space before (or reaching into
// its first line) is a block the first line must start below, with that space before
// laid out again under it (#7143). Exclusions are relative to the first line's
// original top (0), so keep the band anchored there (`[-before, est_h]`) even after
// `row_spans` or `skip_row` moves `self.top` down past a side-wrapping object (#8614):
// only the space the flow actually laid out above 0 holds a space-before obstruction.
if self.first && self.space_before > 0.0 {
let before = self.space_before;
let row = (-before, self.est_h + before, self.table_h);
if let Some(below) = self
.exclusions
.iter()
.filter(|e| e.top_bottom)
.filter(|e| e.intersects_row(row.0, row.1, row.2, lo, self.base_right))
.map(|e| e.bottom)
.reduce(f32::max)
{
self.top = self.top.max(below + before);
}
}
let row = (self.top, self.est_h, self.table_h);
match row_spans(self.exclusions, row, (lo, self.base_right), self.tight_indent).map(|mut spans| (spans.pop_front(), spans)) {
Ok((Some((a, b)), rest)) => {
@@ -368,7 +392,8 @@ impl<'e> Breaker<'e> {
/// Returns how it ends.
fn close_line(&mut self, pl: &mut ParaLayout, mut sc: Scan) -> LineEnd {
if sc.end == LineEnd::Para || sc.end == LineEnd::Wrap {
let xc = sc.x;
let kern = if sc.end == LineEnd::Wrap && sc.j > sc.c0 { line_end_kern(pl, sc.j - 1) } else { 0.0 };
let xc = sc.x - kern;
resolve_tab(pl, &mut sc.pending_tab, &mut sc.xs, sc.c0, xc, &mut sc.x);
}
if sc.j >= self.n && sc.end != LineEnd::Wrap && !matches!(sc.end, LineEnd::LineBreak | LineEnd::PageBreak | LineEnd::ColumnBreak) {
@@ -430,8 +455,8 @@ impl<'e> Breaker<'e> {
let hyphen = (sc.end == LineEnd::Wrap && c1 > c0 && pl.hyph_after.binary_search(&((c1 - 1) as u32)).is_ok())
.then(|| pl.clusters.get(c1 - 1).map(|c| hyphen_glyph(pl, c.style, &mut self.hcache)))
.flatten();
let end_x = match (sc.xs.last(), c1.checked_sub(1).and_then(|k| pl.clusters.get(k))) {
(Some(lx), Some(c)) => lx + c.adv + hyphen.map_or(0.0, |h| h.2),
let end_x = match (sc.xs.last(), c1.checked_sub(1).and_then(|k| pl.clusters.get(k).map(|c| (k, c)))) {
(Some(lx), Some((k, c))) => lx + c.adv - line_end_kern(pl, k) + hyphen.map_or(0.0, |h| h.2),
_ => sc.line_start_x,
};
sc.xs.push(end_x);
@@ -442,7 +467,7 @@ impl<'e> Breaker<'e> {
/// tallest picture on it (which sits on the baseline).
fn extents(&self, pl: &ParaLayout, (c0, c1): (usize, usize)) -> Extents {
let rp = &self.rp;
let mut ex = Extents { asc: 0.0, desc: 0.0, obj_asc: 0.0, obj_desc: 0.0, text: false };
let mut ex = Extents { asc: 0.0, desc: 0.0, obj_asc: 0.0, obj_desc: 0.0, text: false, single: 0.0 };
let mut any = false;
let dropped = pl.drop_cap.map_or(0, |d| d.0);
for (k, c) in pl.clusters.get(c0..c1).into_iter().flatten().enumerate() {
@@ -486,6 +511,7 @@ impl<'e> Breaker<'e> {
};
ex.asc = ex.asc.max(a);
ex.desc = ex.desc.max(d);
ex.single = ex.single.max(a + d);
any = true;
// Text needs its descent below the line; so do inline math (an object with its own
// descent) and a check box. A line break ending the line is no text.
@@ -503,7 +529,7 @@ impl<'e> Breaker<'e> {
/// The line's height, baseline and text extent.
fn measure(&self, pl: &ParaLayout, range: (usize, usize)) -> Measure {
let rp = &self.rp;
let Extents { mut asc, mut desc, obj_asc, obj_desc, text } = self.extents(pl, range);
let Extents { mut asc, mut desc, obj_asc, obj_desc, text, single } = self.extents(pl, range);
let mut text_natural = asc + desc;
let font_desc = desc;
desc = desc.max(obj_desc);
@@ -554,6 +580,10 @@ impl<'e> Breaker<'e> {
}
}
}
// Multiple spacing adds (m - 1) x the tallest of the line's runs, not of the line: a line
// mixing fonts is as much taller as its runs' extents make it, once (Word for Mac and
// Windows: 10 pt Times New Roman with 10 pt Courier New at 1.5 and double spacing).
let run_leading = if single > 0.0 && !pictures_alone { single.min(text_natural) } else { text_natural };
// Keep the picture floor independent of list-label metrics.
let natural = asc + desc;
let pictures = if obj_asc > asc { obj_asc + desc } else { 0.0 };
@@ -562,7 +592,9 @@ impl<'e> Breaker<'e> {
let (height, centred) = match (rp.line_spacing, grid) {
(LineSpacing::Multiple(m), Some(g)) => ((g.snap_height(natural) * m).max(g.snap_height(pictures)), true),
(LineSpacing::AtLeast(v), Some(g)) => (g.snap_height(natural.max(pictures)).max(v), true),
(LineSpacing::Multiple(m), None) => ((text_natural * m + label_extra).max(text_pictures + (m - 1.0).max(0.0) * font_natural), false),
(LineSpacing::Multiple(m), None) => {
((text_natural + (m - 1.0) * run_leading + label_extra).max(text_pictures + (m - 1.0).max(0.0) * font_natural), false)
}
(LineSpacing::AtLeast(v), None) => (natural.max(text_pictures).max(v), false),
(LineSpacing::Exactly(v), _) => (v, false),
};
@@ -745,6 +777,8 @@ struct Extents {
obj_desc: f32,
/// Whether the line holds text besides its pictures (spaces and tabs don't count).
text: bool,
/// The tallest of its runs' own heights (ascent plus descent): the multiple's leading.
single: f32,
}
/// A line's height and baseline, and the extent of its text.
@@ -876,6 +910,14 @@ impl Scan {
bk.wrapped_tab = Some(j);
return true;
}
if bk.wrapped_tab == Some(j) && self.narrowed && stop.pos > bk.base_right + 0.01 && bk.skipped < 50 {
// A left tab past the right indent that wrapped into a span narrowed by a
// floating object (the far side of it, say): like Word, it goes on to the
// first line clear of the object (#6577). A stop inside the right indent
// keeps the zero-width path below.
self.skip = true;
return true;
}
if bk.wrapped_tab == Some(j) {
// Still past the right indent on the line it wrapped to: it takes no
// room, and its text starts at the indent rather than on a line of its own.
@@ -909,19 +951,31 @@ impl Scan {
}
self.x += w;
}
_ => self.pending_tab = Some((j, stop, self.x)),
_ => {
// Its room grows from nothing with its text (a tab moved on from the line before
// may still hold the width it had there).
if let Some(c) = pl.clusters.get_mut(j) {
c.adv = 0.0;
}
self.pending_tab = Some((j, stop, self.x));
}
}
if stop.leader != TabLeader::None {
self.leaders.push((j, stop.leader));
}
}
/// Whether text after a right/centre tab grows leftwards into the tab's space first.
/// Whether text after a right/centre tab grows leftwards into the tab's space first. Up to a
/// right stop it fits even past the right indent (Word: a TOC entry whose text ends
/// less than a digit short of the indent keeps its page number on its line when the stop is
/// at the margin); unshifted, the text after the tab ends at `x - room`.
fn absorbs(&self, pl: &ParaLayout, advance: f32) -> bool {
self.pending_tab.is_some_and(|(tj, stop, _)| {
let room = pl.clusters.get(tj).map(|t| t.adv).unwrap_or(0.0);
match stop.align {
TabAlign::Right | TabAlign::Decimal => room >= advance,
// Not where a floating object narrows the line: the text would run into it.
TabAlign::Right => room >= advance || (!self.narrowed && self.x - room + advance <= stop.pos + 0.01),
TabAlign::Decimal => room >= advance,
TabAlign::Center => room >= advance / 2.0 && self.x + advance / 2.0 <= self.right_edge + 0.01,
_ => false,
}
@@ -947,7 +1001,7 @@ impl Scan {
0.0
};
let fits = absorbs
|| self.x + advance - pl.auto_space_after(j) <= self.right_edge + shrink + 0.01
|| self.x + advance - pl.auto_space_after(j) - line_end_kern(pl, j) <= self.right_edge + shrink + 0.01
|| c.kind == ClKind::Space
|| c.kind == ClKind::Marker;
if !fits && pl.is_edit_boundary(c.start) && (c0..j).any(|k| pl.clusters.get(k).is_some_and(takes_room)) {
@@ -997,7 +1051,9 @@ impl Scan {
/// Text after a decimal/centre/right tab shifts as it grows.
fn shift_pending_tab(&mut self, pl: &mut ParaLayout) {
let Some((tj, stop, tx)) = self.pending_tab else { return };
let seg_w = self.x - tx;
// For a right tab `x` includes the room the tab has so far (it starts from none).
let old = pl.clusters.get(tj).map(|c| c.adv).unwrap_or(0.0);
let seg_w = self.x - tx - if stop.align == TabAlign::Right { old } else { 0.0 };
let shift = match stop.align {
TabAlign::Right => stop.pos - tx - seg_w,
TabAlign::Center => stop.pos - tx - seg_w / 2.0,
@@ -1006,7 +1062,6 @@ impl Scan {
_ => 0.0,
};
let shift = shift.max(0.0);
let old = pl.clusters.get(tj).map(|c| c.adv).unwrap_or(0.0);
if (shift - old).abs() > 0.001 {
let delta = shift - old;
if let Some(c) = pl.clusters.get_mut(tj) {
@@ -1040,7 +1095,7 @@ impl Scan {
self.word_from = if c.kind == ClKind::Space { self.x - c.adv } else { self.x };
} else if self.hyph_ok
&& !pl.clusters.get(j + 1).is_some_and(|n| n.kind == ClKind::Text && n.g1 <= n.g0)
&& self.x + hyphen_glyph(pl, c.style, &mut bk.hcache).2 <= self.right_edge + shrink + 0.01
&& self.x - line_end_kern(pl, j) + hyphen_glyph(pl, c.style, &mut bk.hcache).2 <= self.right_edge + shrink + 0.01
{
self.last_break = Some(j);
}
@@ -1114,6 +1169,17 @@ impl Scan {
}
}
/// The kerning cluster `j` loses when the line ends after it inside a word: Word measures a line's
/// last letter without its pair with the letter that goes on to the next line (a cell's width
/// swept a twip at a time in Word: the letters before a broken kerning pair fit only where they
/// fit on their own, without the pair).
fn line_end_kern(pl: &ParaLayout, j: usize) -> f32 {
match (pl.clusters.get(j), pl.clusters.get(j + 1)) {
(Some(c), Some(next)) if next.kind == ClKind::Text => c.kern,
_ => 0.0,
}
}
/// Narrowest span text flows into beside a floating object, points. Word puts an empty
/// paragraph beside a floating table in a 21.3pt gap but not in an 18.6pt one.
const MIN_SPAN: f32 = 20.0;
+10 -1
View File
@@ -147,6 +147,9 @@ pub struct Cluster {
pub obj_d: f32,
/// The cluster is a decimal separator (decimal tabs align on it).
pub dot: bool,
/// The kerning between this cluster and the next (part of `adv`, usually negative): a line
/// that ends between them lays the cluster out without it.
pub kern: f32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -391,8 +394,14 @@ pub struct ParaEnv<'a> {
/// How digits look on screen (an unresolved `System` shows Western digits).
pub numeral: NumeralMode,
/// Areas text must flow around (floating objects), relative to the paragraph: x from the
/// column's left edge, y from the top of the first line.
/// column's left edge, y from the top of the first line (its top with the space before
/// applied, which is where [`ParaEnv::space_before`] reaches up to).
pub exclusions: &'a [Exclusion],
/// The space before the paragraph that the flow above it actually laid out: its declared
/// space before less what collapsing against the previous paragraph's space after, contextual
/// spacing or a page top took away (and the negative space applied at a page top). A
/// Top-and-Bottom object reaching into it is laid out again below it (#7143).
pub space_before: f32,
/// Automatic equation numbers used before this paragraph.
pub eq_number: u32,
pub read_line_spacing: Option<f32>,
+35 -2
View File
@@ -62,6 +62,7 @@ impl Slot {
obj_h,
obj_d,
dot: false,
kern: 0.0,
}
}
}
@@ -101,6 +102,11 @@ fn is_special(c: char) -> bool {
fn paragraph_props(p: &Paragraph, env: &ParaEnv) -> ResolvedPara {
let doc = env.doc;
let mut rp = doc.styles.resolve_para_in(&p.props, env.table.map(|t| &t.para));
// Before Word 2013 layout (compatibility mode 15) a row split across pages divides its cells'
// text at any line: widow/orphan control doesn't apply in a table (measured in modes 12, 14).
if env.table.is_some() && doc.settings.compat_mode < wordcraft_doc::COMPAT_MODE_CURRENT {
rp.widow_control = false;
}
if let Some(spacing) = env.read_line_spacing.filter(|s| s.is_finite() && (1.0..=2.0).contains(s)) {
rp.line_spacing = wordcraft_doc::props::LineSpacing::Multiple(spacing);
}
@@ -300,6 +306,7 @@ impl<'a> Shaped<'a> {
big.font = f.clone();
big.font_cs = f.clone();
big.font_ea = Some(f.clone());
big.font_ea_theme = None;
}
let before = self.b.clusters.len();
self.b.shape(first, 0, &Arc::new(big), None);
@@ -546,7 +553,12 @@ fn list_label(cx: &Cx, b: &mut Builder, mark_style: u32) -> Option<Label> {
let break_only =
b.clusters.iter().any(|c| c.kind == ClKind::PageBreak) && b.clusters.iter().all(|c| matches!(c.kind, ClKind::PageBreak | ClKind::Marker));
let (text, lvl) = cx.env.label.as_ref().filter(|_| !break_only && !cx.env.joined)?;
let rc = cx.res.char(&p.mark.clone().overlaid(&lvl.chr));
let mut rc = cx.res.char(&p.mark.clone().overlaid(&lvl.chr));
// Word never kerns a list number, whatever the kerning of the paragraph mark or the level
// (measured in Word for Mac: "11)" in Times New Roman with kerning on is 16 pt wide, not
// the 15.55 pt of the kerned "11", so it passes a 312-twip hanging indent and the text goes on
// to the next tab stop).
Arc::make_mut(&mut rc).kern = 0.0;
// A bullet no installed font can draw would come from whatever icon font has its
// private-use code (Font Awesome's Twitter logo at U+F081, #1683): it shows the level's
// default bullet instead.
@@ -652,6 +664,22 @@ fn shown_text(cx: &Cx) -> Option<String> {
Some(shown)
}
/// Each run's end byte and the installed East Asian font (`w:eastAsiaTheme` over `w:eastAsia`)
/// it resolves to, `None` when none is resolved or it isn't installed. Empty when `wanted` is
/// false or the text is ASCII, which has no East Asian characters to look the fonts up for.
fn installed_east_asian_fonts(cx: &Cx, wanted: bool) -> Vec<(usize, Option<wordcraft_fonts::FaceRef>)> {
if !wanted || cx.p.text.is_ascii() {
return Vec::new();
}
cx.p.run_ranges()
.map(|(range, props)| {
let rc = cx.res.char(props);
let face = super::chars::east_asian_font(cx.env.doc, &rc).map(|f| wordcraft_fonts::word::resolve(f, rc.bold, rc.italic));
(range.end, face.filter(|r| !r.substituted).map(|r| r.face))
})
.collect()
}
/// Lay out one paragraph.
pub fn layout_para(p: &Paragraph, env: &ParaEnv) -> ParaLayout {
#[cfg(test)]
@@ -687,7 +715,12 @@ pub fn layout_para(p: &Paragraph, env: &ParaEnv) -> ParaLayout {
let auto_space = if rp.snap_to_grid && env.grid.snap_all && env.grid.chars.is_some() {
Vec::new()
} else {
auto_space(&mut sh.b, &p.text, rp.auto_space_de, rp.auto_space_dn)
let ea = installed_east_asian_fonts(&cx, rp.auto_space_de || rp.auto_space_dn);
// Runs come in order, so their ends rise: the run holding `at` is a binary search away.
let ea_lacks = |at: usize, c: char| {
ea.get(ea.partition_point(|(end, _)| *end <= at)).and_then(|(_, face)| *face).is_some_and(|f: wordcraft_fonts::FaceRef| !f.covers(c))
};
auto_space(&mut sh.b, &p.text, rp.auto_space_de, rp.auto_space_dn, ea_lacks)
};
let mut skip = sh.left.clone();
skip.extend(sh.bare.iter().cloned());
+7 -4
View File
@@ -234,8 +234,10 @@ fn new_page_builder<'p>(
sect_beneath: false,
beneath: false,
foot_top: f32::MAX,
leading_floor: 0.0,
early,
seeded: 0,
framed: Vec::new(),
settle,
column_lines: None,
}
@@ -445,9 +447,10 @@ fn section_endnotes(ctx: &mut Ctx, pb: &mut PageBuilder, endnotes: &mut VecDeque
/// the turned pages of vertical sections.
fn finish_pages(pb: PageBuilder, doc: &Document, sections: &[(usize, &SectionProps)], web: bool) -> Vec<Page> {
let mut pb = pb;
pb.close_column_lines();
pb.apply_valign();
pb.flush_notes();
// Each page is aligned once, before its notes go on it: `finish_page` leaves the page
// top-aligned after, so a page of continued notes isn't moved down again past the bottom
// margin when the next one starts.
pb.finish_page();
let last_block = doc.body.len().saturating_sub(1);
for _ in 0..MAX_NOTE_PAGES {
if pb.carry.is_empty() {
@@ -455,7 +458,7 @@ fn finish_pages(pb: PageBuilder, doc: &Document, sections: &[(usize, &SectionPro
}
let top = pb.top;
pb.new_page(last_block, top);
pb.flush_notes();
pb.finish_page();
}
pb.carry.clear();
pb.raise_front();
+91 -15
View File
@@ -248,6 +248,7 @@ pub fn measure_table_columns(doc: &wordcraft_doc::Document, t: &Table) -> Vec<(f
// Measurement uses a fixed environment (like show_hidden/proofing above).
numeral: crate::NumeralMode::default(),
exclusions: &[],
space_before: 0.0,
eq_number: 0,
read_line_spacing: None,
grid: crate::para::Grid::default(),
@@ -332,9 +333,26 @@ pub fn autofit_widths(cols: &[(f32, f32)], avail: f32) -> Vec<f32> {
cols.iter().map(|c| c.0 + (c.1 - c.0) * k).collect()
}
/// The first cell's left margin: how far its text sits inside the table's edge.
pub(crate) fn first_cell_left_margin(ctx: &Ctx, t: &Table) -> f32 {
first_cell_left_margin_in(t, default_margins(t, table_style(ctx, t).as_ref()))
/// How far left of its offset (`w:tblpX`) a floating table placed by one has its edge. Before
/// Word 2013 layout the first cell's text is at the offset, moved by the table's indent; from it
/// the edge is, moved in by half its left border, the indent ignored (measured in Word for
/// Windows).
pub(crate) fn float_offset_shift(ctx: &Ctx, t: &Table) -> f32 {
let style = table_style(ctx, t);
if ctx.doc.settings.compat_mode < 15 {
first_cell_left_margin_in(t, default_margins(t, style.as_ref())) - t.props.indent.unwrap_or(0.0)
} else {
-half_edge_border(t, &table_borders(t, style.as_ref()))
}
}
/// Half the left border of a table's first cell, which Word (from mode 15) moves the table in by:
/// the cell's own border, else its row's `w:tblPrEx`, else the table's (`borders`, with its style's).
fn half_edge_border(t: &Table, borders: &Borders) -> f32 {
let row = t.rows.first();
let own = row.and_then(|r| r.cells.first()).and_then(|c| c.props.borders.and_then(|b| b.left));
let exception = row.and_then(|r| r.props.exceptions.as_ref()).and_then(|e| e.borders).and_then(|b| b.left);
own.or(exception).or(borders.left).filter(Border::is_visible).map_or(0.0, |b| b.width.clamp(0.0, 12.0) / 2.0)
}
fn first_cell_left_margin_in(t: &Table, def: [f32; 4]) -> f32 {
@@ -574,17 +592,15 @@ fn table_frame(ctx: &mut Ctx, t: &Table, avail: f32, depth: usize, style: Option
let margins_def = default_margins(t, style);
let indent = t.props.indent.unwrap_or(0.0);
let tborders = table_borders(t, style);
let first_cell = t.rows.first().and_then(|r| r.cells.first());
// A right-to-left table (`w:bidiVisual`) mirrors: its first column stands at the right, its
// start alignment and indent are measured from the right margin, and each cell's start
// (left) margin and border are on its right.
// (left) border is drawn on its right (cell margins stay on the sides they name).
let rtl = t.props.bidi_visual;
// How far in from the start margin the table's edge sits when it is start-aligned.
let start_offset = if ctx.doc.settings.compat_mode >= 15 {
// The border is centred on the edge, so half of it sits outside: Word moves the table in
// by that half.
let border = first_cell.and_then(|c| c.props.borders.and_then(|b| b.left)).or(tborders.left);
indent + border.filter(Border::is_visible).map_or(0.0, |b| b.width.clamp(0.0, 12.0) / 2.0)
indent + half_edge_border(t, &tborders)
} else {
indent - first_cell_left_margin_in(t, margins_def)
};
@@ -616,6 +632,51 @@ fn table_frame(ctx: &mut Ctx, t: &Table, avail: f32, depth: usize, style: Option
}
pub fn layout_table(ctx: &mut Ctx, story: StoryRef, t: &Table, path: &[u32], avail: f32, depth: usize) -> TableLayout {
layout_table_rows(ctx, story, t, path, avail, depth, None)
}
/// Row `ri` of the body table laid out again for where it lands on a page, `room` points above the
/// bottom of the page body: a merged cell starting in it that runs on past the page end is
/// aligned (and its turned text laid out) within that room, as its text is drawn with this row.
/// The row's height is the one [`layout_table`] gave it.
pub fn layout_table_row_in(ctx: &mut Ctx, t: &Table, path: &[u32], avail: f32, ri: usize, room: f32) -> Option<RowLayout> {
// A look ahead: list and equation numbers in the cells don't count again.
let (counters, eq_count) = (ctx.counters.clone(), ctx.eq_count);
let mut tl = layout_table_rows(ctx, StoryRef::Body, t, path, avail, 1, Some((ri, room)));
(ctx.counters, ctx.eq_count) = (counters, eq_count);
tl.rows.pop()
}
/// How many rows after row `ri` the merged cells starting in it run on (0 without any).
pub(crate) fn merge_rows_after(t: &Table, ri: usize) -> usize {
let Some(row) = t.rows.get(ri) else { return 0 };
let mut gx = row.first_grid();
let mut most = 0;
for c in &row.cells {
let g = gx;
gx += c.span();
if c.props.vmerge != VMerge::Restart {
continue;
}
let mut k = ri + 1;
while t.rows.get(k).is_some_and(|r| {
let mut gx = r.first_grid();
r.cells.iter().any(|x| {
let at = gx;
gx += x.span();
at == g && x.props.vmerge == VMerge::Continue
})
}) {
k += 1;
}
most = most.max(k - ri - 1);
}
most
}
/// [`layout_table`], or with `only` = (row, room) just that row, its merged cells aligned within
/// `room` (see [`layout_table_row_in`]).
fn layout_table_rows(ctx: &mut Ctx, story: StoryRef, t: &Table, path: &[u32], avail: f32, depth: usize, only: Option<(usize, f32)>) -> TableLayout {
let style = table_style(ctx, t);
// Cell text formatting and looks per set of style parts, built once per table.
let mut cell_text: Vec<(Region, CellText)> = Vec::new();
@@ -707,9 +768,13 @@ pub fn layout_table(ctx: &mut Ctx, story: StoryRef, t: &Table, path: &[u32], ava
} else if turn.is_turned() {
collapsed = false;
// Turned text: its lines run along the cell's height. An exact row height sets
// their length, and a minimum height does when the lines fit across the column;
// otherwise they get the length the text needs unwrapped and the row grows to fit
// (the second pass lays them out again if the row ends up taller).
// their length, and a minimum height (`AtLeast`, or the combined minimum of a
// vertical merge) does when the lines fit across the column; otherwise they get
// the length the text needs unwrapped and the row grows to fit (the second pass
// lays them out again if the row ends up taller). Checked in Word (#6528): in an
// "At least" row, turned text wraps to the minimum height instead of growing the
// row, and a word longer than that minimum runs past the row (tested at 0.3 cm)
// without growing it.
let snap = (ctx.counters.clone(), ctx.eq_count);
let merged = merged_min_height(t, ri, g);
let preferred = merged.or(row.props.height.filter(|h| h.is_finite() && *h > 0.0)).map(|h| h.clamp(4.0, TURNED_LIMIT));
@@ -797,7 +862,7 @@ pub fn layout_table(ctx: &mut Ctx, story: StoryRef, t: &Table, path: &[u32], ava
rows.push(cells);
}
grow_vertical_merges(&rows, &mut heights);
finish_table_rows(ctx, TableRows { story, table: t, path, depth, cell_text, rows, heights, bottoms, edges, x, total })
finish_table_rows(ctx, TableRows { story, table: t, path, depth, cell_text, rows, heights, bottoms, edges, x, total, only })
}
fn grow_vertical_merges(rows: &[Vec<CellBox>], heights: &mut [f32]) {
@@ -832,13 +897,15 @@ struct TableRows<'a> {
edges: Vec<f32>,
x: f32,
total: f32,
/// Only this row (and the room under its top for its merged cells), when set.
only: Option<(usize, f32)>,
}
/// Place the laid-out cells of every row: vertical alignment, turned text, borders and the cell
/// rectangles, clipped where the row's exact height or a fixed table's column is too small for
/// the cell's text.
fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout {
let TableRows { story, table: t, path, depth, cell_text, rows, heights, bottoms, edges, x, total } = input;
let TableRows { story, table: t, path, depth, cell_text, rows, heights, bottoms, edges, x, total, only } = input;
// Grid columns holding a vertical-merge continuation, per row.
let cont: Vec<Vec<usize>> = t
.rows
@@ -858,6 +925,9 @@ fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout {
// Second pass: place cells with their row height, fills and borders.
let mut out = Vec::with_capacity(rows.len());
for (ri, cells) in rows.into_iter().enumerate() {
if only.is_some_and(|(row, _)| row != ri) {
continue;
}
let rh = heights.get(ri).copied().unwrap_or(0.0);
let exact = t.rows.get(ri).is_some_and(|r| r.props.height_rule == HeightRule::Exact && r.props.height.is_some_and(|h| h > 0.0));
let mut items = Vec::new();
@@ -898,10 +968,16 @@ fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout {
_ => None,
})
.fold(c.h, f32::max);
// A merged cell's text is drawn with its restart row, even when the merge runs on
// over later pages: only the room left on the page it starts on can align it.
let align_span = match only {
Some((_, room)) if c.vmerge == VMerge::Restart => span_h.min(room.max(0.0)),
_ => span_h,
};
let mut dy = match c.valign {
VAlign::Top => 0.0,
VAlign::Center => ((span_h - align_h) / 2.0).max(0.0),
VAlign::Bottom => (span_h - align_h).max(0.0),
VAlign::Center => ((align_span - align_h) / 2.0).max(0.0),
VAlign::Bottom => (align_span - align_h).max(0.0),
};
let end = (c.vmerge != VMerge::Continue && c.turned.is_none()).then_some(c.end + dy);
let mut cell_items = c.items;
@@ -909,7 +985,7 @@ fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout {
dy = 0.0;
let m = c.margins;
// The lines run the cell's whole height (laid out again if the row grew).
let len = (span_h - (c.h - tn.len)).clamp(4.0, TURNED_LIMIT);
let len = (align_span - (c.h - tn.len)).clamp(4.0, TURNED_LIMIT);
let mut across = tn.across;
if (len - tn.len).abs() > 0.01
&& let Some(cell) = t.rows.get(ri).and_then(|r| r.cells.get(tn.ci))
+30 -11
View File
@@ -2,7 +2,7 @@ use super::boxes::{BoxInput, clear_of_float_tables, layout_box};
use super::ctx::{Ctx, with_pct_base};
use super::floats::{WrapArea, align_in, body_wraps};
use super::flow::again;
use super::headers::{header_items_cap, header_table_areas, placed_cost};
use super::headers::{begins_section, header_items_cap, header_table_areas, placed_cost};
use super::notes::table_notes;
use super::page::{PageBuilder, PageFrame, page_frame};
use super::placed::Placed;
@@ -14,14 +14,14 @@ pub(crate) fn footer_table_wraps(ctx: &mut Ctx, pb: &PageBuilder) -> Vec<WrapAre
return Vec::new();
}
let Some(page) = pb.pages.last() else { return Vec::new() };
let first = pb.pages.iter().rev().nth(1).is_none_or(|prev| prev.section != page.section);
let hf = Arc::clone(&ctx.hf);
let first = begins_section(&hf.sections, pb.pages.iter().rev().nth(1), page);
let key = (page.section, page.number, first);
if let Some(areas) = ctx.footer_wraps.get(&key) {
return areas.clone();
}
ctx.footer_wraps.insert(key, Vec::new());
let doc = ctx.doc;
let hf = Arc::clone(&ctx.hf);
let Some((_, sect)) = hf.sections.get(page.section) else { return Vec::new() };
if sect.text_direction.is_turned() {
return Vec::new();
@@ -73,6 +73,8 @@ pub(crate) fn footer_table_wraps(ctx: &mut Ctx, pb: &PageBuilder) -> Vec<WrapAre
/// The room a table in the text needs to start on a page: its repeated header rows and the least
/// room its first row can start in (whole, or the part of it that splits off). A paragraph kept
/// with the table goes over with it when that much is not left, as in Word.
/// Before Word 2013 layout (compatibility mode 15) the header rows may stay alone at the foot of a
/// page, so the paragraph keeps with them only.
pub(crate) fn table_start_need(ctx: &mut Ctx, t: &wordcraft_doc::Table, block: usize, width: f32) -> f32 {
// A look ahead: list and equation numbers in the cells don't count yet.
let (counters, eq_count) = (ctx.counters.clone(), ctx.eq_count);
@@ -80,6 +82,10 @@ pub(crate) fn table_start_need(ctx: &mut Ctx, t: &wordcraft_doc::Table, block: u
(ctx.counters, ctx.eq_count) = (counters, eq_count);
let headers = t.rows.iter().take_while(|r| r.props.header).count();
let head: f32 = tl.rows.iter().take(headers).map(|r| r.height).sum();
if headers > 0 && ctx.doc.settings.compat_mode < wordcraft_doc::COMPAT_MODE_CURRENT {
// With the border below the last of them, as `place_table` places them.
return head + tl.rows.get(headers - 1).map_or(0.0, |r| r.edge);
}
let (Some(row), Some(laid)) = (t.rows.get(headers), tl.rows.get(headers)) else { return head };
// ponytail: bisection assumes starting a row gets no harder with more room.
let (mut lo, mut hi) = (0.0f32, laid.height + laid.edge);
@@ -201,8 +207,9 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc
let mut tl = table::layout_table(ctx, StoryRef::Body, t, &[block as u32], width, 1);
if let Some(f) = t.props.float.filter(|_| !pb.web) {
// Before Word 2013 layout (compatibility mode 15) an offset places the first cell's text,
// so the edge sits a cell margin further out.
let legacy = if ctx.doc.settings.compat_mode < 15 { table::first_cell_left_margin(ctx, t) } else { 0.0 };
// so the edge sits a cell margin further out (and the indent further); from it the edge,
// half its border in.
let legacy = table::float_offset_shift(ctx, t);
let h: f32 = tl.rows.iter().map(|r| r.height).sum();
if h <= pb.uncapped_bottom() - pb.top + 0.01 {
place_floating_table(ctx, pb, &tl, &f, legacy, block, body_top);
@@ -259,9 +266,11 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc
t.rows.get(ri).is_some_and(|r| r.props.height_rule == HeightRule::AtLeast && r.props.height.is_some_and(|h| h > room + 0.01))
};
// Like Word, repeated header rows don't stay alone at the bottom of a page: when the first row
// after them can't start under them there, the table starts on the next page.
// after them can't start under them there, the table starts on the next page. Before Word
// 2013 layout (compatibility mode 15) they do (measured in modes 12 and 14).
let first = header_rows.len();
if !header_rows.is_empty()
&& ctx.doc.settings.compat_mode >= wordcraft_doc::COMPAT_MODE_CURRENT
&& !pb.at_top()
&& let Some(row) = tl.rows.get(first)
{
@@ -288,13 +297,22 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc
.get(ri)
.is_some_and(|r| r.props.cant_split && !(r.props.height_rule == HeightRule::Exact && r.props.height.is_some_and(|h| h > 0.0)));
let mut rest: Option<table::RowLayout> = None;
// The row laid out again for where it lands, when a merge starting in it runs past the
// end of that page (its text is drawn with this row, so it can't be aligned below it).
let mut aligned: Option<table::RowLayout> = None;
let merge_rows = table::merge_rows_after(t, ri);
let merge_h: f32 = tl.rows.iter().skip(ri).take(merge_rows + 1).map(|r| r.height).sum();
// On a new page holding only the repeated header rows.
let mut fresh = false;
// Nothing but this table's header rows above it on a page it started at the top of.
let under_top_headers = ri == first && table_at_top;
// Each pass places the part of the row that fits, then breaks the page.
for _ in 0..1000 {
let cur = rest.as_ref().unwrap_or(row);
if rest.is_none() && merge_rows > 0 {
let room = (pb.bottom - pb.y).max(0.0);
aligned = (merge_h > room + 0.01).then(|| table::layout_table_row_in(ctx, t, &[block as u32], width, ri, room)).flatten();
}
let cur = rest.as_ref().or(aligned.as_ref()).unwrap_or(row);
// A fitting kept row follows the next row when that row cannot start below it.
// Move only the prefix's start; an oversized follower cannot separate its kept rows.
let defer_kept = pb.y + cur.height <= pb.bottom + 0.01
@@ -351,7 +369,7 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc
}
fresh = true;
}
let last = rest.as_ref().unwrap_or(row);
let last = rest.as_ref().or(aligned.as_ref()).unwrap_or(row);
place(pb, last);
table_notes(ctx, pb, &last.items);
}
@@ -383,11 +401,12 @@ fn place_floating_table(ctx: &mut Ctx, pb: &mut PageBuilder, tl: &table::TableLa
let x = float_table_x(pb, w, f, legacy, ctx.mirror);
let mut obstacles = if f.overlap { Vec::new() } else { header_table_areas(ctx, pb) };
obstacles.extend_from_slice(&pb.float_tables);
// Moved below another, it keeps its distance from the text's edge, half its border in.
let r = clear_of_float_tables(
Rect::new(x, align_in(v_area, f.y, h, f.v_align), w, h),
f,
ctx.doc.settings.compat_mode >= 15,
h_area.0,
h_area.0 - legacy,
&obstacles,
);
// Like Word, a table that doesn't fit below the text before it moves to the next page with
@@ -468,8 +487,8 @@ fn float_table_h_area(pb: &PageBuilder, f: &TableFloat, mirror: bool) -> (f32, f
}
}
/// A floating table's left edge on the page (`legacy`: the first cell's left margin before Word
/// 2013 layout, when an offset places the cell's text).
/// A floating table's left edge on the page (`legacy`: how far left of an offset its edge stands,
/// [`table::float_offset_shift`]).
fn float_table_x(pb: &PageBuilder, w: f32, f: &TableFloat, legacy: f32, mirror: bool) -> f32 {
let align = PageFrame::h_align(Some(&page_frame(pb, mirror)), f.h_align);
let x = align_in(float_table_h_area(pb, f, mirror), f.x, w, align);
File diff suppressed because it is too large Load Diff
+66
View File
@@ -133,6 +133,72 @@ fn spaces_punctuation_hangul_and_latin_alone_get_nothing() {
}
}
/// Word adds no automatic space, on either side, beside an ideograph whose run names an installed
/// East Asian font without ideographs, even though a substituted face draws it (#6591: 0.00 pt
/// with `w:eastAsia="Times New Roman"`). A font that isn't installed keeps the space.
#[test]
fn an_east_asian_font_without_ideographs_turns_it_off() {
crate::test_fonts();
let with = |latin: Option<&str>, asian: &str| {
let mut d = Document::from_text("法院94年A字");
let p = para0(&mut d);
let len = p.text.len();
p.format(0, len, &|c: &mut CharProps| {
c.font = latin.map(str::to_string);
c.font_ea = Some(asian.to_string());
})
.unwrap();
d
};
// Source Serif 4 is installed for the tests and has no ideographs.
for d in [with(None, "Source Serif 4"), with(Some("Source Serif 4"), "Source Serif 4")] {
assert!(gaps(&d).iter().all(|g| *g == 0.0), "{:?}", gaps(&d));
}
let d = with(None, "No Such East Asian Font 6591");
let q = quarter(&d);
// The room after each Latin character follows the face that draws it, as without a
// `w:eastAsia` font at all (#6583).
assert_eq!(gaps(&d), [0.0, q, 0.0, after(&d, 7), q, after(&d, 11), 0.0], "a font that isn't installed");
}
/// A `w:eastAsiaTheme` slot on a style or run takes precedence over an inherited named East Asian
/// font (`w:eastAsia`) without ideographs: Word draws the ideographs in the theme face instead, so
/// it still keeps the automatic space unless the theme slot itself names an installed font without
/// ideographs. Conversely, a named `w:eastAsia` on a run replaces an inherited theme slot.
#[test]
fn east_asian_theme_slot_overrides_inherited_named_font() {
crate::test_fonts();
use wordcraft_doc::props::ThemeFont;
// Base default names an installed font without ideographs (`Source Serif 4`).
// A style or run setting `minorEastAsia` overrides it: with no non-CJK `a:ea` face, spaces stay.
let mut d = Document::from_text("法院94年A字");
Arc::make_mut(&mut d.styles).default_chr.font_ea = Some("Source Serif 4".to_string());
let len = para0(&mut d).text.len();
para0(&mut d).format(0, len, &|c: &mut CharProps| c.font_ea_theme = Some(ThemeFont::MinorEastAsia)).unwrap();
let q = quarter(&d);
assert_eq!(gaps(&d), [0.0, q, 0.0, after(&d, 7), q, after(&d, 11), 0.0], "theme slot overrides inherited font_ea");
// When the theme's `a:ea` face (in `wordcraft:theme.fonts`) itself is an installed font without
// ideographs, the space is suppressed.
let mut themed_no_cjk = d.clone();
themed_no_cjk.passthrough.insert("wordcraft:theme.fonts".into(), Arc::new(b"minor\tface\tea\tSource Serif 4\n".to_vec()));
assert!(gaps(&themed_no_cjk).iter().all(|g| *g == 0.0), "theme a:ea without ideographs: {:?}", gaps(&themed_no_cjk));
// A Latin theme slot (`minorHAnsi`) resolves to `settings.minor_font`: if installed and lacking
// ideographs, it also suppresses the space.
let mut latin_slot = d.clone();
latin_slot.settings.minor_font = "Source Serif 4".to_string();
para0(&mut latin_slot).format(0, len, &|c: &mut CharProps| c.font_ea_theme = Some(ThemeFont::MinorHAnsi)).unwrap();
assert!(gaps(&latin_slot).iter().all(|g| *g == 0.0), "Latin theme slot without ideographs: {:?}", gaps(&latin_slot));
// A named `w:eastAsia` without `w:eastAsiaTheme` on a run overrides an inherited theme slot.
let mut overridden = Document::from_text("法院94年A字");
Arc::make_mut(&mut overridden.styles).default_chr.font_ea_theme = Some(ThemeFont::MinorEastAsia);
para0(&mut overridden).format(0, len, &|c: &mut CharProps| c.font_ea = Some("Source Serif 4".to_string())).unwrap();
assert!(gaps(&overridden).iter().all(|g| *g == 0.0), "named font_ea overrides inherited theme slot: {:?}", gaps(&overridden));
}
#[test]
fn a_field_result_is_classed_by_the_text_it_shows() {
crate::test_fonts();
+2 -1
View File
@@ -106,7 +106,8 @@ fn cell_letterhead_pulls_an_outside_picture_to_the_outer_left_edge() {
}
}
/// Confinement follows the particular cell, including asymmetric margins mirrored for RTL.
/// Confinement follows the particular cell, including asymmetric margins and RTL column
/// mirroring (cell margins themselves stay on the sides they name).
#[test]
fn cell_float_outer_edges_include_asymmetric_and_mirrored_margins() {
for rtl in [false, true] {
+154
View File
@@ -0,0 +1,154 @@
//! A combining mark the face of its character can't draw (#7865): the character and its marks are
//! drawn together in a face that has them all (CSS Fonts 4 §5.3, cluster matching), and with no
//! such face the mark on its own from a face that has it, except in right-to-left and
//! complex-script text, where it stays with its letter. Marks the face draws and pairs it composes
//! stay with their character. Fixed test fonts: Source Serif 4 lacks U+0336 and U+0338; Source
//! Sans 3 has U+0338; only JetBrains Mono has U+0336.
use std::sync::Arc;
use wordcraft_doc::{CharProps, Document, Paragraph, para_block};
use wordcraft_fonts::{FaceRef, FontDb};
use super::lay;
use super::linear::assert_linear_steps;
use crate::display::DisplayOptions;
use crate::{ParaLayout, Placed};
const SERIF: &str = "Source Serif 4";
fn serif() -> FaceRef {
crate::test_fonts();
let face = wordcraft_fonts::word::resolve(SERIF, false, false).face;
assert_eq!(face.family, SERIF, "the fixed test fonts include {SERIF}");
face
}
/// A document of one paragraph, `text` set in Source Serif 4; `cs`: with complex-script
/// formatting (`w:cs`), its complex-script font Source Serif 4 too.
fn doc(text: &str, cs: bool) -> Document {
let chr = CharProps { font: Some(SERIF.into()), font_cs: Some(SERIF.into()), cs: Some(cs), size: Some(12.0), ..Default::default() };
let mut d = Document::new();
d.body = vec![para_block(Paragraph::with_text(text, chr))];
d
}
/// [`doc`] laid out: its paragraph and the characters drawn as missing glyphs.
fn laid(text: &str, cs: bool) -> (Arc<ParaLayout>, Vec<char>) {
laid_doc(&doc(text, cs))
}
/// `d`, a document of one paragraph, laid out: the paragraph and the characters drawn as missing
/// glyphs.
fn laid_doc(d: &Document) -> (Arc<ParaLayout>, Vec<char>) {
crate::test_fonts();
let l = lay(d);
let missing = l.missing_glyphs(d, &DisplayOptions::default(), None).chars.iter().map(|(c, _)| *c).collect();
let para = l
.pages
.iter()
.flat_map(|p| &p.items)
.find_map(|it| match it {
Placed::Lines { para, .. } => Some(para.clone()),
_ => None,
})
.expect("the paragraph is laid out");
(para, missing)
}
/// The face that draws the character at byte `at` of the paragraph.
fn face_at(para: &ParaLayout, at: usize) -> FaceRef {
let c = para.clusters.iter().find(|c| c.start <= at && at < c.end).expect("a cluster holds the character");
para.styles[c.style as usize].face
}
#[test]
fn a_mark_its_letters_font_lacks_goes_with_its_letter_to_a_face_that_has_both() {
let serif = serif();
let (letter, mark) = ('∞', '\u{338}');
assert!(serif.covers(letter) && !serif.covers(mark), "{SERIF} has {letter} and lacks U+0338");
let text = format!("x {letter}{mark} y");
let (para, missing) = laid(&text, false);
assert!(missing.is_empty(), "nothing is drawn as a missing glyph, but {missing:?} were");
let at = text.find(letter).expect("the letter is in the text");
let face = face_at(&para, at);
assert_eq!(face.id(), face_at(&para, at + letter.len_utf8()).id(), "the letter and its mark are drawn in one face");
assert!(face.covers(letter) && face.covers(mark), "that face has both");
assert_eq!(face_at(&para, 0).id(), serif.id(), "the text before stays in the run's font");
assert_eq!(face_at(&para, text.len() - 1).id(), serif.id(), "the text after goes back to the run's font");
}
/// In small capitals a mark is set at the size of the lower-case letter it belongs to, so the
/// letter and its marks still go together to a face that has them all, also when the run's font has
/// the first mark and lacks the second.
#[test]
fn in_small_capitals_a_letter_and_its_marks_go_together_to_a_face_that_has_them_all() {
let serif = serif();
let (letter, has, lacks) = ('x', '\u{301}', '\u{336}');
assert!(serif.covers(letter) && serif.covers(has) && !serif.covers(lacks), "{SERIF} has x and U+0301 and lacks U+0336");
let text: String = [letter, has, lacks].iter().collect();
let chr = CharProps { font: Some(SERIF.into()), size: Some(12.0), small_caps: Some(true), ..Default::default() };
let mut d = Document::new();
d.body = vec![para_block(Paragraph::with_text(&text, chr))];
let (para, missing) = laid_doc(&d);
assert!(missing.is_empty(), "nothing is drawn as a missing glyph, but {missing:?} were");
let style_at = |at: usize| para.clusters.iter().find(|c| c.start <= at && at < c.end).expect("a cluster holds the character").style;
let face = face_at(&para, 0);
assert!(face.covers(lacks), "the letter is drawn in a face that has U+0336");
for (at, c) in text.char_indices().skip(1) {
assert_eq!(face_at(&para, at).id(), face.id(), "U+{:04X} is drawn in its letter's face", c as u32);
assert_eq!(style_at(at), style_at(0), "U+{:04X} is set at its letter's size", c as u32);
}
}
#[test]
fn a_mark_the_font_composes_with_its_letter_stays_in_the_run_font() {
let serif = serif();
// The font has no U+0338, but the shaper draws = with it as ≠, which the font has.
assert!(!serif.covers('\u{338}') && serif.covers('≠'), "{SERIF} lacks U+0338 and has ≠");
let text = "x =\u{338} y";
let (para, missing) = laid(text, false);
assert!(missing.is_empty(), "nothing is drawn as a missing glyph, but {missing:?} were");
for (at, c) in text.char_indices() {
assert_eq!(face_at(&para, at).id(), serif.id(), "U+{:04X} stays in the run's font", c as u32);
}
}
#[test]
fn a_mark_no_face_draws_with_its_letter_is_drawn_from_a_face_that_has_it() {
let serif = serif();
let (letter, mark) = ('ǹ', '\u{336}');
let db = FontDb::global();
assert!(serif.covers(letter) && !serif.covers(mark), "{SERIF} has {letter} and lacks U+0336");
assert!(db.fallback_for_run(&[letter, mark], serif.id(), false, false).is_none(), "no face has both");
assert!(db.fallback_for(mark, serif.id()).is_some(), "a face has U+0336");
let text = format!("{letter}{mark}");
let (para, missing) = laid(&text, false);
assert!(missing.is_empty(), "the mark is drawn, but {missing:?} were missing glyphs");
assert_eq!(face_at(&para, 0).id(), serif.id(), "the letter stays in the run's font");
assert!(face_at(&para, letter.len_utf8()).covers(mark), "the mark comes from a face that has it");
}
/// In complex-script text a mark no face draws with its letter stays in the letter's face, so it is
/// never split from its letter (Arabic harakat would lose their place on it).
#[test]
fn in_complex_script_text_a_mark_no_face_draws_with_its_letter_stays_with_it() {
let serif = serif();
let (letter, mark) = ('ǹ', '\u{336}');
assert!(FontDb::global().fallback_for_run(&[letter, mark], serif.id(), false, false).is_none(), "no face has both");
let (para, _) = laid(&format!("{letter}{mark}"), true);
assert_eq!(face_at(&para, 0).id(), serif.id(), "the letter stays in the run's font");
assert_eq!(face_at(&para, letter.len_utf8()).id(), serif.id(), "the mark stays with its letter");
}
/// A letter followed by many marks no face draws with it, in complex-script text, where they stay
/// with it: their cluster is matched once, not again at every mark, which made the layout quadratic
/// in their number.
#[test]
fn a_long_run_of_marks_after_one_letter_lays_out_in_linear_time() {
let serif = serif();
let (letter, mark) = ('ǹ', '\u{336}');
assert!(FontDb::global().fallback_for_run(&[letter, mark], serif.id(), false, false).is_none(), "no face has both");
let text = |n: usize| std::iter::once(letter).chain(std::iter::repeat_n(mark, n)).collect::<String>();
assert_linear_steps("marks after one letter", 200, |n| doc(&text(n), true), |d| drop(std::hint::black_box(lay(d))));
}
+37
View File
@@ -3,6 +3,7 @@
#[allow(unused_imports)]
use crate::*;
use wordcraft_doc::Pos;
use wordcraft_doc::props::LineSpacing;
use wordcraft_doc::section::{DocGrid, DocGridType};
@@ -97,3 +98,39 @@ fn character_grid_places_east_asian_text_on_the_pitch() {
}
}
}
#[test]
fn an_exact_character_grid_line_fits_all_its_cells_with_kerning() {
crate::test_fonts();
let text = "AVAVAVAVAVAVAVAVAVAV";
let mut grid = with_grid(text, DocGridType::SnapToChars, 0);
let styles = std::sync::Arc::make_mut(&mut grid.styles);
styles.default_chr.font = Some("Inter".into());
styles.default_chr.kern = Some(1.0);
let set_width = |doc: &mut Document, width: f32| {
let indent = doc.last_section.text_width() - width;
doc.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| p.indent_right = Some(indent)).unwrap();
};
// In proportional text the fifth letter still needs its unkerned width at a line break.
let mut plain = grid.clone();
plain.last_section.doc_grid = None;
let wide = lay(&plain);
let para = wide.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
let paired: f32 = para.clusters[..5].iter().map(|c| c.adv).sum();
let kern = para.clusters[4].kern;
assert!(kern < -0.02, "the test font must kern the pair across the break");
set_width(&mut plain, paired - kern / 2.0);
assert_eq!(super::body_lines(&lay(&plain), text)[0], "AVAV");
let size = para::Grid::of(&grid, &grid.last_section).font_size;
grid.last_section.doc_grid.as_mut().unwrap().char_space = DocGrid::char_space_for(20.0, size);
let pitch = grid.last_section.grid_char_pitch(size).unwrap();
set_width(&mut grid, 5.0 * pitch);
for kern in [0.0, 1.0] {
std::sync::Arc::make_mut(&mut grid.styles).default_chr.kern = Some(kern);
let got = super::body_lines(&lay(&grid), text);
assert_eq!(got[0], "AVAVA", "kerning threshold {kern}: {got:?}");
}
}
+14
View File
@@ -89,6 +89,20 @@ fn a_joined_paragraphs_drawings_are_relative_to_the_shared_line() {
assert!(boxed < alpha + 12.0, "the box's text at {boxed} is below the shared line at {alpha}");
}
#[test]
fn a_margin_anchored_frame_in_a_cell_joins_after_a_hidden_mark() {
let mut d = Document::from_text("Alpha\nOmega");
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().mark.hidden = Some(true);
d.para_mut(StoryRef::Body, &Path::top(1)).unwrap().props.frame =
Some(TextFrame { h_anchor: "page".into(), v_anchor: "margin".into(), ..Default::default() });
in_cell(&mut d);
let l = lay(&d);
let alpha = top_of(&l, &Path(vec![0, 0, 0, 0]));
let omega = top_of(&l, &Path(vec![0, 0, 0, 1]));
assert!((omega - alpha).abs() < 1.0, "framed paragraph should share hidden-mark line: {alpha} vs {omega}");
}
#[test]
fn a_text_frame_after_a_hidden_mark_is_not_joined() {
// A framed paragraph is placed apart, so it shares no line with the one before: its number is
+388
View File
@@ -0,0 +1,388 @@
//! A long word broken by letters: the letter ending the line is measured without its kerning
//! pair with the letter that goes on to the next line (Word, a line's width swept a twip at a
//! time: the letters before a broken kerning pair fit only where they fit on their own).
use super::*;
#[test]
fn a_word_broken_by_letters_ends_without_its_kerning_pair() {
let text = "AVAVAVAVAVAVAVAVAVAV";
let doc = |indent_right: f32| {
let mut d = Document::from_text(text);
Arc::make_mut(&mut d.styles).default_chr.kern = Some(1.0);
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| p.indent_right = Some(indent_right)).unwrap();
d
};
// The word on one line: the first five letters' width with the "AV" pair after the fifth
// and without it.
let l = lay(&doc(0.0));
let para = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para.clone()) } else { None }).unwrap();
let paired: f32 = para.clusters[..5].iter().map(|c| c.adv).sum();
let alone = paired - para.clusters[4].kern;
assert!(alone - paired > 0.1, "the test font kerns \"AV\": {paired} vs {alone}");
// A line between the two takes four letters, as in Word; with the pair it took five.
let got = body_lines(&lay(&doc(468.0 - (paired + alone) / 2.0)), text);
assert_eq!(got.first().map(String::as_str), Some("AVAV"), "{got:?}");
// A line as wide as the five letters alone takes them.
let got = body_lines(&lay(&doc(468.0 - alone - 0.004)), text);
assert_eq!(got.first().map(String::as_str), Some("AVAVA"), "{got:?}");
}
/// Inter under `family` (a 5-byte name) with its `GPOS` hidden and an old-style `kern` table
/// that kerns `(left, right)` by `units` (and nothing else): a shaper splits such a pair between
/// the two glyphs, half in the first one's advance and half in the second one's advance and offset.
fn legacy_kern_family(family: &'static str, left: char, right: char, units: i16) -> &'static str {
assert_eq!(family.len(), "Inter".len());
let inter = wordcraft_fonts::word::resolve("Inter", false, false).face;
let (a, v) = (inter.glyph_for(left) as u16, inter.glyph_for(right) as u16);
let src = inter.data().to_vec();
let u16_at = |d: &[u8], o: usize| u16::from_be_bytes([d[o], d[o + 1]]) as usize;
let u32_at = |d: &[u8], o: usize| u32::from_be_bytes([d[o], d[o + 1], d[o + 2], d[o + 3]]) as usize;
// The tables, `GPOS` renamed so no shaper reads it, and the new `kern` table.
let mut tables: Vec<([u8; 4], Vec<u8>)> = (0..u16_at(&src, 4))
.map(|i| {
let r = 12 + 16 * i;
let tag: [u8; 4] = src[r..r + 4].try_into().unwrap();
let tag = if &tag == b"GPOS" { *b"XPOS" } else { tag };
(tag, src[u32_at(&src, r + 8)..u32_at(&src, r + 8) + u32_at(&src, r + 12)].to_vec())
})
.collect();
let mut kern = Vec::new();
for x in [0u16, 1, 0, 20, 0x0001, 1, 6, 0, 0, a, v] {
kern.extend(x.to_be_bytes());
}
kern.extend(units.to_be_bytes());
tables.push((*b"kern", kern));
tables.sort_by_key(|t| t.0);
// The font file again: its header, the table records, then the tables (4-byte aligned).
let n = tables.len();
let mut data = src[..12].to_vec();
data[4..6].copy_from_slice(&(n as u16).to_be_bytes());
let mut at = 12 + 16 * n;
let mut body = Vec::new();
for (tag, t) in &tables {
data.extend(tag);
data.extend(0u32.to_be_bytes());
data.extend((at as u32).to_be_bytes());
data.extend((t.len() as u32).to_be_bytes());
body.extend(t);
while body.len() % 4 != 0 {
body.push(0);
}
at = 12 + 16 * n + body.len();
}
data.extend(body);
// The family name, in the name table's UTF-16 and single-byte records alike.
let name = tables.iter().take_while(|t| &t.0 != b"name").map(|t| t.1.len().div_ceil(4) * 4).sum::<usize>() + 12 + 16 * n;
let len = tables.iter().find(|t| &t.0 == b"name").map_or(0, |t| t.1.len());
let wide = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::<Vec<u8>>();
for (from, to) in [(wide("Inter"), wide(family)), (b"Inter".to_vec(), family.as_bytes().to_vec())] {
for i in name..name + len - from.len() {
if data[i..i + from.len()] == from[..] {
data[i..i + from.len()].copy_from_slice(&to);
}
}
}
wordcraft_fonts::FontDb::global().add_font(data);
family
}
/// A letter ending a line whose kerning pair with the letter before it the shaper split between
/// them keeps that pair: only its pair with the letter going on to the next line is dropped
/// (Word for Windows, a font with only an old-style `kern` table: "...3Vy" of a base64 token on
/// one line, where the "y" carrying half the "Vy" pair measured it wider and moved it on).
#[test]
fn a_letter_ending_a_line_keeps_its_pair_with_the_letter_before() {
crate::test_fonts();
let text = "AVAVAVAVAVAVAVAVAVAV";
let family = legacy_kern_family("Kernx", 'A', 'V', -300);
let doc = |indent_right: f32| {
let mut d = Document::from_text(text);
let st = Arc::make_mut(&mut d.styles);
st.default_chr.kern = Some(1.0);
st.default_chr.font = Some(family.into());
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| p.indent_right = Some(indent_right)).unwrap();
d
};
let l = lay(&doc(0.0));
let para = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para.clone()) } else { None }).unwrap();
// "AVAVAV" on a line: the "AV" pairs in it kerned, the "VA" after it not kerned at all.
let six: f32 = para.clusters[..6].iter().map(|c| c.adv).sum();
assert!(para.clusters[0].kern < -0.5, "the test font kerns \"AV\": {}", para.clusters[0].kern);
let got = body_lines(&lay(&doc(468.0 - six - 0.004)), text);
assert_eq!(got.first().map(String::as_str), Some("AVAVAV"), "{got:?}");
}
/// A ligature's kerning pair with the letter after it belongs on the ligature's last cluster, not
/// on its head (#8618): a forced character wrap inside the ligature must not subtract the pair
/// after the whole ligature, and a line ending after the ligature drops that pair.
#[test]
fn a_ligatures_kerning_pair_sits_on_its_last_cluster() {
crate::test_fonts();
let text = "flYflYflYflY";
let doc = |indent_right: f32| {
let mut d = Document::from_text(text);
let st = Arc::make_mut(&mut d.styles);
st.default_chr.font = Some("Source Serif 4".into());
st.default_chr.size = Some(14.0);
st.default_chr.kern = Some(1.0);
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| p.indent_right = Some(indent_right)).unwrap();
d
};
let l = lay(&doc(0.0));
let para = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para.clone()) } else { None }).unwrap();
assert!(para.clusters[0].g1 > para.clusters[0].g0 && para.clusters[1].g1 == para.clusters[1].g0, "fixture forms an \"fl\" ligature");
assert_eq!(para.clusters[0].kern, 0.0, "the ligature's head cluster carries no kerning pair");
assert!(para.clusters[1].kern < -0.3, "the ligature's last cluster carries its pair with \"Y\": {}", para.clusters[1].kern);
assert_eq!(para.clusters[3].kern, 0.0);
let paired: f32 = para.clusters[..5].iter().map(|c| c.adv).sum();
let alone = paired - para.clusters[4].kern;
assert!(alone - paired > 0.3, "Source Serif 4 kerns \"fl\" + \"Y\": {paired} vs {alone}");
// Between paired and alone: "flYfl" fits only with its pair with "Y", so "fl" wraps whole.
let got = body_lines(&lay(&doc(468.0 - (paired + alone) / 2.0)), text);
assert_eq!(got.first().map(String::as_str), Some("flY"), "{got:?}");
// Wide enough for "flYfl" without the pair after it.
let got = body_lines(&lay(&doc(468.0 - alone - 0.004)), text);
assert_eq!(got.first().map(String::as_str), Some("flYfl"), "{got:?}");
// A three-letter ligature ("ffi") also puts its pair with "V" only on its last cluster.
let mut d3 = Document::from_text("ffiV");
let st3 = Arc::make_mut(&mut d3.styles);
st3.default_chr.font = Some("Source Serif 4".into());
st3.default_chr.size = Some(14.0);
st3.default_chr.kern = Some(1.0);
let l3 = lay(&d3);
let p3 = l3.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para.clone()) } else { None }).unwrap();
assert!(p3.clusters[0].g1 > p3.clusters[0].g0 && p3.clusters[1].g1 == p3.clusters[1].g0 && p3.clusters[2].g1 == p3.clusters[2].g0);
assert_eq!(p3.clusters[0].kern, 0.0);
assert_eq!(p3.clusters[1].kern, 0.0);
assert!(p3.clusters[2].kern < -0.2, "last cluster of \"ffi\" carries pair with \"V\": {}", p3.clusters[2].kern);
}
fn first_para(d: &Document) -> Arc<ParaLayout> {
lay(d).pages.into_iter().flat_map(|p| p.items).find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap()
}
#[test]
fn a_wrapped_line_end_caret_and_alignment_drop_the_line_end_pair() {
let text = "AVAVAVAVAVAVAVAVAVAV";
let doc = |indent_right: f32, align: Align| {
let mut d = Document::from_text(text);
Arc::make_mut(&mut d.styles).default_chr.kern = Some(1.0);
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| {
p.indent_right = Some(indent_right);
p.align = Some(align);
})
.unwrap();
d
};
let base = first_para(&doc(0.0, Align::Left));
let kern = base.clusters[4].kern;
assert!(kern < -0.1, "the test font kerns \"AV\": {kern}");
let paired: f32 = base.clusters[..5].iter().map(|c| c.adv).sum();
let alone = paired - kern;
let unkerned_last = base.clusters[4].adv - kern;
// Slight slack past the five unkerned letters so right and centre alignments move the line.
let slack = 6.0;
let indent_right = 468.0 - (alone + slack);
let left = first_para(&doc(indent_right, Align::Left));
let l0 = &left.lines[0];
assert_eq!(l0.c1, 5);
assert!((l0.end_x() - alone).abs() < 0.01, "end_x {} should match unkerned {alone}, not {paired}", l0.end_x());
assert!((left.x_of(0, l0.stop).unwrap() - alone).abs() < 0.01);
let right = first_para(&doc(indent_right, Align::Right));
let r0 = &right.lines[0];
assert_eq!(r0.c1, 5);
let r_end = r0.cl_left(4).unwrap() + unkerned_last;
assert!((r_end - r0.right).abs() < 0.01, "right-aligned unkerned end {r_end} should sit at right edge {}", r0.right);
let center = first_para(&doc(indent_right, Align::Center));
let c0 = &center.lines[0];
assert_eq!(c0.c1, 5);
let left_gap = c0.cl_left(0).unwrap() - c0.left;
let right_gap = c0.right - (c0.cl_left(4).unwrap() + unkerned_last);
assert!((left_gap - right_gap).abs() < 0.01, "centred gaps differ: left {left_gap} vs right {right_gap}");
}
#[test]
fn a_positive_kerning_pair_at_line_end_stays_inside_the_right_edge() {
crate::test_fonts();
let text = "AVAVAVAVAVAVAVAVAVAV";
let family = legacy_kern_family("Kernp", 'A', 'V', 300);
let doc = |indent_right: f32, align: Align| {
let mut d = Document::from_text(text);
let st = Arc::make_mut(&mut d.styles);
st.default_chr.kern = Some(1.0);
st.default_chr.font = Some(family.into());
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| {
p.indent_right = Some(indent_right);
p.align = Some(align);
})
.unwrap();
d
};
let base = first_para(&doc(0.0, Align::Left));
let kern = base.clusters[4].kern;
assert!(kern > 0.5, "the test font positively kerns \"AV\": {kern}");
let paired: f32 = base.clusters[..5].iter().map(|c| c.adv).sum();
let alone = paired - kern;
let unkerned_last = base.clusters[4].adv - kern;
let width = (paired + alone) / 2.0;
let indent_right = 468.0 - width;
let left = first_para(&doc(indent_right, Align::Left));
let l0 = &left.lines[0];
assert_eq!(l0.c1, 5);
assert!(l0.end_x() <= l0.right + 0.01, "end_x {} ran past right edge {}", l0.end_x(), l0.right);
assert!((l0.end_x() - alone).abs() < 0.01);
let right = first_para(&doc(indent_right, Align::Right));
let r0 = &right.lines[0];
assert_eq!(r0.c1, 5);
assert!(r0.cl_left(0).unwrap() > 0.01, "right-aligned line failed to shift right");
assert!((r0.cl_left(4).unwrap() + unkerned_last - r0.right).abs() < 0.01);
let center = first_para(&doc(indent_right, Align::Center));
let c0 = &center.lines[0];
assert_eq!(c0.c1, 5);
let left_gap = c0.cl_left(0).unwrap() - c0.left;
let right_gap = c0.right - (c0.cl_left(4).unwrap() + unkerned_last);
assert!(left_gap > 0.01 && (left_gap - right_gap).abs() < 0.01, "centred gaps: left {left_gap} vs right {right_gap}");
}
#[test]
fn a_justified_line_adjusts_spaces_without_the_line_end_pair() {
crate::test_fonts();
// Distributed alignment stretches gaps across clusters directly using `content_end`.
let text = "AVAVAVAVAVAVAVAVAVAV";
for (family, units) in [("Kerdn", -300i16), ("Kerdp", 300i16)] {
let family = legacy_kern_family(family, 'A', 'V', units);
let doc = |indent_right: f32| {
let mut d = Document::from_text(text);
let st = Arc::make_mut(&mut d.styles);
st.default_chr.kern = Some(1.0);
st.default_chr.font = Some(family.into());
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| {
p.indent_right = Some(indent_right);
p.align = Some(Align::Distribute);
})
.unwrap();
d
};
let base = first_para(&doc(0.0));
let kern = base.clusters[4].kern;
assert!((kern.signum() as i16) == units.signum(), "{family}: {kern}");
let paired: f32 = base.clusters[..5].iter().map(|c| c.adv).sum();
let alone = paired - kern;
let unkerned_last = base.clusters[4].adv - kern;
let width = if units < 0 { alone + 4.0 } else { (paired + alone) / 2.0 };
let para = first_para(&doc(468.0 - width));
let l0 = &para.lines[0];
assert_eq!(l0.c1, 5, "{family}: expected wrap after 5th letter");
assert!(l0.cl_left(4).unwrap() > base.clusters[..4].iter().map(|c| c.adv).sum::<f32>() + 0.01);
let end = l0.cl_left(4).unwrap() + unkerned_last;
assert!((end - l0.right).abs() < 0.01, "{family}: distributed end {end} should meet right edge {}", l0.right);
assert!((l0.end_x() - l0.right).abs() < 0.01);
}
// Justified line with spaces breaking mid-word (`word_wrap = false`): both stretching and
// shrinking adjust spaces against the unkerned line end.
let j_text = "a b AVAVAVAVAVAVAVAVAVAV";
for (family, units) in [("Kerjn", -300i16), ("Kerjp", 300i16)] {
let family = legacy_kern_family(family, 'A', 'V', units);
let doc = |indent_right: f32| {
let mut d = Document::from_text(j_text);
d.settings.compat_mode = wordcraft_doc::COMPAT_MODE_CURRENT;
let st = Arc::make_mut(&mut d.styles);
st.default_chr.kern = Some(1.0);
st.default_chr.font = Some(family.into());
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| {
p.indent_right = Some(indent_right);
p.align = Some(Align::Justify);
p.word_wrap = Some(false);
})
.unwrap();
d
};
let base = first_para(&doc(0.0));
// "a b AVAVA" is clusters 0..9; cluster 8 is 'A', cluster 9 is 'V'.
let kern = base.clusters[8].kern;
assert!((kern.signum() as i16) == units.signum(), "{family}: {kern}");
let paired: f32 = base.clusters[..9].iter().map(|c| c.adv).sum();
let alone = paired - kern;
let unkerned_a = base.clusters[8].adv - kern;
let width = if units < 0 { alone + 4.0 } else { (paired + alone) / 2.0 };
let para = first_para(&doc(468.0 - width));
let l0 = &para.lines[0];
assert_eq!(l0.c1, 9, "{family}: expected wrap after 9th cluster");
let space_w = l0.cl_left(2).unwrap() - l0.cl_left(1).unwrap();
assert!(space_w > base.clusters[1].adv + 0.01, "{family}: spaces should widen, got {space_w} vs {}", base.clusters[1].adv);
let end = l0.cl_left(8).unwrap() + unkerned_a;
assert!((end - l0.right).abs() < 0.01, "{family}: justified end {end} should meet right edge {}", l0.right);
assert!((l0.end_x() - l0.right).abs() < 0.01);
if units < 0 {
let shrunk = first_para(&doc(468.0 - (alone - 0.5)));
let s0 = &shrunk.lines[0];
assert_eq!(s0.c1, 9, "{family}: expected shrunk wrap after 9th cluster");
let s_space = s0.cl_left(2).unwrap() - s0.cl_left(1).unwrap();
assert!(s_space < base.clusters[1].adv - 0.01, "{family}: spaces should shrink, got {s_space} vs {}", base.clusters[1].adv);
let s_end = s0.cl_left(8).unwrap() + unkerned_a;
assert!((s_end - s0.right).abs() < 0.01, "{family}: shrunk end {s_end} should meet right edge {}", s0.right);
}
}
}
#[test]
fn auto_hyphenation_uses_the_unkerned_width_before_a_negative_pair() {
crate::test_fonts();
let text = "word consideration";
let family = legacy_kern_family("Kerhy", 'n', 's', -300);
let doc = |indent_right: f32| {
let mut d = Document::from_text(text);
d.settings.auto_hyphenation = true;
d.settings.hyphenation_zone = 0.0;
let st = Arc::make_mut(&mut d.styles);
st.default_chr.kern = Some(1.0);
st.default_chr.font = Some(family.into());
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| p.indent_right = Some(indent_right)).unwrap();
d
};
let base = first_para(&doc(0.0));
let k = *base
.hyph_after
.iter()
.find(|&&k| {
let i = k as usize;
text.get(base.clusters[i].start..base.clusters[i].end) == Some("n")
&& base.clusters.get(i + 1).and_then(|c| text.get(c.start..c.end)) == Some("s")
})
.expect("expected automatic hyphenation point at \"con-sideration\"");
let k = k as usize;
let kern = base.clusters[k].kern;
assert!(kern < -0.5, "the test font kerns \"ns\": {kern}");
let paired_no_hyph: f32 = base.clusters[..=k].iter().map(|c| c.adv).sum();
// Wide enough for "word con-" with room to spare so we can measure the hyphen advance.
let probe = first_para(&doc(468.0 - (paired_no_hyph + 12.0)));
assert_eq!(probe.lines[0].c1, k + 1);
let hyph_w = probe.lines[0].hyphen.expect("probe should hyphenate at \"con-\"").2;
let paired = paired_no_hyph + hyph_w;
let alone = paired - kern;
// Between the kerned and unkerned widths (plus hyphen): "con-" would overrun the margin
// once the "ns" pair is dropped, so the line must fall back to the earlier space.
let mid = first_para(&doc(468.0 - (paired + alone) / 2.0));
let m0 = &mid.lines[0];
assert!(m0.hyphen.is_none(), "hyphenated line {} overran right edge {}", m0.end_x(), m0.right);
assert_eq!(m0.stop, "word ".len(), "expected fallback to space break, got {:?}", &text[..m0.stop]);
// Wide enough for the unkerned letters plus hyphen: the break at "con-" fits inside the margin.
let fit = first_para(&doc(468.0 - (alone + 0.004)));
let f0 = &fit.lines[0];
assert_eq!(f0.c1, k + 1);
assert!(f0.hyphen.is_some());
assert!(f0.end_x() <= f0.right + 0.01, "end_x {} ran past right edge {}", f0.end_x(), f0.right);
assert!((f0.end_x() - alone).abs() < 0.01);
}
+64
View File
@@ -874,6 +874,70 @@ fn a_roman_page_number_in_the_footer_stays_roman_with_the_page_count_in_the_body
}
}
#[test]
fn a_multiple_spaced_lines_leading_may_run_past_a_footer_above_the_margin() {
// A footer reaching above the bottom margin: Word lets the leading of the page's last
// 1.5-spaced line run past its top as into the margin, only the text has to fit, whatever the
// footer holds. Word for Mac and Windows, a 1.5-spaced 12pt line pushed down by half a point:
// it stays while its text ends above the footer (up to 0.4pt above), with a one-line
// page-number footer above the margin by 6.6pt and by 28pt, with a four-line footer, and with
// an empty exact-height 120pt paragraph. Also when the footer is the first page's own (a title
// page footer, the other pages' footer short): the first page's footer counts there.
use wordcraft_doc::props::LineSpacing;
// (footer lines, their text, the title page's own footer, footer distance from the page bottom)
let cases: [(usize, &str, bool, Option<f32>); 4] =
[(1, "", false, None), (1, "", true, None), (1, "7", false, Some(72.0)), (4, "Footer line", false, None)];
for (lines, text, first, from_bottom) in cases {
let mut past_footer = 0;
for shift in (0..28).step_by(2) {
let mut d = Document::from_text(&"Several words wrap onto many lines of a long paragraph. ".repeat(60));
if let Some(wordcraft_doc::Block::Para(p)) = d.body.get_mut(0).map(Arc::make_mut) {
p.props.line_spacing = Some(LineSpacing::Multiple(1.5));
p.props.space_before = Some(shift as f32);
p.props.widow_control = Some(false);
}
let foot_paras = (0..lines)
.map(|_| {
let mut f = Paragraph::with_text(text, Default::default());
if text.is_empty() {
f.props.line_spacing = Some(LineSpacing::Exactly(120.0));
}
para_block(f)
})
.collect();
let id = d.add_part(PartKind::Footer, foot_paras);
if let Some(f) = from_bottom {
d.last_section.footer = f;
}
if first {
d.last_section.title_page = true;
d.last_section.footers.first = Some(id);
} else {
d.last_section.footers.default = Some(id);
}
let l = lay(&d);
let foot = l.pages[0].body.bottom();
let what = format!("footer of {lines} x {text:?}, shift {shift}");
assert!(foot < d.last_section.page_h - d.last_section.margin_bottom - 1.0, "{what}: the footer reaches above the margin: {foot}");
let Some(Placed::Lines { y, para, l0, l1, .. }) =
l.pages[0].items.iter().find(|i| matches!(i, Placed::Lines { story: StoryRef::Body, .. }))
else {
panic!("{what}: no body lines on page 1")
};
let (first, last, next) = (&para.lines[*l0], &para.lines[*l1 - 1], &para.lines[*l1]);
let top = y + last.top - first.top;
let text_end = top + (last.baseline - last.top) + last.text_desc;
assert!(text_end <= foot + 0.01, "{what}: the last line's text ends at {text_end}, below the footer at {foot}");
let next_text_end = top + last.height + (next.baseline - next.top) + next.text_desc;
assert!(next_text_end > foot + 0.01, "{what}: the next line's text would end at {next_text_end}, above the footer at {foot}");
if top + last.height > foot + 0.01 {
past_footer += 1;
}
}
assert!(past_footer > 0, "footer of {lines} x {text:?}: some shift should leave the last line's leading past the footer");
}
}
#[test]
fn a_page_ends_when_a_multiple_spaced_lines_text_no_longer_fits() {
// Multiple spacing puts its extra leading below the text, and Word lets that leading of a
@@ -0,0 +1,52 @@
//! A character Times New Roman's metric twin lacks ("‒", "₽" in Liberation Serif) is drawn from
//! a fallback face, but the line is as tall as the twin's: Times New Roman has those characters,
//! so Word's line is as tall as Times New Roman's, not the taller UI sans.
use crate::{Document, LayoutCache, LayoutOptions, Placed, layout};
/// Inter under the family name "Tinos" (a metric twin of Times New Roman), from the bundled font
/// so the test needs no installed font. Inter lacks "☐"; Source Sans 3 (the fallback) has it and
/// its line is taller (1.326 em against 1.21).
fn fake_tinos() -> &'static str {
const FAMILY: &str = "Tinos";
let inter = wordcraft_fonts::word::resolve("Inter", false, false).face;
assert!(!inter.covers('☐'));
let mut data = inter.data().to_vec();
let u16_at = |d: &[u8], o: usize| u16::from_be_bytes([d[o], d[o + 1]]) as usize;
let u32_at = |d: &[u8], o: usize| u32::from_be_bytes([d[o], d[o + 1], d[o + 2], d[o + 3]]) as usize;
let (name, len) = (0..u16_at(&data, 4))
.map(|i| 12 + 16 * i)
.find(|&r| &data[r..r + 4] == b"name")
.map(|r| (u32_at(&data, r + 8), u32_at(&data, r + 12)))
.unwrap();
let wide = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::<Vec<u8>>();
for (from, to) in [(wide("Inter"), wide(FAMILY)), (b"Inter".to_vec(), FAMILY.as_bytes().to_vec())] {
for i in name..name + len - from.len() {
if data[i..i + from.len()] == from[..] {
data[i..i + from.len()].copy_from_slice(&to);
}
}
}
wordcraft_fonts::FontDb::global().add_font(data);
FAMILY
}
fn line_height(text: &str, font: &str) -> f32 {
let chr = wordcraft_doc::CharProps { font: Some(font.into()), size: Some(14.0), ..Default::default() };
let mut d = Document::new();
d.body = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text(text, chr))];
let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default());
l.pages.iter().flat_map(|p| &p.items).find_map(|it| if let Placed::Lines { para, .. } = it { Some(para.lines[0].height) } else { None }).unwrap()
}
#[test]
fn a_twin_fallback_keeps_the_twins_line_height() {
crate::test_fonts();
let tinos = fake_tinos();
assert_eq!(wordcraft_fonts::word::resolve(tinos, false, false).face.family, tinos, "the test font is installed under its own name");
let plain = line_height("Aa", tinos);
let boxed = line_height("A☐a", tinos);
assert!((boxed - plain).abs() < 0.01, "a line with a fallback character is {boxed} pt, without it {plain} pt");
// Other fonts keep the fallback's taller line.
assert!(line_height("A☐a", "Inter") > line_height("Aa", "Inter") + 1.0);
}
+8 -2
View File
@@ -107,6 +107,7 @@ fn write_attempt(doc: &Document, lay: &DocLayout, opts: &PdfOptions, pages: &[us
objects: crate::exporter::ObjectLookup::new(doc),
at: (0, 0),
links: Vec::new(),
last_link: None,
bookmarks: std::cell::OnceCell::new(),
};
if let Some(o) = ex.outline(pages) {
@@ -136,8 +137,13 @@ fn write_attempt(doc: &Document, lay: &DocLayout, opts: &PdfOptions, pages: &[us
}
}
surface.finish();
for annotation in annotations {
kp.add_annotation(annotation);
for (annotation, tag) in annotations {
if opts.tagged {
let annot_id = kp.add_tagged_annotation(annotation);
ex.attach_link_annotation(tag, annot_id);
} else {
kp.add_annotation(annotation);
}
}
kp.finish();
}
+107 -30
View File
@@ -3,7 +3,7 @@ use super::glyphs::{baseline, cluster_ends, glyph_id, glyph_outlines, left_to_ri
use super::options::{PdfError, PdfOptions};
use super::paint::{append_path, fill, grown, norm, ok, paint_fill, pdf_line_cap, rect_path, shape_effects, shape_path};
use super::picture::{Vector, build_vector, load_image, paint_of, vector_picture};
use super::tags::{Role, TagEntry, figure_alt, graphic_alt, holds_picture, holds_text};
use super::tags::{Role, TagEntry, build_tag_tree, figure_alt, graphic_alt, holds_picture, holds_text};
use super::{
Annotation, Arc, Artifact, ArtifactType, ClKind, ContentTag, DocLayout, DocPath, Document, Draw, FaceRef, Fill, FillRule, Font, HashMap, HashSet,
Identifier, Image, InlineObject, ItemDisplay, KrillaGlyph, LineCap, LineEnd, LineJoin, LineStyle, LinkAnnotation, Node, NonZeroU16, Outline,
@@ -18,6 +18,29 @@ mod objects;
pub(crate) use objects::ObjectLookup;
mod text;
/// Where a link annotation's `OBJR` attaches in the structure tree.
#[derive(Clone, Copy)]
pub(crate) enum LinkTag {
/// Inside an existing `Tag::Link` group at `(para, child)` in `Exporter::tags`, with
/// reading-order position `at` as fallback.
Group { para: usize, child: usize, at: (usize, usize) },
/// Outside any paragraph (for example a header or footer artifact), as its own `Link`
/// structure element placed at reading-order position `at`.
Standalone((usize, usize)),
}
pub(crate) struct LinkRect {
pub(crate) x0: f32,
pub(crate) y0: f32,
pub(crate) x1: f32,
pub(crate) y1: f32,
pub(crate) target: String,
/// `(para_idx, child_idx)` in `Exporter::tags` for this link's `Tag::Link` group.
pub(crate) tag: Option<(usize, usize)>,
/// Reading-order position ([`TagEntry::at`]) where this link was drawn.
pub(crate) at: (usize, usize),
}
pub(crate) struct Exporter<'a> {
pub(crate) doc: &'a Document,
pub(crate) lay: &'a DocLayout,
@@ -42,8 +65,10 @@ pub(crate) struct Exporter<'a> {
pub(crate) objects: ObjectLookup<'a>,
/// Where the item being drawn is read ([`TagEntry::at`]).
pub(crate) at: (usize, usize),
/// Link rectangles on the current page: (x0, y0, x1, y1, target).
pub(crate) links: Vec<(f32, f32, f32, f32, String)>,
/// Link rectangles on the current page.
pub(crate) links: Vec<LinkRect>,
/// Index in `links` touched by the most recent `Draw::Glyphs` item, if any.
pub(crate) last_link: Option<usize>,
/// Bookmark positions by name (the first of a name wins), gathered once: looking each internal
/// link up by walking the whole document made a long document with a linked table of contents
/// take seconds to export.
@@ -146,13 +171,14 @@ impl Exporter<'_> {
e.children.push(Node::Leaf(id));
}
}
Role::Figure => {
Role::Figure(source) => {
let id: Identifier = s.start_tagged(ContentTag::Other);
f(self, s);
s.end_tagged();
let alt = alt.map(str::to_string).filter(|a| !a.is_empty()).or_else(|| Some("picture".to_string()));
let g = TagGroup::with_children(Tag::Figure(alt), vec![Node::Leaf(id)]);
self.tags.push(TagEntry { kind: Tag::Div.into(), children: vec![Node::Group(g)], at: self.at });
let source = source.filter(|(_, p)| p.0.len() >= 4).map(|(st, p)| (st, p.clone()));
self.tags.push(TagEntry { kind: Tag::Div.into(), children: vec![Node::Group(g)], source, at: self.at });
}
}
}
@@ -160,7 +186,7 @@ impl Exporter<'_> {
/// A rotated inline picture or group: turned as a whole, with each picture in it tagged on its
/// own, so a decorative picture is an artifact while the others stay figures with their alt
/// text. A described shape's figure keeps its description; anything else is an artifact.
fn rotated_pictures(&mut self, s: &mut Surface, d: &Draw) {
fn rotated_pictures(&mut self, s: &mut Surface, d: &Draw, source: Option<(StoryRef, &DocPath)>) {
match d {
Draw::Rotated { cx, cy, spin, items } => {
if !ok(*cx) || !ok(*cy) {
@@ -169,7 +195,7 @@ impl Exporter<'_> {
let [a, b, c, d, e, f] = spin.matrix(*cx, *cy);
s.push_transform(&Transform::from_row(a, b, c, d, e, f));
for it in items {
self.rotated_pictures(s, it);
self.rotated_pictures(s, it, source);
}
s.pop();
}
@@ -178,13 +204,13 @@ impl Exporter<'_> {
let Some(clip) = rect_path(rect) else { return };
s.push_clip_path(&clip, &FillRule::NonZero);
for it in items {
self.rotated_pictures(s, it);
self.rotated_pictures(s, it, source);
}
s.pop();
}
Draw::Image { decorative: true, .. } => self.tagged(s, Role::Artifact(ArtifactType::Other), None, |me, s| me.draw(s, d)),
Draw::Image { alt, .. } => self.tagged(s, Role::Figure, Some(alt), |me, s| me.draw(s, d)),
Draw::Figure { alt, draws, .. } => self.tagged(s, Role::Figure, Some(alt), |me, s| {
Draw::Image { alt, .. } => self.tagged(s, Role::Figure(source), Some(alt), |me, s| me.draw(s, d)),
Draw::Figure { alt, draws, .. } => self.tagged(s, Role::Figure(source), Some(alt), |me, s| {
for d in draws {
me.draw(s, d);
}
@@ -193,24 +219,72 @@ impl Exporter<'_> {
}
}
/// Attach a paragraph's marked-content `id` to its `Tag::Link` group when `draw` recorded a
/// link rectangle, or directly to the paragraph entry otherwise.
fn attach_para_link(&mut self, idx: usize, id: Identifier) {
if let Some(li) = self.last_link.take()
&& let Some(link) = self.links.get_mut(li)
{
if let Some((p_idx, c_idx)) = link.tag
&& let Some(Node::Group(g)) = self.tags.get_mut(p_idx).and_then(|e| e.children.get_mut(c_idx))
{
g.push(Node::Leaf(id));
return;
}
if let Some(e) = self.tags.get_mut(idx) {
let c_idx = e.children.len();
e.children.push(Node::Group(TagGroup::with_children(Tag::Link, vec![Node::Leaf(id)])));
link.tag = Some((idx, c_idx));
return;
}
}
if let Some(e) = self.tags.get_mut(idx) {
e.children.push(Node::Leaf(id));
}
}
/// Attach a link annotation's `OBJR` identifier to its `Tag::Link` group, or add a standalone
/// `Div -> Link` entry holding just the `OBJR` when the link has no paragraph group (such as
/// a link drawn inside a header or footer artifact).
pub(crate) fn attach_link_annotation(&mut self, tag: LinkTag, annot_id: Identifier) {
if let LinkTag::Group { para, child, .. } = tag
&& let Some(Node::Group(g)) = self.tags.get_mut(para).and_then(|e| e.children.get_mut(child))
{
g.children.insert(0, Node::Leaf(annot_id));
return;
}
let at = match tag {
LinkTag::Group { at, .. } | LinkTag::Standalone(at) => at,
};
let g = TagGroup::with_children(Tag::Link, vec![Node::Leaf(annot_id)]);
self.tags.push(TagEntry { kind: Tag::Div.into(), children: vec![Node::Group(g)], source: None, at });
}
/// One draw of a paragraph's line, tagged for what it is: text as the paragraph's content
/// (structure entry `idx`), pictures and figures on their own, anything else an artifact.
fn line_item(&mut self, s: &mut Surface, d: &Draw, idx: usize) {
fn line_item(&mut self, s: &mut Surface, d: &Draw, idx: usize, story: StoryRef, path: &DocPath) {
match d {
Draw::Glyphs { link: Some(_), .. } if self.opts.tagged && self.opts.links => {
self.last_link = None;
let id = s.start_tagged(ContentTag::Span(SpanTag::empty()));
self.draw(s, d);
s.end_tagged();
self.attach_para_link(idx, id);
}
Draw::Glyphs { .. } | Draw::Turned { .. } => self.tagged(s, Role::Para(idx), None, |me, s| me.draw(s, d)),
// A picture marked decorative: an artifact screen readers skip.
Draw::Image { decorative: true, .. } => self.tagged(s, Role::Artifact(ArtifactType::Other), None, |me, s| me.draw(s, d)),
Draw::Image { alt, .. } => self.tagged(s, Role::Figure, Some(alt), |me, s| me.draw(s, d)),
Draw::Image { alt, .. } => self.tagged(s, Role::Figure(Some((story, path))), Some(alt), |me, s| me.draw(s, d)),
// A rotated inline picture, or a rotated group holding pictures: turned as a
// whole, each picture tagged on its own (see `rotated_pictures`).
Draw::Rotated { items, .. } if items.iter().any(holds_picture) => self.rotated_pictures(s, d),
Draw::Rotated { items, .. } if items.iter().any(holds_picture) => self.rotated_pictures(s, d, Some((story, path))),
// A clip (a turned picture cut at its line, an exact-height cell's lines, a canvas's
// members): each draw in it tagged as it would be outside it.
Draw::Clip { rect, items } => {
let Some(clip) = rect_path(rect) else { return };
s.push_clip_path(&clip, &FillRule::NonZero);
for it in items {
self.line_item(s, it, idx);
self.line_item(s, it, idx, story, path);
}
s.pop();
}
@@ -218,7 +292,7 @@ impl Exporter<'_> {
// without text falls to the artifacts below.
Draw::Rotated { items, .. } if items.iter().any(holds_text) => self.tagged(s, Role::Para(idx), None, |me, s| me.draw(s, d)),
// An inline chart, diagram or described shape: its text is part of the figure, not the paragraph.
Draw::Figure { alt, kind, draws: inner } => self.tagged(s, Role::Figure, Some(figure_alt(alt, *kind)), |me, s| {
Draw::Figure { alt, kind, draws: inner } => self.tagged(s, Role::Figure(Some((story, path))), Some(figure_alt(alt, *kind)), |me, s| {
for d in inner {
me.draw(s, d);
}
@@ -252,7 +326,17 @@ impl Exporter<'_> {
let dopts = self.opts.display_options();
// What the items share (the authors' colours, the clipped cells) is worked out once per page.
let shown = ItemDisplay::new(self.doc, page);
for it in page.header.iter().chain(page.footer.iter()) {
self.at.1 = 0;
for it in &page.header {
let draws = shown.draws(it, &dopts);
self.tagged(s, Role::Artifact(ArtifactType::Other), None, |me, s| {
for d in &draws {
me.draw(s, d);
}
});
}
self.at.1 = usize::MAX;
for it in &page.footer {
let draws = shown.draws(it, &dopts);
self.tagged(s, Role::Artifact(ArtifactType::Other), None, |me, s| {
for d in &draws {
@@ -261,13 +345,13 @@ impl Exporter<'_> {
});
}
for (i, it) in page.items.iter().enumerate() {
self.at.1 = page.reading.get(i).copied().unwrap_or(i);
self.at.1 = page.reading.get(i).copied().unwrap_or(i).saturating_add(1).min(usize::MAX - 1);
let draws = shown.draws(it, &dopts);
match it {
Placed::Lines { story, path, para, .. } => {
let idx = self.entry(*story, path, para);
for d in &draws {
self.line_item(s, d, idx);
self.line_item(s, d, idx, *story, path);
}
}
Placed::Image { story, path, off, .. } => {
@@ -276,7 +360,7 @@ impl Exporter<'_> {
let role = if obj.is_some_and(InlineObject::is_decorative) || *off == usize::MAX {
Role::Artifact(ArtifactType::Other)
} else {
Role::Figure
Role::Figure(Some((*story, path)))
};
let alt = match obj {
Some(InlineObject::Image { alt, .. }) => alt.clone(),
@@ -289,7 +373,7 @@ impl Exporter<'_> {
});
}
// A floating shape with a description: a figure (see `shape_figure_alt`).
Placed::Shape { alt, .. } if !alt.is_empty() => self.tagged(s, Role::Figure, Some(alt), |me, s| {
Placed::Shape { alt, .. } if !alt.is_empty() => self.tagged(s, Role::Figure(None), Some(alt), |me, s| {
for d in &draws {
me.draw(s, d);
}
@@ -299,7 +383,7 @@ impl Exporter<'_> {
Some(InlineObject::Graphic { alt, .. }) => graphic_alt(alt, graphic.kind).to_string(),
_ => graphic.kind.noun().to_string(),
};
self.tagged(s, Role::Figure, Some(&alt), |me, s| {
self.tagged(s, Role::Figure(Some((*story, path))), Some(&alt), |me, s| {
for d in &draws {
me.draw(s, d);
}
@@ -337,26 +421,19 @@ impl Exporter<'_> {
}
_ => Tag::P.into(),
};
self.tags.push(TagEntry { kind, children: Vec::new(), at: self.at });
self.tags.push(TagEntry { kind, children: Vec::new(), source: Some((story, path.clone())), at: self.at });
let i = self.tags.len() - 1;
self.tag_index.insert((story, path.clone()), i);
i
}
pub(crate) fn tag_tree(&mut self) -> TagTree {
let mut tree = TagTree::new().with_lang(self.doc.styles.default_chr.lang.clone());
// In reading order: a floating object drawn over the text after it is read after its
// anchor (#5534). The sort is stable, so what is read at one place keeps its order.
let mut tags = std::mem::take(&mut self.tags);
tags.sort_by_key(|e| e.at);
self.tag_index.clear();
for e in tags {
if e.children.is_empty() {
continue;
}
tree.push(TagGroup::with_children(e.kind, e.children));
}
tree
build_tag_tree(self.doc, tags)
}
/// The watermark text stretched over its box (Word's `v:textpath fitshape`): its advance across
+3 -1
View File
@@ -31,7 +31,9 @@ impl Exporter<'_> {
}
None => self.glyphs(s, face, *size, glyphs, paint, (text, ranges)),
}
if let Some(l) = link {
if self.opts.links
&& let Some(l) = link
{
self.link_rect(face, *size, glyphs, l);
}
}
+18 -16
View File
@@ -1,5 +1,5 @@
use super::{
Annotation, ClKind, DocPath, Exporter, Fit, HashMap, LineEnd, LinkAnnotation, Outline, OutlineNode, Placed, Point, StoryRef, Target,
Annotation, ClKind, DocPath, Exporter, Fit, HashMap, LineEnd, LinkAnnotation, LinkTag, Outline, OutlineNode, Placed, Point, StoryRef, Target,
XyzDestination, krilla, write,
};
@@ -53,24 +53,26 @@ impl Exporter<'_> {
None
}
pub(crate) fn annotations(&self, fit: Fit) -> Vec<Annotation> {
pub(super) fn link_target(&self, target: &str) -> Option<Target> {
if let Some(name) = target.strip_prefix('#') {
self.bookmark(name).map(|(page, x, y)| Target::Destination(XyzDestination::new(page, Point::from_xy(x, y)).into()))
} else {
// Unsafe targets (javascript:, file:, shares, other schemes) get no link; the text stays.
write::uri_target(target)
}
}
pub(crate) fn annotations(&self, fit: Fit) -> Vec<(Annotation, LinkTag)> {
let mut v = Vec::new();
for (x0, y0, x1, y1, target) in &self.links {
let ((x0, y0), (x1, y1)) = (fit.point(*x0, *y0), fit.point(*x1, *y1));
for link in &self.links {
let ((x0, y0), (x1, y1)) = (fit.point(link.x0, link.y0), fit.point(link.x1, link.y1));
let Some(rect) = krilla::geom::Rect::from_ltrb(x0, y0, x1, y1) else { continue };
let t = if let Some(name) = target.strip_prefix('#') {
match self.bookmark(name) {
Some((page, x, y)) => Target::Destination(XyzDestination::new(page, Point::from_xy(x, y)).into()),
None => continue,
}
} else {
// Unsafe targets (javascript:, file:, shares, other schemes) get no link; the text stays.
match write::uri_target(target) {
Some(t) => t,
None => continue,
}
let Some(t) = self.link_target(&link.target) else { continue };
let tag = match link.tag {
Some((para, child)) => LinkTag::Group { para, child, at: link.at },
None => LinkTag::Standalone(link.at),
};
v.push(Annotation::new_link(LinkAnnotation::new(rect, t), Some(target.clone())));
v.push((Annotation::new_link(LinkAnnotation::new(rect, t), Some(link.target.clone())), tag));
}
v
}
+23 -7
View File
@@ -158,25 +158,41 @@ impl Exporter<'_> {
}
}
/// Whether a link's `Link` group is still the last content of its paragraph, so more linked text
/// can join it without being read ahead of unlinked text drawn since. Untagged links always continue.
fn link_run_continues(&self, tag: Option<(usize, usize)>) -> bool {
match tag {
None => true,
Some((p, c)) => self.tags.get(p).is_some_and(|e| e.children.len() == c + 1),
}
}
pub(super) fn link_rect(&mut self, face: &FaceRef, size: f32, glyphs: &[(u32, f32, f32)], link: &str) {
let (Some(first), Some(last)) = (glyphs.first(), glyphs.last()) else { return };
let adv = face.advance(last.0) as f32 * size / face.upem.max(1.0) as f32;
let (x0, x1) = (first.1.min(last.1), first.1.max(last.1) + adv);
let (y0, y1) = (first.2 - size * 0.85, first.2 + size * 0.25);
if ![x0, x1, y0, y1].iter().all(|v| ok(*v)) {
if ![x0, x1, y0, y1].iter().all(|v| ok(*v)) || x0 >= x1 || y0 >= y1 {
return;
}
if self.link_target(link).is_none() {
return;
}
let continues = self.links.last().is_some_and(|prev| prev.at == self.at && self.link_run_continues(prev.tag));
if let Some(prev) = self.links.last_mut()
&& prev.4 == link
&& (prev.1 - y0).abs() < 0.5
&& x0 - prev.2 < size
&& prev.target == link
&& (prev.y0 - y0).abs() < 0.5
&& x0 - prev.x1 < size
&& continues
{
prev.0 = prev.0.min(x0);
prev.2 = prev.2.max(x1);
prev.x0 = prev.x0.min(x0);
prev.x1 = prev.x1.max(x1);
self.last_link = Some(self.links.len() - 1);
return;
}
if self.links.len() < 10_000 {
self.links.push((x0, y0, x1, y1, link.to_string()));
self.links.push(super::LinkRect { x0, y0, x1, y1, target: link.to_string(), tag: None, at: self.at });
self.last_link = Some(self.links.len() - 1);
}
}
+2 -2
View File
@@ -25,7 +25,7 @@
pub mod imposition;
use std::collections::{HashMap, HashSet};
use std::num::NonZeroU16;
use std::num::{NonZeroU16, NonZeroU32};
use std::sync::Arc;
use craft_metafile::{Picture, PlacedItem};
@@ -42,7 +42,7 @@ use krilla::outline::{Outline, OutlineNode};
use krilla::page::PageSettings;
use krilla::paint::{Fill, FillRule, LineCap, LineJoin, Stroke, StrokeDash};
use krilla::surface::Surface;
use krilla::tagging::{Artifact, ArtifactType, ContentTag, Identifier, Node, SpanTag, Tag, TagGroup, TagKind, TagTree};
use krilla::tagging::{Artifact, ArtifactType, ContentTag, Identifier, Node, SpanTag, TableHeaderScope, Tag, TagGroup, TagKind, TagTree};
use krilla::text::{Font, GlyphId, KrillaGlyph};
use wordcraft_doc::graphic::GraphicKind;
use wordcraft_doc::para::{InlineObject, ShapeKind};
+162 -4
View File
@@ -1,4 +1,4 @@
use super::{ArtifactType, Draw, GraphicKind, Node, TagKind};
use super::{ArtifactType, DocPath, Document, Draw, GraphicKind, Node, NonZeroU32, StoryRef, TableHeaderScope, Tag, TagGroup, TagKind, TagTree};
/// A chart's or diagram's alt text: its own, else what it is ("chart", "diagram").
pub(crate) fn graphic_alt(alt: &str, kind: GraphicKind) -> &str {
@@ -36,6 +36,8 @@ pub(crate) fn figure_alt(alt: &str, kind: Option<GraphicKind>) -> &str {
pub(crate) struct TagEntry {
pub(crate) kind: TagKind,
pub(crate) children: Vec<Node>,
/// Paragraph `(story, path)` this entry belongs to, used to nest table cell entries under `Table`/`TR`/`TH` or `TD`.
pub(crate) source: Option<(StoryRef, DocPath)>,
/// Where it is first read: the page (in the order pages are drawn) and the place there of
/// the item it came from (`Page::reading`). The tree is in this order, not the drawing order.
pub(crate) at: (usize, usize),
@@ -43,13 +45,169 @@ pub(crate) struct TagEntry {
/// What the content being drawn is, for tagging.
#[derive(Clone, Copy, PartialEq)]
pub(crate) enum Role {
pub(crate) enum Role<'a> {
/// Paragraph content of the structure entry at this index.
Para(usize),
/// Header/footer, decorations: not part of the structure.
Artifact(ArtifactType),
/// A floating picture (its own Figure).
Figure,
/// A figure (its own `Figure`), optionally anchored to `(story, path)`.
Figure(Option<(StoryRef, &'a DocPath)>),
}
enum StructNode {
Leaf(TagGroup),
Table(TableNode),
}
struct TableNode {
story: StoryRef,
path: DocPath,
rows: Vec<RowNode>,
}
struct RowNode {
index: usize,
cells: Vec<CellNode>,
}
struct CellNode {
index: usize,
children: Vec<StructNode>,
}
/// Build the PDF structure tree, nesting table cell entries under `Table` -> `TR` -> `TH` / `TD`.
pub(crate) fn build_tag_tree(doc: &Document, tags: Vec<TagEntry>) -> TagTree {
let mut roots = Vec::new();
for e in tags {
let group = (!e.children.is_empty()).then(|| TagGroup::with_children(e.kind, e.children));
match (e.source, group) {
// A blank cell still gets its TD/TH, so the row keeps every column's position.
(Some((story, path)), group) if path.0.len() >= 4 => insert_into_nodes(&mut roots, story, &path, group),
(_, Some(group)) => roots.push(StructNode::Leaf(group)),
_ => {}
}
}
let mut tree = TagTree::new().with_lang(doc.styles.default_chr.lang.clone());
for node in roots {
tree.push(into_tag_group(doc, node));
}
tree
}
fn insert_into_nodes(mut nodes: &mut Vec<StructNode>, story: StoryRef, path: &DocPath, group: Option<TagGroup>) {
let mut k = 0usize;
while k.saturating_add(3) < path.0.len() {
let Some(prefix) = path.0.get(..=k) else { break };
let Some(&row_raw) = path.0.get(k + 1) else { break };
let Some(&cell_raw) = path.0.get(k + 2) else { break };
let table_path = DocPath(prefix.to_vec());
let row_idx = row_raw as usize;
let cell_idx = cell_raw as usize;
let table_pos = nodes.iter().rposition(|n| matches!(n, StructNode::Table(t) if t.story == story && t.path == table_path));
let table_pos = match table_pos {
Some(pos) => pos,
None => {
nodes.push(StructNode::Table(TableNode { story, path: table_path, rows: Vec::new() }));
nodes.len() - 1
}
};
let Some(StructNode::Table(table)) = nodes.get_mut(table_pos) else { return };
let row_pos = match table.rows.binary_search_by_key(&row_idx, |r| r.index) {
Ok(pos) => pos,
Err(pos) => {
table.rows.insert(pos, RowNode { index: row_idx, cells: Vec::new() });
pos
}
};
let Some(row) = table.rows.get_mut(row_pos) else { return };
let cell_pos = match row.cells.binary_search_by_key(&cell_idx, |c| c.index) {
Ok(pos) => pos,
Err(pos) => {
row.cells.insert(pos, CellNode { index: cell_idx, children: Vec::new() });
pos
}
};
let Some(cell) = row.cells.get_mut(cell_pos) else { return };
nodes = &mut cell.children;
k = k.saturating_add(3);
}
if let Some(group) = group {
nodes.push(StructNode::Leaf(group));
}
}
fn into_tag_group(doc: &Document, node: StructNode) -> TagGroup {
match node {
StructNode::Leaf(g) => g,
StructNode::Table(t) => {
let doc_table = doc.table(t.story, &t.path);
// Only the unbroken run of header rows at the top of the table are headers, as layout
// counts them (`take_while(|r| r.props.header)`); a row marked as a header further down
// is a body row, so its cells get TD and not TH.
let header_rows = doc_table.map(|dt| dt.rows.iter().take_while(|r| r.props.header).count()).unwrap_or(0);
let row_nodes = t
.rows
.into_iter()
.map(|r| {
let doc_row = doc_table.and_then(|dt| dt.rows.get(r.index));
let is_header = r.index < header_rows;
let cell_nodes = r
.cells
.into_iter()
.map(|c| {
let doc_cell = doc_row.and_then(|dr| dr.cells.get(c.index));
let col_span = doc_cell.and_then(|dc| NonZeroU32::new(dc.span() as u32)).filter(|n| n.get() > 1);
let row_span =
doc_table.and_then(|dt| cell_row_span(dt, r.index, c.index)).and_then(NonZeroU32::new).filter(|n| n.get() > 1);
let tag: TagKind = if is_header {
Tag::TH(TableHeaderScope::Column).with_col_span(col_span).with_row_span(row_span).into()
} else {
Tag::TD.with_col_span(col_span).with_row_span(row_span).into()
};
let children = c.children.into_iter().map(|ch| Node::Group(into_tag_group(doc, ch))).collect();
Node::Group(TagGroup::with_children(tag, children))
})
.collect();
Node::Group(TagGroup::with_children(Tag::TR, cell_nodes))
})
.collect();
TagGroup::with_children(Tag::Table, row_nodes)
}
}
}
fn cell_row_span(table: &wordcraft_doc::Table, row_idx: usize, cell_idx: usize) -> Option<u32> {
let row = table.rows.get(row_idx)?;
let cell = row.cells.get(cell_idx)?;
if cell.props.vmerge != wordcraft_doc::props::VMerge::Restart {
return None;
}
let grid_col = row.first_grid().saturating_add(row.cells.get(..cell_idx)?.iter().map(wordcraft_doc::Cell::span).sum::<usize>());
let mut span = 1u32;
for next_row in table.rows.get(row_idx.saturating_add(1)..)? {
let mut g = next_row.first_grid();
let mut matched = false;
for nc in &next_row.cells {
if g == grid_col && nc.props.vmerge == wordcraft_doc::props::VMerge::Continue {
matched = true;
break;
}
g = g.saturating_add(nc.span());
if g > grid_col {
break;
}
}
if matched {
span = span.saturating_add(1);
} else {
break;
}
}
(span > 1).then_some(span)
}
#[cfg(test)]
+295
View File
@@ -1946,6 +1946,7 @@ fn bookmark_destination_is_the_page_of_its_start() {
objects: crate::exporter::ObjectLookup::new(&d),
at: (0, 0),
links: Vec::new(),
last_link: None,
bookmarks: std::cell::OnceCell::new(),
};
let (page, x, y) = ex.bookmark("target").unwrap();
@@ -3709,3 +3710,297 @@ fn chart_and_equation_text_keep_their_pdf_bytes() {
["B", "o", "d", "y", " ", "t", "e", "x", "R", "v", "n", "u", "2", "0", "4", "+", "1", equation_x].into_iter().map(String::from).collect();
assert_eq!(shown, expected, "math face: {}", math_face.family);
}
#[test]
fn tables_are_tagged_with_table_tr_th_and_td() {
use wordcraft_doc::{Cell, Row, Table, props::RowProps};
let mut d = Document::from_text("A table.");
let header = Row {
props: RowProps { header: true, ..Default::default() },
cells: vec![Cell::with_text("Head"), Cell::with_text("Col2")],
..Default::default()
};
let body = Row { cells: vec![Cell::with_text("Cell10"), Cell::with_text("Cell11")], ..Default::default() };
let t = Table { grid: vec![120.0, 120.0], rows: vec![header, body], ..Default::default() };
d.body.push(Arc::new(wordcraft_doc::Block::Table(t)));
let raw = String::from_utf8_lossy(&export(&d, &PdfOptions { tagged: true, compress: false, ..Default::default() }).unwrap()).into_owned();
assert!(raw.contains("/S/Table") || raw.contains("/S /Table"), "missing /S /Table in:\n{raw}");
assert!(raw.contains("/S/TR") || raw.contains("/S /TR"), "missing /S /TR in:\n{raw}");
assert!(raw.contains("/S/TH") || raw.contains("/S /TH"), "missing /S /TH in:\n{raw}");
assert!(raw.contains("/S/TD") || raw.contains("/S /TD"), "missing /S /TD in:\n{raw}");
assert!(raw.contains("/Scope/Column") || raw.contains("/Scope /Column"), "missing /Scope /Column on TH");
}
/// Only the run of header rows at the top of the table are headers, as layout counts them: a
/// header-flagged row further down is a body row, so its cells are TD and not TH.
#[test]
fn a_header_row_below_the_top_of_the_table_is_tagged_td() {
use wordcraft_doc::{Cell, Row, Table, props::RowProps};
let mut d = Document::from_text("A table.");
let header = Row {
props: RowProps { header: true, ..Default::default() },
cells: vec![Cell::with_text("Head"), Cell::with_text("Col2")],
..Default::default()
};
let body = Row { cells: vec![Cell::with_text("Cell10"), Cell::with_text("Cell11")], ..Default::default() };
let later_header = Row {
props: RowProps { header: true, ..Default::default() },
cells: vec![Cell::with_text("Mid"), Cell::with_text("Mid2")],
..Default::default()
};
let t = Table { grid: vec![120.0, 120.0], rows: vec![header, body, later_header], ..Default::default() };
d.body.push(Arc::new(wordcraft_doc::Block::Table(t)));
let raw = String::from_utf8_lossy(&export(&d, &PdfOptions { tagged: true, compress: false, ..Default::default() }).unwrap()).into_owned();
let count = |tag: &str| raw.matches(&format!("/S/{tag}")).count() + raw.matches(&format!("/S /{tag}")).count();
assert_eq!(count("TH"), 2, "only the top header row's cells are TH");
assert_eq!(count("TD"), 4, "the body row and the later header row are TD");
}
/// A blank cell still gets its TD or TH, so a filled cell after it keeps its column.
#[test]
fn blank_table_cells_keep_their_td_and_th() {
use wordcraft_doc::{Cell, Row, Table, props::RowProps};
let mut d = Document::from_text("A table.");
let header = Row {
props: RowProps { header: true, ..Default::default() },
cells: vec![Cell::with_text(""), Cell::with_text("Col2")],
..Default::default()
};
let body = Row { cells: vec![Cell::with_text(""), Cell::with_text("Cell11")], ..Default::default() };
let t = Table { grid: vec![120.0, 120.0], rows: vec![header, body], ..Default::default() };
d.body.push(Arc::new(wordcraft_doc::Block::Table(t)));
let raw = String::from_utf8_lossy(&export(&d, &PdfOptions { tagged: true, compress: false, ..Default::default() }).unwrap()).into_owned();
let count = |tag: &str| raw.matches(&format!("/S/{tag}")).count() + raw.matches(&format!("/S /{tag}")).count();
assert_eq!(count("TH"), 2, "both header cells, including the blank one");
assert_eq!(count("TD"), 2, "both body cells, including the blank one");
}
/// A row whose cells are all blank is still a row: its TR and its cells are in the tree.
#[test]
fn an_all_blank_row_keeps_its_cells() {
use wordcraft_doc::{Cell, Row, Table};
let mut d = Document::from_text("A table.");
let blank = Row { cells: vec![Cell::with_text(""), Cell::with_text("")], ..Default::default() };
let filled = Row { cells: vec![Cell::with_text("A"), Cell::with_text("B")], ..Default::default() };
let t = Table { grid: vec![120.0, 120.0], rows: vec![blank, filled], ..Default::default() };
d.body.push(Arc::new(wordcraft_doc::Block::Table(t)));
let raw = String::from_utf8_lossy(&export(&d, &PdfOptions { tagged: true, compress: false, ..Default::default() }).unwrap()).into_owned();
let count = |tag: &str| raw.matches(&format!("/S/{tag}")).count() + raw.matches(&format!("/S /{tag}")).count();
assert_eq!(count("TR"), 2, "both rows, including the all-blank one");
assert_eq!(count("TD"), 4, "every body cell");
}
#[test]
fn link_annotations_are_tagged_with_link_and_objr() {
use hayro_syntax::object::{Array, Dict, Name, Object};
let mut p = Paragraph::with_text("Visit ", CharProps::default());
let link_props = CharProps { link: Some("https://example.com".into()), ..Default::default() };
p.insert_text(p.len(), "Example", &link_props).unwrap();
p.insert_text(p.len(), " now", &CharProps::default()).unwrap();
let mut d = Document::new();
d.core.title = "Link test".into();
d.body = vec![para_block(p)];
let bytes = export(&d, &PdfOptions { compress: false, tagged: true, ..Default::default() }).unwrap();
let pdf = hayro_syntax::Pdf::new(bytes).unwrap();
let page = &pdf.pages()[0];
let annots = page.raw().get::<Array>(b"Annots").expect("page Annots");
let annot = annots.iter::<Dict>().next().expect("link annotation");
assert!(annot.get::<i32>(b"StructParent").is_some(), "link annotation missing /StructParent");
let annot_id = format!("{:?}", annot.obj_id().expect("indirect annotation"));
let root = pdf.xref().get::<Dict>(pdf.xref().root_id()).unwrap();
let struct_tree = root.get::<Dict>(b"StructTreeRoot").expect("StructTreeRoot");
fn find_links(dict: &Dict, out: &mut Vec<(bool, Option<String>)>) {
if dict.get::<Name>(b"S").is_some_and(|s| s.as_ref() == b"Link") {
let mut has_mcid = false;
let mut objr = None;
if let Some(k) = dict.get::<Array>(b"K") {
for item in k.iter::<Object>() {
match item {
Object::Number(_) => has_mcid = true,
Object::Dict(d) if d.get::<Name>(b"Type").is_some_and(|t| t.as_ref() == b"OBJR") => {
objr = d.get::<Dict>(b"Obj").and_then(|o| o.obj_id()).map(|id| format!("{id:?}"));
}
_ => {}
}
}
}
out.push((has_mcid, objr));
}
if let Some(k) = dict.get::<Array>(b"K") {
for item in k.iter::<Object>() {
if let Object::Dict(child) = item {
find_links(&child, out);
}
}
} else if let Some(child) = dict.get::<Dict>(b"K") {
find_links(&child, out);
}
}
let mut links = Vec::new();
find_links(&struct_tree, &mut links);
assert!(!links.is_empty(), "StructTreeRoot has no /Link structure element (annot {annot_id})");
assert!(
links.iter().any(|(mcid, objr)| *mcid && objr.as_deref() == Some(&annot_id)),
"Link element missing MCID or OBJR for {annot_id}: {links:?}"
);
}
/// Linked text split by unlinked text keeps reading order: two Link elements, not one that
/// swallows the later run ahead of the text between.
#[test]
fn separated_link_runs_are_separate_link_elements() {
use hayro_syntax::object::{Array, Dict, Name, Object};
let link_props = CharProps { link: Some("https://example.com".into()), ..Default::default() };
let mut p = Paragraph::with_text("A", link_props.clone());
p.insert_text(p.len(), ".", &CharProps::default()).unwrap();
p.insert_text(p.len(), "B", &link_props).unwrap();
let mut d = Document::new();
d.body = vec![para_block(p)];
let bytes = export(&d, &PdfOptions { compress: false, tagged: true, ..Default::default() }).unwrap();
let pdf = hayro_syntax::Pdf::new(bytes).unwrap();
let root = pdf.xref().get::<Dict>(pdf.xref().root_id()).unwrap();
let tree = root.get::<Dict>(b"StructTreeRoot").expect("StructTreeRoot");
fn count(dict: &Dict) -> usize {
let mut n = usize::from(dict.get::<Name>(b"S").is_some_and(|s| s.as_ref() == b"Link"));
if let Some(k) = dict.get::<Array>(b"K") {
for item in k.iter::<Object>() {
if let Object::Dict(c) = item {
n += count(&c);
}
}
} else if let Some(c) = dict.get::<Dict>(b"K") {
n += count(&c);
}
n
}
assert_eq!(count(&tree), 2, "each separated link run needs its own Link element");
}
#[test]
fn header_and_footer_link_annotations_are_tagged_on_every_page() {
use hayro_syntax::object::{Array, Dict, Name, Object};
let header_props = CharProps { link: Some("https://header.example.com".into()), ..Default::default() };
let footer_props = CharProps { link: Some("https://footer.example.com".into()), ..Default::default() };
let body_props = CharProps { link: Some("https://body.example.com".into()), ..Default::default() };
let mut d = Document::new();
d.core.title = "Header and footer links".into();
let header_id = d.add_part(wordcraft_doc::PartKind::Header, vec![para_block(Paragraph::with_text("Header site", header_props))]);
let footer_id = d.add_part(wordcraft_doc::PartKind::Footer, vec![para_block(Paragraph::with_text("Footer site", footer_props))]);
d.last_section.headers.default = Some(header_id);
d.last_section.footers.default = Some(footer_id);
let mut p1 = Paragraph::with_text("Visit ", CharProps::default());
p1.insert_text(p1.len(), "Body", &body_props).unwrap();
let mut p2 = Paragraph::with_text("Second page", CharProps::default());
p2.props.page_break_before = Some(true);
d.body = vec![para_block(p1), para_block(p2)];
let bytes = export(&d, &PdfOptions { compress: false, tagged: true, ..Default::default() }).unwrap();
let pdf = hayro_syntax::Pdf::new(bytes).unwrap();
assert_eq!(pdf.pages().len(), 2, "expected two pages");
// Collect every link annotation across both pages and check /StructParent on each.
let mut expected_annots: Vec<(usize, String, i32)> = Vec::new();
for (page_idx, page) in pdf.pages().iter().enumerate() {
let annots = page.raw().get::<Array>(b"Annots").expect("page Annots");
for annot in annots.iter::<Dict>() {
let sp = annot.get::<i32>(b"StructParent").expect("link annotation missing /StructParent");
let id = format!("{:?}", annot.obj_id().expect("indirect annotation"));
expected_annots.push((page_idx, id, sp));
}
}
assert_eq!(expected_annots.len(), 5, "page 1 has header+body+footer links, page 2 has header+footer links");
let root = pdf.xref().get::<Dict>(pdf.xref().root_id()).unwrap();
let struct_tree = root.get::<Dict>(b"StructTreeRoot").expect("StructTreeRoot");
fn find_links(dict: &Dict, out: &mut Vec<(bool, Option<String>)>) {
if dict.get::<Name>(b"S").is_some_and(|s| s.as_ref() == b"Link") {
let mut has_mcid = false;
let mut objr = None;
if let Some(k) = dict.get::<Array>(b"K") {
for item in k.iter::<Object>() {
match item {
Object::Number(_) => has_mcid = true,
Object::Dict(d) if d.get::<Name>(b"Type").is_some_and(|t| t.as_ref() == b"OBJR") => {
objr = d.get::<Dict>(b"Obj").and_then(|o| o.obj_id()).map(|id| format!("{id:?}"));
}
_ => {}
}
}
}
out.push((has_mcid, objr));
}
if let Some(k) = dict.get::<Array>(b"K") {
for item in k.iter::<Object>() {
if let Object::Dict(child) = item {
find_links(&child, out);
}
}
} else if let Some(child) = dict.get::<Dict>(b"K") {
find_links(&child, out);
}
}
let mut links = Vec::new();
find_links(&struct_tree, &mut links);
assert_eq!(links.len(), expected_annots.len(), "every link annotation needs a /Link structure element: {links:?}");
for (page_idx, annot_id, _) in &expected_annots {
assert!(
links.iter().any(|(_, objr)| objr.as_deref() == Some(annot_id.as_str())),
"page {page_idx} annotation {annot_id} has no /Link OBJR in StructTreeRoot: {links:?}"
);
}
// The 4 header/footer links stay outside artifact content (OBJR only); the body link also holds its MCID.
assert_eq!(links.iter().filter(|(mcid, _)| !*mcid).count(), 4, "header/footer links hold only OBJR: {links:?}");
assert_eq!(links.iter().filter(|(mcid, _)| *mcid).count(), 1, "body link holds MCID and OBJR: {links:?}");
// Verify /ParentTree maps every annotation's /StructParent to a /Link structure element.
let parent_tree = struct_tree.get::<Dict>(b"ParentTree").expect("ParentTree");
let nums = parent_tree.get::<Array>(b"Nums").expect("ParentTree Nums");
let num_items: Vec<Object> = nums.iter::<Object>().collect();
for (page_idx, annot_id, sp) in &expected_annots {
let mut parent_role = None;
for pair in num_items.as_chunks::<2>().0 {
if let [Object::Number(k), Object::Dict(elem)] = pair
&& k.as_i64() == i64::from(*sp)
{
parent_role = elem.get::<Name>(b"S").map(|s| s.as_str().to_string());
break;
}
}
assert_eq!(
parent_role.as_deref(),
Some("Link"),
"page {page_idx} annotation {annot_id} /StructParent {sp} must point to /Link in /ParentTree"
);
}
// Verify reading order under Document: page 1 header link -> body P -> page 1 footer link -> page 2 header link -> body P -> page 2 footer link.
let mut tops: Vec<Dict> = match struct_tree.get::<Object>(b"K") {
Some(Object::Array(a)) => a.iter::<Dict>().collect(),
Some(Object::Dict(d)) => vec![d],
_ => Vec::new(),
};
while let [only] = tops.as_slice()
&& only.get::<Name>(b"S").is_some_and(|s| s.as_str() == "Document")
{
tops = match only.get::<Object>(b"K") {
Some(Object::Array(a)) => a.iter::<Dict>().collect(),
Some(Object::Dict(d)) => vec![d],
_ => Vec::new(),
};
}
let top_roles: Vec<String> = tops.iter().map(|d| d.get::<Name>(b"S").map(|s| s.as_str().to_string()).unwrap_or_default()).collect();
assert_eq!(top_roles, vec!["Div", "P", "Div", "Div", "P", "Div"], "header link before body, footer link after body");
}
+2 -2
View File
@@ -16,7 +16,7 @@ craft = { workspace = true, features = [
"color", "color-ui", "control", "draw", "font-manager", "gpu", "menu", "pages", "print", "review", "table", "text",
"text-find", "web-api", "web-host", "window",
] }
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
wordcraft-geom = { workspace = true, features = ["image"] }
wordcraft-doc = { workspace = true }
wordcraft-fonts = { workspace = true }
@@ -76,7 +76,7 @@ craft-ui-test-kit = { workspace = true }
craft = { workspace = true, features = ["ui-testing"] }
[build-dependencies]
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", features = ["subset"] }
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", features = ["subset"] }
serde_json = { workspace = true }
toml = "1"
+3 -1
View File
@@ -266,7 +266,9 @@ fn main() {
}
let mem_after_typing = memory_mb();
// Edit/Undo burst: 40 discrete paragraph insertions followed by 40 undos.
// Edit/Undo burst: 40 discrete short-text insertions (" {k}") at the current caret (the first
// table cell when the document has a table, otherwise the target paragraph), each in its own
// undo group, followed by 40 undos.
let mut edit_burst = Vec::new();
let mut undo_burst = Vec::new();
for k in 0..40 {
+3 -3
View File
@@ -1,5 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" height="20">
<rect x="7.5" y="2.5" width="5" height="9.5" rx="1" fill="none" stroke="currentColor" stroke-width="1.25"/>
<path d="M5 9.5 L5 11 L10 15 L15 11 L15 9.5" fill="none" stroke="currentColor" stroke-width="1.25"/>
<path d="M10 15 L10 18" fill="none" stroke="currentColor" stroke-width="1.25"/>
<rect x="7.5" y="2.5" width="5" height="9.5" rx="2.5" fill="none" stroke="currentColor" stroke-width="1.25"/>
<path d="M5 9.5 L5 11 L10 15 L15 11 L15 9.5" fill="none" stroke="currentColor" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M10 15 L10 18" fill="none" stroke="currentColor" stroke-width="1.25" stroke-linecap="round"/>
</svg>

Before

Width:  |  Height:  |  Size: 386 B

After

Width:  |  Height:  |  Size: 458 B

+3
View File
@@ -133,6 +133,8 @@ impl WordApp {
user_origin: false,
read_aloud_error: None,
autosave_path: None,
autosave_choice: None,
read_from: None,
saves_in_flight: Vec::new(),
fallback_chooser: false,
font_generation: wordcraft_fonts::FontDb::global().generation(),
@@ -363,6 +365,7 @@ impl WordApp {
// draws, for itself.
self.window_work(ctx);
self.drain_inbox();
crate::keys::tick_paste_wait(self, ctx);
self.paste_arrived(ctx);
// Focus hides the title bar's search box: a search left open there has no box to show it, and would keep
// Escape from leaving Focus (#5398).
+25 -12
View File
@@ -348,7 +348,11 @@ impl WordApp {
let params = if fired.command.params.is_null() { json!({}) } else { fired.command.params.clone() };
let from_key = fired.source == FireSource::Key;
let (id, params) = if id == "edit.pasteFormat" && from_key { self.paste_format_command(ctx, params) } else { (id, params) };
let (id, params) = if id == "edit.pasteFormat" && from_key { self.paste_format_command(ctx, fired.mods, params) } else { (id, params) };
if from_key && id != "edit.pasteFormat" {
self.canvas.ignore_next_paste = false;
self.canvas.paste_wait_since = None;
}
// An Undo or Redo that is not a focused field's own edit (S-L187 sends that one to the
// field) first takes back the gesture under way and every running one (S-L364).
if matches!(id, "edit.undo" | "edit.redo") {
@@ -368,25 +372,34 @@ impl WordApp {
self.canvas.focus_page(ctx);
}
}
self.canvas.paste_event_consumed_same_frame = false;
}
/// Paste Formatting from its key. Mod+Shift+V pastes the formatting Mod+Shift+C (or the Format
/// Painter) picked up; with none picked up it pastes the clipboard as text only, as Word for
/// Windows does (#1537, #4943). Another key bound to Paste Formatting only pastes formatting.
/// The framework fires one command per chord, so nothing waits for a browser paste event.
fn paste_format_command(&self, ctx: &egui::Context, params: Value) -> (&'static str, Value) {
/// On platforms where a browser paste event follows Mod+Shift+V, pasting formatting arms
/// `ignore_next_paste` so that paired paste event is dropped.
fn paste_format_command(&mut self, ctx: &egui::Context, fired_mods: craft::keymap::Mods, params: Value) -> (&'static str, Value) {
let formatting = self.session.painter.is_some() || self.session.copied_format.is_some();
// The command runs a pass after its press, when a quick tap's modifiers are already up: with none held the fire
// is Mod+Shift+V's while that chord is still the command's.
let mods = ctx.input(|i| i.modifiers);
let chord = if mods.any() {
mods.command && mods.shift && !mods.alt
// `fired.mods` carries the chord's modifiers across every OS window, even after a quick
// tap releases the physical keys before `run_fired` runs.
let platform = if craft::ui::runtime::windows::os_of(ctx) == craft::host::target::Os::Mac {
craft::keymap::Platform::Mac
} else {
let default = Binding::parse("Mod+Shift+V").ok().map(|binding| binding.trigger.chord);
craft::ui::runtime::commands::bindings(ctx, &CommandRef::new("edit.pasteFormat"))
.iter()
.any(|binding| Some(binding.trigger.chord) == default)
craft::keymap::Platform::Windows
};
let eff = fired_mods.effective(platform);
let mod_shift = eff.cmd && eff.shift && !eff.alt && !eff.ctrl;
let default = Binding::parse("Mod+Shift+V").ok().map(|binding| binding.trigger.chord);
let chord = mod_shift
&& craft::ui::runtime::commands::bindings(ctx, &CommandRef::new("edit.pasteFormat"))
.iter()
.any(|binding| Some(binding.trigger.chord.effective(platform)) == default);
if formatting && chord && self.canvas.paste_event_follows_chord && !std::mem::take(&mut self.canvas.paste_event_consumed_same_frame) {
self.canvas.ignore_next_paste = true;
self.canvas.paste_wait_since = Some(ctx.input(|i| i.time));
}
if !formatting && chord { ("edit.pasteText", json!({})) } else { ("edit.pasteFormat", params) }
}
}
+96 -24
View File
@@ -10,8 +10,13 @@ use super::{
};
use crate::colors;
/// The document's own save stamps: zoom, last-modified-by, created, modified and revision.
type SaveStamps = (Option<wordcraft_doc::Zoom>, String, String, String, u32);
impl WordApp {
/// `run` for a command a mouse drag on a table sends: the view stays where it is.
/// Runs a command from a pointer gesture without automatically scrolling to the caret.
/// Table and ruler gestures and picture or shape selection use this when the pointer
/// already identifies the target.
pub(crate) fn run_keep_view(&mut self, id: &str, params: Value) -> Result<Value, String> {
self.canvas.keep_view = true;
let r = self.run(id, params);
@@ -114,6 +119,42 @@ impl WordApp {
r
}
/// File › Export's `copy` (#6131) writes a copy and never the document's own file. A host
/// page's Save writes the opened file under its own name and its flag can't say "copy", so a
/// copy named like the opened file would overwrite it with unsaved text; and `password`
/// changes the document's own later saves. Both are refused before anything is written.
fn copy_save(&self, id: &str, name: &str, params: &Value) -> Result<bool, String> {
let as_copy = params.get("copy").and_then(Value::as_bool) == Some(true);
if !as_copy {
return Ok(false);
}
let opened = self.session.path.as_ref().and_then(|p| p.file_name()).map(|n| n.to_string_lossy().to_string());
// Compare file names only: a copy given as a path still lands on the opened file's name.
let copy_name = std::path::Path::new(name).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| name.to_string());
if opened.as_deref() == Some(copy_name.as_str()) {
return Err("a copy can't have the same name as the open document: choose another name".into());
}
if matches!(id, "file.save" | "file.saveAs") && params.get("password").is_some_and(|pw| !pw.is_null()) {
return Err("`password` changes the document's own saves, so it can't come with `copy` (use file.encrypt)".into());
}
Ok(true)
}
/// A copy (File › Export, #6131) writes its bytes with fresh save stamps; the document's own
/// are then put back, so its next Save still goes to the original file.
fn restore_copy_stamps(&mut self, as_copy: bool, stamps: &SaveStamps) {
if as_copy {
let (zoom, by, created, modified, revision) = stamps;
(
self.session.doc.settings.zoom,
self.session.doc.core.last_modified_by,
self.session.doc.core.created,
self.session.doc.core.modified,
self.session.doc.core.revision,
) = (*zoom, by.clone(), created.clone(), modified.clone(), *revision);
}
}
/// Run a command for a script or an agent (control channel, MCP bridge): never asks first.
/// UI-level commands (`ui.*`) are handled here, the rest by the engine.
pub fn execute(&mut self, id: &str, params: Value) -> Result<Value, String> {
@@ -135,7 +176,11 @@ impl WordApp {
return Err(e.into());
}
if id == "file.autosave" {
return self.set_autosave(&params);
let r = self.set_autosave(&params);
if let Err(e) = &r {
self.status(e.clone());
}
return r;
}
if let Some(r) = table_pen::toggle(self, id, &params) {
return r;
@@ -153,6 +198,9 @@ impl WordApp {
// Inspect only the suffix bytes: no full-name allocation or UTF-8 slicing.
let has_pdf_suffix = name.as_bytes().last_chunk::<4>().is_some_and(|suffix| suffix.eq_ignore_ascii_case(b".pdf"));
let name = if id == "file.exportPdf" && !has_pdf_suffix { format!("{name}.pdf") } else { name };
// `copy` (File › Export, #6131) writes a copy: the document keeps its unsaved changes,
// its name and its save stamps, as for a PDF.
let as_copy = self.copy_save(id, &name, &params)?;
// A save with a password encrypts this and later saves (`file.save`'s `password`).
if matches!(id, "file.save" | "file.saveAs")
&& let Some(pw) = params.get("password").filter(|v| !v.is_null())
@@ -172,6 +220,7 @@ impl WordApp {
self.session.doc.core.revision,
);
// A save is a save, download or not: advance the revision and modified stamp (#262).
// A copy carries fresh stamps too, but the document's own are put back after.
if matches!(id, "file.save" | "file.saveAs") {
self.session.stamp_save();
}
@@ -192,23 +241,26 @@ impl WordApp {
return Err(error);
}
};
self.restore_copy_stamps(as_copy, &before_stamp);
// An export is a copy, and so is a save in a format that doesn't keep everything (a
// page image, plain text): the document itself still has unsaved changes.
let marked_saved = matches!(id, "file.save" | "file.saveAs") && keeps_everything(&name);
let marked_saved = matches!(id, "file.save" | "file.saveAs") && !as_copy && keeps_everything(&name);
// The ticket's answer may be a failure: what the save stamped is put back then (`settle_saves`).
let undo_stamp: Option<Box<dyn FnOnce(&mut wordcraft_engine::Session)>> = matches!(id, "file.save" | "file.saveAs").then(|| {
let dirty = dirty_before;
Box::new(move |session: &mut wordcraft_engine::Session| {
(
session.doc.settings.zoom,
session.doc.core.last_modified_by,
session.doc.core.created,
session.doc.core.modified,
session.doc.core.revision,
) = before_stamp;
session.dirty = dirty;
}) as Box<dyn FnOnce(&mut wordcraft_engine::Session)>
});
// A copy already restored its stamps above, so settling it leaves the document's own stamps alone.
let undo_stamp: Option<Box<dyn FnOnce(&mut wordcraft_engine::Session)>> =
(matches!(id, "file.save" | "file.saveAs") && !as_copy).then(|| {
let dirty = dirty_before;
Box::new(move |session: &mut wordcraft_engine::Session| {
(
session.doc.settings.zoom,
session.doc.core.last_modified_by,
session.doc.core.created,
session.doc.core.modified,
session.doc.core.revision,
) = before_stamp;
session.dirty = dirty;
}) as Box<dyn FnOnce(&mut wordcraft_engine::Session)>
});
// Save As tells the host page the document is now this file, which it only is when the
// save marks it saved. A Save under a name the page never sent (an untitled document,
// an imported .doc saved as .docx) is a new file too, never an overwrite.
@@ -278,13 +330,8 @@ impl WordApp {
self.recovery_seen = true;
self.sync_document();
}
// An explicit save to the document's own file lets AutoSave keep writing there.
if let Ok(v) = &r
&& matches!(id, "file.save" | "file.saveAs")
&& v.get("saved").and_then(Value::as_bool) == Some(true)
&& v.get("path").and_then(Value::as_str).map(std::path::Path::new) == self.session.path.as_deref()
{
self.autosave_path = self.session.path.clone();
if let Ok(v) = &r {
self.note_file_on_disk(id, &params, v);
}
// A Markdown file edited in the formatted view was written out again, not kept as it was.
if let Ok(v) = &r
@@ -301,6 +348,9 @@ impl WordApp {
if self.autosave_path.as_ref() == Some(&old) {
self.autosave_path = self.session.path.clone();
}
if self.read_from.as_ref() == Some(&old) {
self.read_from = self.session.path.clone();
}
let old = old.to_string_lossy();
self.ui.recent.retain(|r| *r != old);
}
@@ -386,6 +436,25 @@ impl WordApp {
r
}
/// Which file on disk the document is in, after `file.save`, `file.saveAs` or `file.open`.
fn note_file_on_disk(&mut self, id: &str, params: &Value, v: &Value) {
// A save makes the file eligible for AutoSave without changing the document's switch choice.
if matches!(id, "file.save" | "file.saveAs")
&& v.get("saved").and_then(Value::as_bool) == Some(true)
&& v.get("path").and_then(Value::as_str).map(std::path::Path::new) == self.session.path.as_deref()
{
self.autosave_path = self.session.path.clone();
self.read_from = self.session.path.clone();
}
// A file read from disk may have AutoSave turned on for it; one opened from bytes only
// names a file it never read.
// `file.open` without a path only asks for the picker, and `data` that isn't a string is
// ignored (the file is read from disk).
if id == "file.open" && params.get("path").and_then(Value::as_str).is_some() && v.get("alreadyOpen").and_then(Value::as_bool) == Some(false) {
self.read_from = if params.get("data").and_then(Value::as_str).is_some() { None } else { self.session.path.clone() };
}
}
fn after_command(&mut self, id: &str) {
self.canvas.glide.restart(craft::platform::clock::monotonic_ms());
if id == "view.outline" {
@@ -398,7 +467,7 @@ impl WordApp {
self.canvas.read_first_visible = None;
}
// Drawing leaves the caret where it was: following it would pull the view off the ink.
// A mouse drag on a table (`run_keep_view`) does the same (#1738). A caret in an empty
// Pointer gestures using `run_keep_view` also keep the view in place. A caret in an empty
// story (a footer just made) also spans the whole story: it isn't a selection of it, and
// the view follows it. Saving, exporting, printing, the document's properties and File ›
// Options move neither the caret nor the text, so the view stays where the user is
@@ -800,6 +869,8 @@ impl WordApp {
};
return Some(self.answer_save_changes(answer));
}
// The app menu's Quit (⌘Q): asks about each unsaved document, as the Dock's Quit does.
"ui.quit" => json!({"quit": self.quit()}),
"ui.openFileDialog" => {
self.open_dialog();
json!({})
@@ -1250,6 +1321,7 @@ pub(crate) fn works_without_document(id: &str) -> bool {
| "ui.animations"
| "ui.language"
| "ui.saveChanges"
| "ui.quit"
| "ui.openFileDialog"
| "ui.printCancel"
| "ui.fileBrowser"
+71 -9
View File
@@ -1,7 +1,7 @@
use craft::host::{PickId, Picked};
use craft::platform::open::{DroppedFile, Intake};
use craft::quit::{CloseAnswer, CloseGuard, CloseScope, GuardStep};
use craft::ui::dialog::{DialogId, DialogResult, UnsavedChangesDialog};
use craft::ui::dialog::{DialogId, DialogResult, HostedUnsavedChangesDialog, UnsavedChangesDialog};
use craft::ui::shell::embed::CloseDecision;
use super::{AutoSaveBlock, PromptSave, Value, WordApp, file_dialogs, i18n, json, keeps_everything, panes, printing};
@@ -151,7 +151,7 @@ impl WordApp {
dialog = dialog.reason(reason);
}
// PLAN: assumed `WordApp::dialog_host: DialogHost`, the shown window's
let id = self.dialog_host.open(dialog);
let id = self.dialog_host.open(HostedUnsavedChangesDialog::new(dialog));
if let Some(closing) = self.closing.as_mut() {
closing.prompt = Some(id);
closing.window = self.windows.shown();
@@ -246,7 +246,7 @@ impl WordApp {
let ctx = self.ctx.clone().unwrap_or_default();
if let Some(host) = self.window_dialog_host_mut(window) {
host.cancel_by_id(&ctx, id);
let _ = host.take_by_id::<UnsavedChangesDialog>(id);
let _ = host.take_by_id::<HostedUnsavedChangesDialog>(id);
}
}
@@ -262,7 +262,7 @@ impl WordApp {
/// from `logic`.
pub(crate) fn pump_close_prompt(&mut self) {
let Some((window, id)) = self.closing.as_ref().and_then(|c| c.prompt.map(|id| (c.window, id))) else { return };
let Some(result) = self.window_dialog_host_mut(window).and_then(|host| host.take_by_id::<UnsavedChangesDialog>(id)) else { return };
let Some(result) = self.window_dialog_host_mut(window).and_then(|host| host.take_by_id::<HostedUnsavedChangesDialog>(id)) else { return };
if let Some(ctx) = self.ctx.as_ref() {
crate::dialogs::chrome::forget_nudge(ctx, id);
}
@@ -285,6 +285,16 @@ impl WordApp {
if self.raise_closing().is_some() {
return CloseDecision::Hold;
}
// Nothing is open, so nothing to ask about (also under a windowless root, whose last document window going is
// what asks).
if self.session.documents().is_empty() {
return CloseDecision::Close;
}
// A windowless root has no window of its own: its close is a quit (the OS quit, or the last document window
// going), never one window's close.
if self.ctx.as_ref().is_some_and(craft::ui::runtime::windows::windowless_root) {
return if self.close_requested() { CloseDecision::Close } else { CloseDecision::Hold };
}
if self.closes_a_window() {
// The root window's close button closes that window alone (File › Close in it, which asks
// about unsaved changes first); the framework leaves the root's window open on `Hold`, and
@@ -541,9 +551,27 @@ impl WordApp {
if let Some(result) = self.raise_closing() {
return Ok(result);
}
if self.closes_only_its_window("file.close", params) {
// `save: true` still writes the document, which stays open in the other windows.
if params.get("save").and_then(Value::as_bool) == Some(true)
&& let Some(pending) = self.save_for_close()?
{
return Ok(pending);
}
}
if self.closes_only_its_window("file.close", params) && self.close_window_only() {
return Ok(json!({"closed": true, "window": true}));
}
if params.get("save").and_then(Value::as_bool) == Some(true) {
// A comment still being typed refuses before anything is written.
if let Some(e) = crate::control::close_refused(self, "file.close", params) {
return Err(e.into());
}
// Automation's `save: true`: write the document, then close it. Never a prompt (spec rule 8).
if let Some(pending) = self.save_for_close()? {
return Ok(pending);
}
}
if let Some(e) = crate::control::close_refused(self, "file.close", params) {
return Err(e.into());
}
@@ -578,6 +606,24 @@ impl WordApp {
Ok(json!({"closed": true}))
}
/// `file.close` with `save: true`: save the shown document if it has unsaved work. `Some` is
/// the reply when the save finishes later (the browser's picker). A document with no file
/// to write has nowhere to save without asking, so that is an error, not a prompt.
fn save_for_close(&mut self) -> Result<Option<Value>, String> {
if !self.document_unsaved() {
return Ok(None);
}
if self.session.path.is_none() || self.legacy_word_path() {
return Err("the document has no file to save to: use file.saveAs first, or pass {\"force\": true} to discard it".into());
}
match self.save_for_prompt()? {
PromptSave::Saved => Ok(None),
// lean: only the browser picker saves later and it has no control channel, so the close is not resumed.
PromptSave::Later => Ok(Some(json!({"pending": "save"}))),
PromptSave::NotSaved => Err("the document was not saved, so it stays open".into()),
}
}
/// These paths have readers but no writer, so an interactive save needs another format.
pub(super) fn legacy_word_path(&self) -> bool {
self.session
@@ -662,7 +708,8 @@ impl WordApp {
}
/// Why AutoSave can't cover the document, or `None` when it can: it writes only a file the
/// user saved to in this session, in a format that keeps everything, and never in the browser
/// user saved to in this session or explicitly enabled after opening it from disk. The format
/// must keep everything, and AutoSave never writes in the browser
/// (a page can't write to the user's files; saving there is a download, #176).
pub fn autosave_block(&self) -> Option<AutoSaveBlock> {
if self.browser_saves() {
@@ -673,7 +720,8 @@ impl WordApp {
let name = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
return Some(AutoSaveBlock::Format { name });
}
if !self.saved_here() {
let opened_and_enabled = self.autosave_choice == Some(true) && self.read_from.as_ref() == Some(path);
if !self.saved_here() && !opened_and_enabled {
return Some(AutoSaveBlock::NotSavedHere);
}
None
@@ -681,17 +729,30 @@ impl WordApp {
/// Whether AutoSave covers the document: it is on and nothing blocks it ([`Self::autosave_block`]).
pub fn autosaves(&self) -> bool {
self.autosave && self.autosave_block().is_none()
self.autosave && self.autosave_choice != Some(false) && self.autosave_block().is_none()
}
/// What the AutoSave switch can't lift: [`Self::autosave_block`], less a file read from disk
/// here, which the switch turns on (#3307). A document opened from bytes stays blocked.
pub fn autosave_switch_block(&self) -> Option<AutoSaveBlock> {
self.autosave_block().filter(|b| *b != AutoSaveBlock::NotSavedHere || self.read_from != self.session.path)
}
/// `file.autosave` (the AutoSave switch, and scripts): `value` turns AutoSave on or off;
/// without it, it toggles what the switch shows. Turning it on for a document AutoSave can't
/// cover is an error that says why, instead of a switch that is on but saves nothing (#196).
/// Turning it on for a file only opened here is the go-ahead a save gives (#3307), when the
/// document was read from that file; turning it off withdraws the go-ahead for this document.
pub(super) fn set_autosave(&mut self, params: &Value) -> Result<Value, String> {
let on = params.get("value").and_then(Value::as_bool).unwrap_or(!self.autosaves());
if on && let Some(block) = self.autosave_block() {
let on = match params.get("value") {
None => !self.autosaves(),
Some(Value::Bool(on)) => *on,
Some(_) => return Err("`value` must be true or false".into()),
};
if on && let Some(block) = self.autosave_switch_block() {
return Err(block.reason());
}
self.autosave_choice = Some(on);
self.autosave = on;
self.session.autosave = on;
Ok(json!({"value": on}))
@@ -705,6 +766,7 @@ impl WordApp {
if let Err(e) = self.session.run("file.save", &json!({})) {
log::warn!("AutoSave failed: {e}");
self.autosave_path = None;
self.autosave_choice = None;
self.status(i18n::fmt(tl!("AutoSave failed: {error}. Save the document to turn AutoSave back on."), &[("error", &e.to_string())]));
}
}
+33 -10
View File
@@ -16,12 +16,18 @@ use crate::i18n::Lang;
// PLAN(chrome-w12): build.rs embeds the craft faces into `craft_fonts.rs`
pub static CRAFT_FONTS: &[EmbeddedFace] = include!(concat!(env!("OUT_DIR"), "/craft_fonts.rs"));
/// The interface fonts for `lang`: the embedded craft faces, ordered by the language's scripts,
/// and installed system fonts loaded on demand where the platform has them.
/// The interface fonts for `lang`: WordCraft's own Inter and the embedded craft faces, ordered by the language's
/// scripts, and installed system fonts loaded on demand where the platform has them.
pub fn ui_fonts(lang: Lang) -> UiFonts<'static> {
ui_fonts_with_optional_faces(lang, CRAFT_FONTS)
}
/// [`ui_fonts`] with `faces` as the optional craft-fonts faces. Tests pass none, so the faces a CI build embeds
/// can't hide a character the interface's own faces lack.
pub(crate) fn ui_fonts_with_optional_faces(lang: Lang, faces: &[EmbeddedFace]) -> UiFonts<'static> {
let codes: Vec<&str> = Lang::all().map(Lang::code).collect();
let os_locale = wordcraft_engine::system_locale();
let fonts = UiFonts::new(&I18nScripts).craft_faces(CRAFT_FONTS).languages(&codes).ui_language(lang.code());
let fonts = UiFonts::new(&I18nScripts).craft_faces(&own_inter()).craft_faces(faces).languages(&codes).ui_language(lang.code());
let fonts = match os_locale {
Some(locale) => fonts.os_locale(locale),
None => fonts,
@@ -31,6 +37,21 @@ pub fn ui_fonts(lang: Lang) -> UiFonts<'static> {
fonts
}
/// WordCraft's own Inter Regular and SemiBold, from the bytes the document fonts embed. The suite's interface face is
/// the same Inter release cut to Latin, Greek and Cyrillic; tagged with those scripts, these come right after the
/// suite's faces and draw the rest of Inter (○ ✓ ★, the macOS key symbols) in the same design and row height, as the
/// interface did before it moved onto the shared font stack (#7101).
fn own_inter() -> [EmbeddedFace; 2] {
wordcraft_fonts::bundled_inter().map(|(style, bytes)| EmbeddedFace {
family: "Inter",
style,
scripts: &["Latn", "Grek", "Cyrl"],
index: 0,
bytes,
role: None,
})
}
#[cfg(test)]
/// One character of each script the app ships, to find the document fonts that cover it.
const FALLBACK_SAMPLES: [char; 6] = ['ع', 'א', 'ก', 'ა', 'ա', '汉'];
@@ -116,12 +137,12 @@ mod tests {
}
}
/// Symbols written as text in the interface code must exist in the interface fonts; a missing
/// glyph draws as an empty box, as the panes' "✕" close button once did. Letters are the
/// catalogs' business (see the i18n font tests).
/// Symbols written as text in the interface code must exist in the interface fonts, also in a build without the
/// optional craft-fonts faces; a missing glyph draws as an empty box, as the panes' "✕" close button once did.
/// Letters are the catalogs' business (see the i18n font tests).
#[test]
fn interface_symbols_have_glyphs() {
let stack = ui_fonts(Lang::EN).stack();
let stack = ui_fonts_with_optional_faces(Lang::EN, &[]).stack();
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
let mut symbols = BTreeSet::new();
// The i18n module's literals are catalog and pseudo-locale test text, not interface text.
@@ -154,9 +175,11 @@ mod tests {
symbols.retain(|(c, file)| !exempt(*c, file));
let files: Vec<(char, String)> = symbols.into_iter().collect();
let texts: Vec<(String, String)> = files.iter().map(|(c, f)| (c.to_string(), f.clone())).collect();
let samples = texts.iter().map(|(t, f)| Sample::new("en", f, t));
let missing = missing_glyphs(&stack, &FontRef::proportional(), samples, false);
assert!(missing.is_empty(), "symbols without a glyph: {missing:#?}");
for family in [FontRef::proportional(), FontRef::named(craft::ui::fonts::SEMIBOLD)] {
let samples = texts.iter().map(|(t, f)| Sample::new("en", f, t));
let missing = missing_glyphs(&stack, &family, samples, false);
assert!(missing.is_empty(), "symbols without a glyph in {family:?}: {missing:#?}");
}
}
/// An installed Arabic font is asked for only when Arabic text needs one (and no embedded
+4
View File
@@ -77,6 +77,10 @@ impl WordApp {
if !ClipboardHandle::of(ctx).arrived() {
return;
}
if std::mem::take(&mut self.canvas.ignore_next_paste) {
self.canvas.paste_wait_since = None;
return;
}
// PLAN(canvas-w9): cv.A10 `CanvasState::focused(&self, &egui::Context) -> bool`
if paste_target(self.canvas.focused(ctx), self.ui.backstage, self.modal_open()) {
let _ = self.run("edit.paste", json!({}));
+18
View File
@@ -941,3 +941,21 @@ fn clicking_beside_the_back_arrow_does_not_close_the_file_page() {
h.run_steps(4);
assert!(h.state().ui.backstage, "clicking beside the arrow leaves the File page open");
}
/// #7171: in a window too short for the settings column its scroll bar shows, and the buttons stop where the bar's lane
/// starts instead of running under it. The column also ends short of the preview.
#[test]
fn print_settings_buttons_stay_clear_of_the_bar_and_the_preview() {
let mut a = new_app();
a.run("text.insert", json!({"text": "Some text"})).unwrap();
a.run("ui.backstage", json!({"value": true, "page": "print"})).unwrap();
let mut h = harness(a, egui::vec2(700.0, 500.0));
h.run_steps(6);
let column = h.query_all_by_label("Print").map(|n| n.rect()).max_by(|a, b| a.height().total_cmp(&b.height())).expect("the settings column");
let pane = h.query_all_by_label("Sheet 1 of 1").map(|n| n.rect()).max_by(|a, b| a.height().total_cmp(&b.height())).expect("the preview");
assert!(pane.min.x >= column.max.x + 8.0, "a gap between the column and the preview: {column:?} {pane:?}");
for name in ["Save these pages as PDF…", "PDF document (*.pdf)"] {
let button = h.get_by_label(name).rect();
assert!(button.min.x >= column.min.x && button.max.x <= column.max.x - 4.0, "{name} leaves the bar's lane: {button:?} {column:?}");
}
}
+17 -2
View File
@@ -152,8 +152,8 @@ pub struct CanvasState {
/// revision: finding out walks every paragraph, too slow for every frame (#811).
markup_facts: Cell<Option<((u64, u64), [bool; 3])>>,
pub scroll_to_caret: bool,
/// Set while a command runs for a mouse drag on a table: the pointer is already
/// on the target, so the view stays put instead of following the caret (#1738).
/// Set while a pointer-triggered command runs through `WordApp::run_keep_view`
/// to suppress automatic scrolling to the caret.
pub keep_view: bool,
/// A heading navigation click aligns its page against the navigation pane, not just visible.
pub(crate) nav_to_caret: bool,
@@ -262,6 +262,17 @@ pub struct CanvasState {
/// Snapshot of `session.doc` for `(document_id, rev)`, shared via `Arc::clone` across
/// unchanged frames instead of cloning the full `Document` every pass.
doc_snapshot: Option<((u64, u64), Arc<wordcraft_doc::Document>)>,
/// On the web, Mod+Shift+V pasted formatting from its key press: the browser's paste event
/// that follows is the same keystroke and pastes nothing (#5616). Any other key press, pointer
/// press, focus change, or wait past `PASTE_WAIT` clears it.
pub(crate) ignore_next_paste: bool,
/// Input time (seconds) when `ignore_next_paste` was armed.
pub(crate) paste_wait_since: Option<f64>,
/// Whether the platform sends a paste event after Mod+Shift+V's key (true on the web).
pub(crate) paste_event_follows_chord: bool,
/// The paired browser paste arrived and was dropped in the same frame as Mod+Shift+V, before
/// `run_fired` runs in the next frame.
pub(crate) paste_event_consumed_same_frame: bool,
}
type TablePreviewKey = ((String, serde_json::Value, u64, u64, wordcraft_engine::Selection), Arc<DocLayout>);
@@ -474,6 +485,10 @@ impl Default for CanvasState {
preview_scroll: None,
table_preview_layout: None,
doc_snapshot: None,
ignore_next_paste: false,
paste_wait_since: None,
paste_event_follows_chord: cfg!(target_arch = "wasm32"),
paste_event_consumed_same_frame: false,
}
}
}
+25 -13
View File
@@ -30,7 +30,7 @@ struct BalloonItems {
}
/// Comment balloons in the markup area right of each page, joined to their anchors, with each comment's replies in
/// its card. Clicking a card selects it, like Word: its text becomes editable in place, with Reply, Resolve and
/// its card. Clicking a card selects it, like Word: a double click makes its text editable in place, with Reply, Resolve and
/// Delete (the same commands as the Comments pane).
pub(crate) fn balloons(app: &mut WordApp, ui: &mut Ui, out: &craft::pages::ui::PageViewOutput, layout: &DocLayout) {
app.canvas.balloon_rects.clear();
@@ -63,6 +63,26 @@ pub(crate) fn balloons(app: &mut WordApp, ui: &mut Ui, out: &craft::pages::ui::P
for edit in shown.edits {
apply(app, &cards, edit);
}
open_edit_on_double_click(app, ui);
}
/// A double click on the selected card's own text opens its comment for editing, as craft's comments pane does. A click
/// that lands in a field or on a button (Reply, Resolve, the menu) is not one.
// lean: mouse only; a keyboard path (Enter/F2 on the selected card) is a follow-up.
fn open_edit_on_double_click(app: &mut WordApp, ui: &Ui) {
let Some(id) = app.canvas.selected_balloon() else { return };
if app.canvas.comments.editing.is_some() || ui.ctx().egui_wants_keyboard_input() {
return;
}
let at = ui.input(|i| i.pointer.button_double_clicked(egui::PointerButton::Primary).then(|| i.pointer.interact_pos())).flatten();
let Some(at) = at else { return };
let on_card = app.canvas.balloon_rects.iter().any(|(i, r)| *i == id && r.contains(at));
if !on_card || !crate::app::command_board::command_enabled(app, "review.editComment") {
return;
}
let Some(c) = app.session.doc.comments.get(&id) else { return };
let text = app.session.doc.plain_text(StoryRef::Part(c.part));
app.canvas.comments.edit(thread_id(id), 0, text);
}
/// Applies what a card reported through the commands the Comments pane uses.
@@ -243,25 +263,17 @@ fn write_back(app: &mut WordApp, id: u32) {
let _ = crate::panes::commit_reply(app, id);
}
/// Makes comment `id` the selected card with its own text open for editing, writing back the draft of the one edited
/// before. The card selects itself on a click; this opens its edit so the field has the keyboard.
/// Makes comment `id` the selected card, writing back the draft of the one edited before. As in Word, selecting a card
/// puts no message into edit (that hides its Reply); an edit starts on a double click on the selected card.
fn focus_balloon(app: &mut WordApp, id: u32) {
let before = app.canvas.comments.editing.as_ref().and_then(|(t, ..)| app_id(*t)).filter(|b| *b != id);
if let Some(before) = before {
write_back(app, before);
}
// Where comments can't change (a read-only document) the card is selected with no edit open: nothing is typed.
let editable = crate::app::command_board::command_enabled(app, "review.editComment");
let text = app.session.doc.comments.get(&id).filter(|_| editable).map(|c| app.session.doc.plain_text(StoryRef::Part(c.part)));
let thread = thread_id(id);
let comments = &mut app.canvas.comments;
comments.selected = craft::behavior::Selection::single(thread);
if comments.editing.as_ref().is_none_or(|(t, ..)| *t != thread) {
comments.editing = text.map(|t| (thread, 0, t));
}
app.canvas.comments.selected = craft::behavior::Selection::single(thread_id(id));
}
/// Select a comment's balloon (its text gets the keyboard), writing back any edit in the one selected before.
/// Select a comment's balloon (no edit opens), writing back any edit in the one selected before.
pub fn select_balloon(app: &mut WordApp, id: u32) {
if app.canvas.selected_balloon() == Some(id) {
return;
+5 -6
View File
@@ -151,12 +151,11 @@ fn rows(app: &mut WordApp, ui: &mut Ui) {
let _ = Menu::submenu_row(ui, tl!("Synonyms").to_string(), |ui, _cx| {
for w in syn.iter().filter_map(|x| x.as_str()) {
if MenuItem::new(w.to_string()).show(ui).ran {
let _ = app.run("select.word", json!({}));
let (a, b) = app.session.sel.ordered();
let trimmed = app.session.doc.para_at(&a).and_then(|p| p.text.get(a.off..b.off)).map(|t| t.trim_end().len()).unwrap_or(0);
let end = wordcraft_doc::Pos { off: a.off + trimmed, ..b };
app.session.set_selection(wordcraft_engine::Selection { anchor: a, focus: end });
let _ = app.run("text.insert", json!({"text": w, "raw": true}));
// The word the synonyms were looked up for: quotes around it stay (#6517).
if let Some((a, b)) = wordcraft_engine::cmd::review::thesaurus_word(&app.session) {
app.session.set_selection(wordcraft_engine::Selection { anchor: a, focus: b });
let _ = app.run("text.insert", json!({"text": w, "raw": true}));
}
}
}
});
+20 -1
View File
@@ -7,10 +7,29 @@ use super::{Pos2, WordApp};
/// coordinates) while any of it is inside the window (`top` .. `top + height`, `top` the layout's y at the window's
/// top edge), else the page at the window's top: the first whose shown band ends below it (with Hide White Space the
/// rects overlap in the hidden margins, and the next page's text already shows there), the last page past the end.
/// A page whose shown part at the top is no more than the gap to the page below it (the next row down) does not count: Go To leaves the
/// pages' margin above a page, which is more than that gap, so a sliver of the page above still shows (#7149).
pub(super) fn viewed_page(caret: Option<(usize, f64, f64)>, top: f64, layout: &PagedLayout, height: f64) -> usize {
match caret {
Some((page, from, to)) if to >= top && from <= top + height => page,
_ => layout.rects.iter().zip(&layout.bands).position(|(r, band)| r.y0 + band.1 > top).unwrap_or(layout.rects.len().saturating_sub(1)),
_ => (0..layout.rects.len())
.position(|i| {
let end = layout.rects[i].y0 + layout.bands.get(i).map_or(0.0, |band| band.1);
// The gap to the first later page whose shown part starts at or below this one's end: the page below,
// whatever the column (an incomplete last row, a Two Up cover) and with Hide White Space (a seam).
let below = |j: &usize| layout.rects.get(*j).is_some_and(|r| r.y0 + layout.bands.get(*j).map_or(0.0, |b| b.0) >= end);
// Measured from the bottom of the row (the tallest page between this one and that page): pages of different
// heights share a row, and the next row starts below the tallest.
let gap = ((i + 1)..layout.rects.len()).find(below).and_then(|j| layout.rects.get(j).map(|next| (j, next))).map_or(0.0, |(j, _)| {
let row_end = (i..j).map(|k| layout.rects[k].y0 + layout.bands.get(k).map_or(0.0, |b| b.1)).fold(end, f64::max);
// The next row's real top: its shorter pages are centred lower, so not `next`'s own top.
let shown = |k: usize| layout.rects[k].y0 + layout.bands.get(k).map_or(0.0, |b| b.0);
let next_top = (j..(j + layout.columns.max(1)).min(layout.rects.len())).map(shown).fold(shown(j), f64::min);
(next_top - row_end).max(0.0)
});
end > top + gap
})
.unwrap_or(layout.rects.len().saturating_sub(1)),
}
}
+10 -24
View File
@@ -60,19 +60,10 @@ pub(crate) fn page_rulers(app: &mut WordApp, ui: &mut Ui, out: &craft::pages::ui
.map(|cg| cg.gaps.iter().map(|&(l, r)| if rtl { (col_end - r, col_end - l) } else { (l - col_x, r - col_x) }).collect())
.unwrap_or_default();
let row_cells = caret_row(app, layout, pi);
let borders_page: Vec<f32> =
row_cells.first().map(|f| std::iter::once(f.x).chain(row_cells.iter().map(|b| b.right())).collect()).unwrap_or_default();
// While a column marker is dragged the markers show where the preview puts their borders (the ruler draws them
// where it is told), so the grabbed marker follows the pointer and the ones right of it move along.
let caret_row_idx = app.session.sel.focus.path.cell().map(|(_, r, _)| r);
let row = crate::table_resize::ruler_row(app, layout, pi);
// Both the ruler markers and Alt widths use the preview of the caret row's actual grid lines.
let mods = crate::table_resize::mods_now(ui.ctx());
let borders: Vec<f32> = borders_page
.iter()
.enumerate()
.map(|(line, &x)| to_start(crate::table_resize::caret_drag(app, pi).and_then(|d| d.ruler_line_x(mods, caret_row_idx, line)).unwrap_or(x)))
.collect();
let row_y = row_cells.first().map_or(0.0, |b| b.y + b.h / 2.0);
let borders: Vec<f32> = row.as_ref().map(|r| r.positions(app, pi, mods).into_iter().map(to_start).collect()).unwrap_or_default();
let bottoms = row_bottoms(app, layout, pi);
let rows: Vec<f32> = bottoms.iter().map(|(_, b)| b.bottom()).collect();
// A section whose columns `column_drag` refuses shows its gaps without grips.
@@ -159,10 +150,13 @@ pub(crate) fn page_rulers(app: &mut WordApp, ui: &mut Ui, out: &craft::pages::ui
}
}
if let Some(d) = output.ruler.column {
let at = borders_page.get(d.border.index).map(|&x| (x, row_y));
let to = (to_page(d.border.position), row_y);
table_drag(app, layout, pi, BorderDrag { phase: d.phase, edge: Edge::Column(d.border.index), at, to, mods: d.mods });
if let Some(d) = output.ruler.column
&& let Some(row) = &row
&& let Some(&(line, x)) = row.borders.get(d.border.index)
{
let at = Some((x, row.y));
let to = (to_page(d.border.position), row.y);
table_drag(app, layout, pi, BorderDrag { phase: d.phase, edge: Edge::Column(line), at, to, mods: d.mods });
}
if let Some(d) = output.row {
let at = bottoms.get(d.index).map(|(_, b)| (b.x + b.w / 2.0, b.bottom()));
@@ -382,14 +376,6 @@ pub(crate) fn text_area(app: &WordApp, layout: &DocLayout, page: usize) -> Optio
Some((b.x + left, (b.w - left - right).max(0.0)))
}
/// The caret row's cells on `page`, left to right.
fn caret_row(app: &WordApp, layout: &DocLayout, page: usize) -> Vec<wordcraft_geom::Rect> {
let Some((_, r, _)) = app.session.sel.focus.path.cell() else { return Vec::new() };
let mut row: Vec<wordcraft_geom::Rect> = cells(app, layout, page).into_iter().filter(|(row, ..)| *row == r).map(|(.., b)| b).collect();
row.sort_by(|a, b| a.x.total_cmp(&b.x));
row
}
/// Each row of the caret's table on `page` with the cell its bottom is taken from: its shortest box, as a vertically
/// merged cell's box spans all its rows, and of those the leftmost.
fn row_bottoms(app: &WordApp, layout: &DocLayout, page: usize) -> Vec<(usize, wordcraft_geom::Rect)> {
+102
View File
@@ -518,6 +518,24 @@ fn the_page_in_view_follows_the_caret_while_it_is_on_screen() {
assert_eq!(viewed_page(caret(2, 90.0), scrolled(330.0), &layout, 100.0), 3, "a caret just above the window is not in view");
}
/// Two Up centres the shorter page of a spread: the next spread's shorter first page starts lower than its row, and
/// the gap to the page above is measured to the row's top, so a visible sliver of page 0 still counts (#7149).
#[test]
fn the_page_in_view_measures_to_the_next_spreads_top() {
use craft::behavior::kurbo::Size;
use craft::pages::layout::{LayoutOptions, PageDisplay, PageSpacing, place_pages};
// Heights 100,100 | 100,200: the taller page of the second spread sits higher than its shorter neighbour.
let sizes = [Size::new(80.0, 100.0), Size::new(80.0, 100.0), Size::new(80.0, 100.0), Size::new(80.0, 200.0)];
let spacing = PageSpacing { gap: 10.0, margin: 0.0, side: 0.0, white_space_pad: 0.0, seam: 1.0 };
let options = LayoutOptions { display: PageDisplay::TwoUp, cover: false, ..LayoutOptions::WORD };
let layout = place_pages(&sizes, 1.0, Size::new(400.0, 400.0), &options, &spacing);
assert!(layout.rects[2].y0 > layout.rects[3].y0, "the shorter page is centred below the row's top");
let row_end = layout.rects[0].y1;
let at = |shown: f64| row_end - shown;
assert_eq!(viewed_page(None, at(spacing.gap * 2.0), &layout, 100.0), 0, "more than the gap of the first spread shows");
assert_eq!(viewed_page(None, at(spacing.gap / 2.0), &layout, 100.0), 2, "less than the gap is a sliver");
}
/// #856: the left margin beside body text is Word's selection bar. A click selects the line,
/// a double-click the paragraph, a triple-click (or Ctrl/⌘+click) the document; dragging
/// selects whole lines and Shift+click extends by lines.
@@ -775,6 +793,24 @@ fn the_text_pointer_stays_off_the_grey_around_the_page() {
assert_ne!(h.output().platform_output.cursor_icon, egui::CursorIcon::Default, "press and move in one frame keep the text pointer");
h.event(egui::Event::PointerButton { pos: beside, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() });
h.step();
// A Ctrl/⌘ press in the grey area is ignored: no unit selection starts and the pointer stays an arrow.
let ctrl = egui::Modifiers::COMMAND;
h.event(egui::Event::PointerMoved(beside));
h.step();
h.event(egui::Event::ModifiersChanged(ctrl));
h.event(egui::Event::PointerButton { pos: beside, button: egui::PointerButton::Primary, pressed: true, modifiers: ctrl });
h.step();
assert!(h.state().canvas.unit_drag.is_none(), "a Ctrl/⌘ press in the grey area does not start a unit selection");
assert!(!h.state().canvas.dragging, "a Ctrl/⌘ press in the grey area does not start a drag");
assert!(h.state().session.sel.is_collapsed(), "a Ctrl/⌘ press in the grey area does not select text");
assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Default, "arrow during a Ctrl/⌘ press in the grey area");
h.event(egui::Event::PointerMoved(further_beside));
h.step();
assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Default, "arrow during a Ctrl/⌘ drag in the grey area");
h.event(egui::Event::PointerButton { pos: further_beside, button: egui::PointerButton::Primary, pressed: false, modifiers: ctrl });
h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE));
h.step();
}
/// #4410: with the Format Painter armed, a double-click on a word paints that word, and the
@@ -2604,6 +2640,72 @@ fn hostile_numbers_are_ignored() {
assert!(h.state().canvas.view.offset.0.is_finite() && h.state().canvas.view.offset.1.is_finite());
}
/// `viewed_page` with the sliver of the page above that Go To leaves at the top of the window: it is not the page in view.
#[test]
fn a_sliver_of_the_page_above_is_not_the_page_in_view() {
let rects: Vec<craft::behavior::kurbo::Rect> =
(0..4).map(|i| craft::behavior::kurbo::Rect::new(0.0, f64::from(i) * 110.0, 80.0, f64::from(i) * 110.0 + 100.0)).collect();
let layout = craft::pages::layout::PagedLayout { rects, size: Default::default(), columns: 1, bands: vec![(0.0, 100.0); 4] };
// The gap between pages is 10; page 2 ends at 320. A window top 4 above its end shows 4 of it: a sliver.
assert_eq!(viewed_page(None, 316.0, &layout, 100.0), 3, "4 points of page 2 is a sliver");
assert_eq!(viewed_page(None, 310.0, &layout, 100.0), 3, "as much as the gap is still a sliver");
assert_eq!(viewed_page(None, 300.0, &layout, 100.0), 2, "20 points of page 2 is the page in view");
}
/// In Columns and Two Up the pages are stored row by row: the gap to measure is the one to the page below, not to the
/// page beside.
#[test]
fn a_sliver_of_a_row_above_is_not_the_page_in_view_with_columns() {
let rects: Vec<craft::behavior::kurbo::Rect> = [(0.0, 0.0), (90.0, 0.0), (0.0, 110.0), (90.0, 110.0)]
.iter()
.map(|&(x, y)| craft::behavior::kurbo::Rect::new(x, y, x + 80.0, y + 100.0))
.collect();
let layout = craft::pages::layout::PagedLayout { rects, size: Default::default(), columns: 2, bands: vec![(0.0, 100.0); 4] };
// The first row ends at 100 and the next starts at 110: a window top at 96 shows 4 points of it, a sliver.
assert_eq!(viewed_page(None, 96.0, &layout, 100.0), 2, "4 points of the row above is a sliver");
assert_eq!(viewed_page(None, 80.0, &layout, 100.0), 0, "20 points of the first row is the page in view");
}
/// A last row that is not full has no page below the one above it: the gap is still the one to the next row.
#[test]
fn a_sliver_of_a_row_above_is_not_the_page_in_view_with_an_incomplete_last_row() {
let rects: Vec<craft::behavior::kurbo::Rect> =
[(0.0, 0.0), (90.0, 0.0), (0.0, 110.0)].iter().map(|&(x, y)| craft::behavior::kurbo::Rect::new(x, y, x + 80.0, y + 100.0)).collect();
let layout = craft::pages::layout::PagedLayout { rects, size: Default::default(), columns: 2, bands: vec![(0.0, 100.0); 3] };
assert_eq!(viewed_page(None, 96.0, &layout, 100.0), 2, "4 points of the row above is a sliver");
assert_eq!(viewed_page(None, 80.0, &layout, 100.0), 0, "20 points of the first row is the page in view");
}
/// Pages of different heights share a row and the next row starts below the tallest: the gap is measured from the row's bottom.
#[test]
fn a_shorter_page_in_a_taller_row_is_still_the_page_in_view() {
let rects: Vec<craft::behavior::kurbo::Rect> = [(0.0, 0.0, 100.0), (90.0, 0.0, 200.0), (0.0, 210.0, 100.0), (90.0, 210.0, 100.0)]
.iter()
.map(|&(x, y, h)| craft::behavior::kurbo::Rect::new(x, y, x + 80.0, y + h))
.collect();
let layout = craft::pages::layout::PagedLayout {
rects,
size: Default::default(),
columns: 2,
bands: vec![(0.0, 100.0), (0.0, 200.0), (0.0, 100.0), (0.0, 100.0)],
};
assert_eq!(viewed_page(None, 50.0, &layout, 100.0), 0, "the short page is fully visible, the row gap is 10 not 110");
assert_eq!(viewed_page(None, 196.0, &layout, 100.0), 2, "4 points of the tall page's row is a sliver");
}
/// Two Up with a cover: page 0 is a row of its own, so there is no page `columns` after it.
#[test]
fn a_sliver_of_the_cover_is_not_the_page_in_view() {
let rects: Vec<craft::behavior::kurbo::Rect> = [(90.0, 0.0), (0.0, 110.0), (90.0, 110.0), (0.0, 220.0)]
.iter()
.map(|&(x, y)| craft::behavior::kurbo::Rect::new(x, y, x + 80.0, y + 100.0))
.collect();
let layout = craft::pages::layout::PagedLayout { rects, size: Default::default(), columns: 2, bands: vec![(0.0, 100.0); 4] };
assert_eq!(viewed_page(None, 96.0, &layout, 100.0), 1, "4 points of the cover is a sliver");
assert_eq!(viewed_page(None, 80.0, &layout, 100.0), 0, "20 points of the cover is the page in view");
assert_eq!(viewed_page(None, 206.0, &layout, 100.0), 3, "4 points of the spread is a sliver");
}
/// A window in the background shows no caret and asks for no frames to blink one (#7674). The page keeps the keyboard
/// focus, so the caret blinks again once the window is active again.
#[test]
+44 -13
View File
@@ -46,6 +46,20 @@ fn click_at(h: &mut H, at: Pos2) {
steps(h, 3);
}
/// A primary double click at `at`: two clicks a few frames apart, inside egui's double click delay.
fn double_click_at(h: &mut H, at: Pos2) {
// Let the click before it age out, or the pair would count as a triple click.
steps(h, 40);
h.event(egui::Event::PointerMoved(at));
for _ in 0..2 {
h.event(button(at, egui::PointerButton::Primary, true));
h.app_frame();
h.event(button(at, egui::PointerButton::Primary, false));
h.app_frame();
}
steps(h, 3);
}
/// A primary drag from `from` to `to` in six moves.
fn drag_between(h: &mut H, from: Pos2, to: Pos2) {
h.event(egui::Event::PointerMoved(from));
@@ -195,7 +209,7 @@ fn ruler_tab_stops_are_set_moved_and_cleared_with_the_pointer() {
let step = 4.5_f32;
let near = |stops: &[(f32, TabAlign)], want: f32| stops.len() == 1 && stops[0].1 == TabAlign::Center && (stops[0].0 - want).abs() <= step;
// Lets the double-click time pass before the next press.
let settle = |h: &mut H| steps(h, 30);
let settle = |h: &mut H| steps(h, 40);
let stops = |h: &H| {
let s = &h.state().session;
let para = s.doc.para_at(&s.sel.focus).expect("a paragraph");
@@ -253,19 +267,27 @@ fn comment_harness() -> (H, u32) {
a.run("select.text", json!({"text": "text"})).unwrap();
let id = a.run("review.newComment", json!({"text": "Original"})).unwrap()["id"].as_u64().unwrap() as u32;
a.run("view.commentsPane", json!({"value": false})).unwrap();
(window(a), id)
(window_dt(a, Some(1.0 / 60.0)), id)
}
/// Click comment `id`'s balloon (from no selected balloon): the card is selected and its own
/// edit has the keyboard in its field.
/// Click comment `id`'s balloon (from no selected balloon): the card is selected with no edit open (as in Word), then
/// a double click opens its message for editing, and takes the keyboard in its field.
fn click_balloon(h: &mut H, id: u32) {
h.state_mut().canvas.comments.selected = craft::behavior::Selection::default();
steps(h, 2);
let card = h.state().canvas.balloon_rects.iter().find(|(i, _)| *i == id).map(|(_, r)| *r).expect("the comment has a balloon");
click_at(h, card.left_top() + vec2(30.0, 8.0));
assert_eq!(h.state().canvas.selected_balloon(), Some(id), "the click selected the balloon");
// The selected card opens its own edit, a framework text field, which takes the keyboard by a click in it
// (none opens where comments can't change).
select_balloon_card(h, id);
open_edit(h, id);
}
/// Double-clicks comment `id`'s card to open message 0 for editing, unless a draft is already open (a refused one
/// is kept), and clicks into its field. Nothing opens where comments can't change.
fn open_edit(h: &mut H, id: u32) {
if crate::app::command_board::command_enabled(h.state(), "review.editComment") {
if h.state().canvas.comments.editing.is_none() {
let card = h.state().canvas.balloon_rects.iter().find(|(i, _)| *i == id).map(|(_, r)| *r).expect("the comment has a balloon");
double_click_at(h, card.left_top() + vec2(30.0, 8.0));
assert!(h.state().canvas.comments.editing.is_some(), "a double click on the card opens its edit");
}
steps(h, 2);
}
use egui::accesskit::Role;
let field = h
.query_by_role_and_label(Role::MultilineTextInput, "Edit")
@@ -277,6 +299,15 @@ fn click_balloon(h: &mut H, id: u32) {
}
}
/// Clicks comment `id`'s card (from no selected balloon): it is selected with no edit open, so Reply shows.
fn select_balloon_card(h: &mut H, id: u32) {
h.state_mut().canvas.comments.selected = craft::behavior::Selection::default();
steps(h, 2);
let card = h.state().canvas.balloon_rects.iter().find(|(i, _)| *i == id).map(|(_, r)| *r).expect("the comment has a balloon");
click_at(h, card.left_top() + vec2(30.0, 8.0));
assert_eq!(h.state().canvas.selected_balloon(), Some(id), "the click selected the balloon");
}
/// Types `text` into the field that has the keyboard.
fn type_in(h: &mut H, text: &str) {
h.event(egui::Event::Text(text.into()));
@@ -327,7 +358,7 @@ fn an_empty_comment_balloon_deletes() {
}
let id = a.run("review.newComment", json!({})).unwrap()["id"].as_u64().unwrap() as u32;
a.run("view.commentsPane", json!({"value": false})).unwrap();
let mut h = window(a);
let mut h = window_dt(a, Some(1.0 / 60.0));
click_balloon(&mut h, id);
let resolve = h.get_by_label("Resolve").rect().center();
click_at(&mut h, resolve);
@@ -382,7 +413,7 @@ fn a_refused_comment_edit_keeps_the_draft() {
#[test]
fn replying_to_a_comment_from_its_balloon_posts_the_reply() {
let (mut h, id) = comment_harness();
click_balloon(&mut h, id);
select_balloon_card(&mut h, id);
h.get_by_label("Reply").click();
steps(&mut h, 3);
type_in(&mut h, "A reply");
+66 -6
View File
@@ -76,16 +76,43 @@ fn new_app() -> WordApp {
WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), crate::Services::default())
}
/// A saved .docx (so AutoSave can cover it) in the harness.
fn autosave_harness() -> (egui_kittest::Harness<'static, WordApp>, std::path::PathBuf) {
let dir = std::env::temp_dir().join(format!("wordcraft-ui-autosave-label-{}", std::process::id()));
/// How [`autosave_harness`] has the saved file in its window.
#[derive(Debug, PartialEq)]
enum Reopen {
/// The window that saved it.
No,
/// Opened in a fresh window, read from disk.
FromDisk,
/// Opened in a fresh window from its bytes, which only names the file.
FromBytes,
}
/// A saved .docx (so AutoSave can cover it), or the same file opened in a fresh window as
/// `reopen` says, with the title bar drawn over it. `files` answers a later Save As pick.
fn autosave_harness(
reopen: Reopen,
files: &std::sync::Arc<craft::host::ScriptedFiles>,
) -> (egui_kittest::Harness<'static, WordApp>, std::path::PathBuf) {
let dir = std::env::temp_dir().join(format!("wordcraft-ui-autosave-label-{}-{reopen:?}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("draft.docx");
let mut a = new_app();
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), crate::Services::default())
.with_host(std::sync::Arc::new(craft::host::Host::builder(crate::APP).files(files.clone()).build()));
a.run("text.insert", json!({"text": "Hello"})).unwrap();
a.run("file.save", json!({"path": path.to_string_lossy()})).unwrap();
assert!(a.autosaves(), "a saved .docx is covered by AutoSave");
if reopen != Reopen::No {
a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), crate::Services::default())
.with_host(std::sync::Arc::new(craft::host::Host::builder(crate::APP).files(files.clone()).build()));
if reopen == Reopen::FromBytes {
let data = wordcraft_engine::cmd::insert::base64_encode(&std::fs::read(&path).unwrap());
a.execute("file.open", json!({"path": path.to_string_lossy(), "data": data})).unwrap();
} else {
a.run("file.open", json!({"path": path.to_string_lossy()})).unwrap();
}
assert!(!a.autosaves(), "an opened file waits for the user's go-ahead");
}
let h = harness(a);
(h, dir)
}
@@ -93,7 +120,8 @@ fn autosave_harness() -> (egui_kittest::Harness<'static, WordApp>, std::path::Pa
/// #3370: clicking the AutoSave switch label toggles AutoSave on and off.
#[test]
fn clicking_the_autosave_label_toggles_autosave() {
let (mut h, dir) = autosave_harness();
let files = std::sync::Arc::new(craft::host::ScriptedFiles::new());
let (mut h, dir) = autosave_harness(Reopen::No, &files);
assert!(h.state().autosaves());
h.get_by_label("AutoSave").click();
crate::test_harness::frames(&mut h, 2);
@@ -104,6 +132,35 @@ fn clicking_the_autosave_label_toggles_autosave() {
let _ = std::fs::remove_dir_all(&dir);
}
/// #3307: a file opened, not saved, in this window had the switch greyed out, and clicking it
/// asked for Save As. Clicking it now turns AutoSave on for that file.
#[test]
fn clicking_autosave_on_an_opened_file_turns_it_on() {
let files = std::sync::Arc::new(craft::host::ScriptedFiles::new());
let (mut h, dir) = autosave_harness(Reopen::FromDisk, &files);
h.get_by_label("AutoSave").click();
crate::test_harness::frames(&mut h, 2);
assert!(h.state().autosaves(), "the switch turned AutoSave on");
assert!(h.state().dialog_host.is_empty() && h.state().file_dialog.is_none(), "without Save As");
let _ = std::fs::remove_dir_all(&dir);
}
/// A document opened from bytes only names its file, so the switch can't hand that file to
/// AutoSave: it shows the block and clicking it asks for Save As, after which AutoSave is on.
#[test]
fn clicking_autosave_on_a_document_opened_from_bytes_asks_for_save_as() {
let files = std::sync::Arc::new(craft::host::ScriptedFiles::new());
let (mut h, dir) = autosave_harness(Reopen::FromBytes, &files);
assert_eq!(h.state().autosave_switch_block(), Some(crate::AutoSaveBlock::NotSavedHere));
let copy = dir.join("copy.docx");
files.queue(craft::host::Picked::Paths(vec![copy.clone()]));
h.get_by_label("AutoSave").click();
crate::test_harness::frames(&mut h, 2);
assert!(copy.is_file(), "Save As saved a copy");
assert!(h.state().autosaves(), "AutoSave covers the copy");
let _ = std::fs::remove_dir_all(&dir);
}
/// #701: the arrow beside Undo lists the session's undo steps, newest first; clicking the third
/// row undoes three steps at once.
#[test]
@@ -744,8 +801,11 @@ fn the_autosave_knob_sits_right_when_on_and_mirrors_right_to_left() {
a.ui.language = "en".into();
// Mark the document as saved here without touching disk (`session.dirty` stays false).
let path = std::path::PathBuf::from("draft.docx");
// A save to the document's own file records both (`note_file_on_disk`): the file is read
// from disk, so the switch can be turned on again after it has been turned off.
a.session.path = Some(path.clone());
a.autosave_path = Some(path);
a.autosave_path = Some(path.clone());
a.read_from = Some(path);
let mut h = harness(a);
// Arabic UI labels draw even when built without `CRAFT_FONTS_DIR` (embedded Arabic faces).
+2 -1
View File
@@ -104,7 +104,8 @@ fn leading(app: &mut WordApp, ui: &mut Ui) -> Option<egui::Rect> {
/// The AutoSave switch: off and with the reason as its tooltip when AutoSave can't cover the document (#196,
/// #176); a click then offers Save As where that helps. Returns the rect it took.
fn autosave(app: &mut WordApp, ui: &mut Ui) -> egui::Rect {
let block = app.autosave_block();
// A file read from disk here is off, not blocked: the switch turns it on (#3307).
let block = app.autosave_switch_block();
let on = app.autosaves() && block.is_none();
let tip = block.as_ref().map_or_else(|| tl!("AutoSave saves every change to the file (needs a saved document)").to_string(), |b| b.reason());
// The small switch, as the old title bar drew it.

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