Compare commits

...
Author SHA1 Message Date
Martin BallandClaude Opus 5.5 568039cd7f fix(ui-egui): a key's edit pass no longer clears the settled pages
A pass that places no page (the edit pass a key triggers) matched the empty
shown pages and reset settled_pages to empty, so that pass asked for unsized
pictures and the next pass's exact-pixel pictures were rendered again on a
worker plus an extra frame (~33 ms CPU, ~4.7 ms main thread per key). Only
settle when at least one page was placed; zoom, resize and scroll still
settle to their exact pixels.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCXNomWeGUu3duixKdm
2026-12-06 21:21:00 +00:00
autocraft-bot[bot] 67096983b6 Merge pull request #9925 2026-12-06 20:15:42 +00:00
batistalucasv 41a8b4b0fc fix(xtask): check craft UI features enabled via package [features] table (#9648) 2026-12-06 17:15:42 -03:00
autocraft-bot[bot] 616ba02027 Merge pull request #9922 2026-12-06 19:38:20 +00:00
batistalucasv 9d7a7044b1 fix(wordcraft): log folder open failure on Unix when syncing nightly session directory (#9870) 2026-12-06 16:38:20 -03:00
autocraft-bot[bot] 152a511502 Merge pull request #9920 2026-12-06 19:23:07 +00:00
batistalucasv 3d0e56d7c6 fix(doc): combine note and body text-box alloc warnings into one per paste (#9918) 2026-12-06 16:23:07 -03:00
autocraft-bot[bot] 0acb3bb409 Merge pull request #9916 2026-12-06 19:06:41 +00:00
autocraft-bot[bot] 0c6325c0b7 Merge pull request #9912 2026-12-06 19:06:41 +00:00
autocraft-bot[bot] 3b9284ec9f Part 1: FindState::set_results in crates/engine/src/doc_state.rs now b
Part 1: `FindState::set_results` in crates/engine/src/doc_state.rs now bumps `results_gen` only when the matches actually change, and `clear_results` bumps only when results were non-empty. Find Next/Previous after a Navigation pane search finds identical matches, so `nav_results_gen` still matches and the pane keeps its highlights and Results list. A search with different matches still bumps the generation, so the advanced-find scope/option cases still show 0 highlights. Added the test `find_next_after_nav_pane_search_keeps_nav_pane_highlights` (edit.findNext and edit.findPrevious after a pane search keep 3 Found marks and '3 results'). fmt, clippy and the find/nav_pane tests pass.
2026-12-06 19:06:41 +00:00
batistalucasv 99cb9aa14d fix(ui-egui): read drawn size and send only edited sides from Size dialog (#9845) 2026-12-06 16:06:04 -03:00
batistalucasv debd74a5ee fix(ui-egui): tie Navigation pane search highlights to its own FindState results generation (#9698) 2026-12-06 15:46:11 -03:00
autocraft-bot[bot] 0368b9fc79 Merge pull request #9910 2026-12-06 18:36:02 +00:00
batistalucasv 61b4d191a7 test(engine): check saving template elsewhere leaves AutoSave stamp alone (#9905) 2026-12-06 15:36:02 -03:00
autocraft-bot[bot] 7186056198 Merge pull request #9907 2026-12-06 18:26:02 +00:00
batistalucasv b9ff92bf62 fix(wordcraft): log folder path when nightly session directory sync fails (#9869) 2026-12-06 15:26:02 -03:00
autocraft-bot[bot] 1f989efaa5 Merge pull request #9903 2026-12-06 18:05:20 +00:00
autocraft-bot[bot] 37b7a98d2a Merge pull request #9883 2026-12-06 18:05:20 +00:00
batistalucasv e8aebb1c88 fix(doc): warn once per paste on text-box part allocation failure (#9872) 2026-12-06 15:05:20 -03:00
autocraft-bot[bot] 24bc0410ec Merge pull request #9902 2026-12-06 17:50:12 +00:00
batistalucasv 79b16d95d2 test(ui-egui): locate print preview outline around page texture (#9895) 2026-12-06 14:50:12 -03:00
autocraft-bot[bot] b37ce04e8f Merge pull request #9893 2026-12-06 17:48:13 +00:00
autocraft-bot[bot] 3148a654b5 Part 2: rotation_window no longer sets InlineJobs on the install spe
Part 2: `rotation_window` no longer sets `InlineJobs` on the install spec, where it had no effect. It now builds the app's `Host` with a `ManualJobs` queue and installs it through `with_host`, so the page-texture loader runs its renders on the host's jobs. Part 1: I removed the settle loop. The new `rotation_window_with_jobs` returns the harness and its `ManualJobs`. It runs the queue after each of the 6 setup frames, then takes one more frame to upload what rendered. `rotation_window` calls it and drops the queue, so the other callers are unchanged. In the rotation drag test, the sample now goes `jobs.run_all()`, then `steps(&mut h, 1)`, then `at_rest`. All of these frames use `app_frame()` through `steps`, so none skips the app's input hook. `cargo fmt --check` is clean. clippy reports only an unused-dependency warning on `egui_extras` in `Cargo.toml`, which my change doesn't touch. The 25 `objects::` tests pass. The rotation drag tests also pass 3 times in a row.
2026-12-06 17:48:13 +00:00
autocraft-bot[bot] 33c9916168 Merge pull request #9898 2026-12-06 17:43:13 +00:00
batistalucasv 074f233ccf docs(ui-egui): clarify SHEET_EDGE background and drop white-only test (#9897) 2026-12-06 14:43:13 -03:00
batistalucasv 9efe148815 test(ui-egui): settle meshes and repaints before sampling at_rest in rotation drag test (#9821) 2026-12-06 14:32:05 -03:00
autocraft-bot[bot] 047726ddea Merge pull request #9894 2026-12-06 17:06:08 +00:00
RickiNano f78836c1b4 Save as Template over the document's own file keeps AutoSave going (#9865)
file.saveTemplate wrote through save_path and never updated
Session::disk_stamp, so after a template was saved over the document's
own .dotx or .dotm, the next AutoSave (ifUnchanged) took WordCraft's own
write for another program's change, refused, and turned AutoSave off.

Write with save_path_checked and keep the stamp it returns when the path
is the document's own file, as file.save's copy branch already does.
2026-12-06 18:06:08 +01:00
autocraft-bot[bot] ce23acdbe6 Merge pull request #9745 2026-12-06 15:52:42 +00:00
batistalucasv 20592b350a test(ui-egui): settle immediate repaints before measuring caret blink delay (#9859) 2026-12-06 12:52:42 -03:00
batistalucasv d8889fccd7 test(ui-egui): locate preview outline by stroke kind and check contrast against actual pane background 2026-12-06 12:40:48 -03:00
batistalucasv 7106bedb9e test(ui-egui): guard wheel-outside-box draft against missing hover check (#9844) 2026-12-06 12:34:04 -03:00
Martin BallandClaude Opus 5.5 508e22d6bb Move craft-libs to 0a15c60 (typing-speed fixes for 0.20.2) (#9862)
* Move craft-libs to 0a15c60 (#4285, #5610, #5315, #6020)

Brings the typing-speed fixes in craft-libs: the idle ribbon replays through
MemoView (#4285, which #8119's chrome slot versions rely on), Thumbnails
renders no picture in a measuring run (#5610, needed by #9417), page
pictures texel for texel (#5315), and a replayed text field keeps its
I-beam (#6020).

Adaptations:
- app/frame.rs keeps the ribbon output only from a real run: with the ribbon
  replaying, the measuring run's output (no tabs) replaced it, so KeyTips
  after an edit showed no badges (F10 then H did nothing).
- Tests that read painted shapes look inside replayed PaintChunks (as
  chrome/tests.rs already does); the icon signature includes texture
  coordinates now that icons share atlas pages (#4271/#4275).
- The save prompt asks Save / Don't Save / Cancel on every OS (craft-libs
  92ed66b43).
- A scrolled-out balloon card reports no name over the view (craft-libs
  #3504); the balloon test still checks that the check reads paint.

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

* Tests: the balloon and save-prompt checks guard what they did before the move

The balloon test's precondition is again that the scrolled-out card keeps its
name (now with bounds of no area, craft-libs#3504), so a name search would
still pass; the save-prompt test also needs the prompt's own Don't Save, not
just the title bar's Save.

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

* Smoke test: the save prompt says Don't Save on every OS

craft-libs 92ed66b43 words the unsaved-changes prompt Save / Don't Save /
Cancel everywhere; the smoke test still looked for "No" off macOS.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-06 15:24:21 +00:00
autocraft-bot[bot] 28fe0c22f7 Merge main (618cbf1d) into the pull request
Resolved the only conflict, in crates/layout/src/tests.rs, where both si

Resolved the only conflict, in crates/layout/src/tests.rs, where both sides had appended tests at the end of the file. I kept both sets: the pull request's header-share test and the tests main added. No conflict markers remain, the layout crate builds, and cargo fmt --check is clean. In cargo test -p wordcraft-layout, 999 tests pass and 5 hyphenation-related tests fail. I looked at only one of them; it found no break in a Polish word, which looks like hyphenation data missing in this workspace. I did not run them on the unmerged branches. The pull request's own test passes.
2026-12-06 14:10:43 +00:00
pakiatandClaude Opus 5.5 a0960a2f24 Ungroup: a header's or footer's share is of the upright page
Headers and footers are laid out upright on the page with its section's
own frame, also in a turned section, so `share_base_on` takes that frame
for them and keeps the recorded body frames for body anchors.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 20:52:26 +07:00
pakiatandClaude Opus 5.5 79fcb028b5 Ungroup: a member's share is of the page frame layout placed the group on
Layout now records on each page the section frames it placed floating
objects with (`Page::sect_frames`): the page's own section, then each
continuous section starting on it, as laid out in the view (reflowed in
the continuous views, unturned in a turned section, Read Mode's too).
`share_base_on` takes the page and the anchor's section and uses that
frame, so a group in a continuous section partway down a page, or in a
turned section in Read Mode, ungroups into members of the sizes it drew.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 20:14:28 +07:00
pakiatandClaude Opus 5.5 52bf2b652e Ungroup: a member's share is of the page the view lays out on
`share_base_on` now takes the layout options and uses the page the
continuous views lay out on (as wide as the window in Web view), as
layout sizes the group there. `Session::view_layout_options` gives the
view's options, which `layout_with` now also uses.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 19:47:00 +07:00
autocraft-bot[bot] 618cbf1de8 Merge pull request #9835 2026-12-06 12:46:59 +00:00
pakiatandClaude Opus 5.5 cd8d4ebc7e Layout: a framed paragraph laid out again keeps its equation numbers
Each layout of a page-anchored framed paragraph after the first counts its
automatic equation numbers from where the first did, so a frame laid out
again for its floats doesn't skip numbers. A frame that hasn't settled is
as tall as the text it ends up with, so body text after it keeps clear of
all its lines. Drops an unused binding in a test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 19:46:59 +07:00
autocraft-bot[bot] 8ce0b94eb2 Merge pull request #9854 2026-12-06 12:42:44 +00:00
autocraft-bot[bot] 3790793312 Merge pull request #9855 2026-12-06 12:42:44 +00:00
NetterSilver a176c9c6b4 fix(docx): log conversion errors instead of dropping them
Alt chunk import and the chart and SmartArt item conversions discarded their error. They now log it with log::warn and keep their return values. log becomes a regular dependency of the crate.
2026-12-06 13:42:44 +01:00
NetterSilver 5817146b39 fix(doc): log failed part and list id allocation
add_part, add_list and the text-box import silently fell back to id 0 or dropped the box when ids ran out. Log these rare failures so the cause is visible; the returned values are unchanged.
2026-12-06 13:38:43 +01:00
autocraft-bot[bot] f5d2f9a03b Merge pull request #9850 2026-12-06 12:24:45 +00:00
NetterSilver a37b2c49b8 fix(wordcraft): log failed token and session-file cleanup
Report a failed removal of the control token file (ignoring a file that is already gone) and failed cleanup or directory sync when writing the nightly session record, instead of silently dropping the result.
2026-12-06 13:24:45 +01:00
autocraft-bot[bot] ed4f43f997 Merge pull request #9847 2026-12-06 12:20:54 +00:00
RickiNano 1a02a850da test(fonts): assert the MONO list itself for compound bold weights (#9838)
uses_generic_serif_or_monospace_fallback also accepts SERIF, so compare
the resolved list with MONO directly.
2026-12-06 13:20:54 +01:00
pakiatandClaude Opus 5.5 6f25fde401 Layout: a frame's text below its own float, where the frame ends up
- A float wrapped top and bottom over a page-anchored frame's first
  line moves the frame's text down by as much as it moved the lines,
  as the flow's lead does: the text is no longer drawn back at the
  frame's top over the float.
- A frame placed from its height (aligned to the bottom or middle) is
  laid out again until it stays put (a few times at most); if it still
  moves, it stays where it ended up and its text goes around its
  floats there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 19:17:41 +07:00
pakiatandClaude Opus 5.5 3e127d222a Ungroup: a member's share is its length over what the share is of
A member drawn past 4000 pt now takes as its share its drawn length
over the length the group's share is of (the page's or margin's, on
the page the group is drawn on), not the group's share scaled by its
part of the group: a group drawn at the longest a share gives (a share
past it, from JSON import) no longer overstates its members. Layout
gives that length out (`share_base_on`), the one `relative_size` uses.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 19:11:01 +07:00
autocraft-bot[bot] 5679d09ea2 Merge pull request #9768 2026-12-06 12:01:21 +00:00
pakiatandClaude Opus 5.5 52354d330a Review: a moved selection ends the navigated change; scoped changes stay apart
- Any command that moves the selection (Next Comment, Find and the
  like, not only caret and select commands) ends the change Next /
  Previous Change selected, except that navigation and the Accept or
  Reject that follows it.
- A table's, row's or cell's change is never folded together with the
  formatting change of the first run after it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 19:01:21 +07:00
autocraft-bot[bot] e9d9d9a1ee Merge pull request #9417 2026-12-06 11:58:07 +00:00
Martin BallandClaude Opus 5.5 ff261e20de Page view: SYNC_PIXELS and WordPages::new docs state the cap
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCXNomWeGUu3duixKdm
2026-12-06 11:58:07 +00:00
pakiatandClaude Opus 5.5 dc1c6f0d39 Layout: a framed paragraph's floats obstruct the page top too
The wrap areas of a page-anchored framed paragraph's floating objects
join the page's framed areas, so a page they reach into is not fresh:
body text a float pushes past the page's foot goes on to the next page
instead of being kept at the bottom edge.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 18:49:37 +07:00
pakiat adcda6de98 Merge remote-tracking branch 'origin/main' into fix/framed-paragraph-objects
# Conflicts:
#	crates/layout/src/tests.rs
2026-12-06 18:48:20 +07:00
RickiNano 880ebb5827 fix(fonts): strip compound bold weights whole in joined mono names (#9838)
The joined-name check stripped the first style suffix in the list that
ended the stem. `bold` comes before `semibold`, `demibold` and
`extrabold`, so `jetbrainsmonosemibold` became `jetbrainsmonosemi` and
fell back to sans. Strip the longest matching suffix instead.
2026-12-06 12:45:22 +01:00
pakiatandClaude Opus 5.5 fcf62f2ba8 Layout: a framed paragraph's own text and front objects
- A page-anchored framed paragraph's own text goes around its floating
  objects as their wrapping says (laid out again with their areas).
- Its objects are added as the flow adds a piece's (`add_items`): those
  in front of the text are raised over text laid out after them, and
  the behind count stays right.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 18:44:58 +07:00
autocraft-bot[bot] c098d6483c Merge pull request #9816 2026-12-06 11:44:26 +00:00
autocraft-bot[bot] c6c38616ad Merge main (4d080463) into the pull request 2026-12-06 11:44:26 +00:00
pakiat 02dd9df9dd Merge remote-tracking branch 'origin/main' into fix/relative-size-follow-ups
# Conflicts:
#	crates/engine/src/cmd/objects/tests.rs
2026-12-06 18:42:42 +07:00
Martin BallandClaude Opus 5.5 1023240607 Page view: a caret page up to 4 Mpx renders in the key's frame
A Letter or A4 page at 100 % on a 2x display is about 3.4 Mpx; at 2.5 Mpx it
went to a worker and lost the same-frame letter, though a worker render waits
a frame or more anyway.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCXNomWeGUu3duixKdm
2026-12-06 11:36:43 +00:00
pakiatandClaude Opus 5.5 d52321841e Layout: body text wraps around a framed paragraph's floats
The floating objects of a page-anchored framed paragraph add their
wrap areas, placed as they are drawn from the frame, so the body text
after it goes around them as it did when the paragraph flowed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 18:34:21 +07:00
pakiatandClaude Opus 5.5 1cb3dad2a6 Ungroup: a member past 4000 pt keeps its size as a share
A member a share-sized group draws past the 4000 pt an object's own
size stops at takes its part of the group's share of the page or
margin, so it keeps the size it showed; smaller ones take their size
outright, as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 18:34:21 +07:00
pakiatandClaude Opus 5.5 f51d855a2f Review: resolve only the navigated cell change, and step past it
- The navigation target keeps which of a cell's changes it is (the
  table's, the row's, the cell's formatting, or its tracked merge), so
  Next Change steps from one to the next when one revision made more
  than one of them, and Accept or Reject resolves that change alone: a
  tracked merge no longer rejects the cell's formatting with it.
- A click elsewhere (`set_selection`) ends the navigation, as a caret
  command does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 18:34:20 +07:00
autocraft-bot[bot] 0c3ce08789 Merge pull request #9804 2026-12-06 11:34:20 +00:00
pakiatandClaude Opus 5.5 0cfe0c2ff2 AutoSave: fail closed without a baseline, stamp after closing
- A conditional save to the document's own file with no stamp of how
  it looked (missing a moment while it was read, say) writes nothing.
- A copy written over the document's own file is its stamp now.
- The written file is closed before its metadata is read: Windows
  settles the last-write time only then.
- The stamp's limit is stated: a writer that keeps both size and
  modified time goes unseen, as no content is read.
- The test's external writes are each later than the one before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 18:34:20 +07:00
Martin BallandClaude Opus 5.5 750767d367 Render the caret page in the pass only up to a pixel budget
A whole page at 200 % on a 2x screen is ~14 Mpx; rendered on the UI thread per key it stalls typing.
Pictures over 2.5 Mpx go to a worker as before; zoomed past the texture side, the part in view still
renders in the pass when it fits.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCXNomWeGUu3duixKdm
2026-12-06 11:18:01 +00:00
autocraft-bot[bot] 29b301b5d6 Merge main (d3e824f2) into the pull request 2026-12-06 11:08:36 +00:00
pakiatandClaude Opus 5.5 092989cf28 Layout: a page-anchored framed paragraph draws its objects
A body paragraph framed against the page is placed apart from the flow
(#6535), and that path laid out only its text: the pictures, shapes and
text boxes in it were left out, so a logo in a framed letterhead left an
empty gap on screen and in PDF. They are placed with it now, as the
flow and Outline view place a paragraph's objects: floating ones from
the frame, those in line with its lines, and both can be selected.

Fixes #8530

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 18:08:09 +07:00
pakiat 0ad62cd7a1 Merge remote-tracking branch 'fork/fix/autosave-keeps-external-changes' into fix/autosave-keeps-external-changes 2026-12-06 17:58:09 +07:00
Martin Ball 7e22997bda Merge remote-tracking branch 'origin/main' into merge/9417 2026-12-06 10:42:32 +00:00
autocraft-bot[bot] 037b7f02f3 Merge main (eaf8c825) into the pull request 2026-12-06 10:35:51 +00:00
pakiatandClaude Opus 5.5 8e7bf6bc1f AutoSave: check again just before writing, keep the stamp on rename
- A checked save looks at the file once more when its new bytes are
  ready, just before they replace it (`safe_save::write_checked`), and
  writes nothing if another program changed it meanwhile.
- The stamp recorded after a save is the written file's, taken before
  the rename, not whatever is at the path afterwards.
- `file.open` takes the stamp before it reads the file.
- A rename keeps the stamp taken when the file was read or saved: the
  file keeps its size and modified time, so a change made before the
  rename still counts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 17:24:46 +07:00
autocraft-bot[bot] aab76383c5 Merge pull request #9795 2026-12-06 10:22:39 +00:00
autocraft-bot[bot] 4d080463a7 Merge pull request #9780 2026-12-06 10:22:39 +00:00
autocraft-bot[bot] d3e824f25b Merge pull request #9758 2026-12-06 10:22:39 +00:00
Martin BallandClaude Opus 5.5 eaf8c8256c Caret: no blink-timer wakeups while a selection hides the caret (#9770)
The 530 ms blink repaint was scheduled whenever the editor had focus,
including when a text selection hides the caret, so an idle window with
text selected redrew about twice a second for nothing.


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

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-06 10:22:39 +00:00
autocraft-bot[bot] e85833b8f9 Merge pull request #9781 2026-12-06 10:22:39 +00:00
autocraft-bot[bot] 6d8bfcd192 Merge pull request #9766 2026-12-06 10:22:39 +00:00
autocraft-bot[bot] 8ddc5c2f53 Merge pull request #9752 2026-12-06 10:22:39 +00:00
autocraft-bot[bot] 3bb6faee18 Merge pull request #9769 2026-12-06 10:22:39 +00:00
autocraft-bot[bot] 999a25c676 Merge pull request #9712
With AutoCraft's conflict resolution e1a18a78.
2026-12-06 10:22:39 +00:00
autocraft-bot[bot] a3d820c90d Merge pull request #9809 2026-12-06 10:22:39 +00:00
autocraft-bot[bot] 8f15b2c4b8 Merge pull request #9744 2026-12-06 10:22:39 +00:00
autocraft-bot[bot] ec35d69f7b Merge pull request #9737 2026-12-06 10:22:39 +00:00
autocraft-bot[bot] 3c67b24aef Merge pull request #9735 2026-12-06 10:22:39 +00:00
autocraft-bot[bot] 48d111ea23 Merge pull request #9733 2026-12-06 10:22:39 +00:00
batistalucasv 3e5c75673b refactor(ui-egui): share status_bar_message and update slot version doc (#9815) 2026-12-06 07:20:03 -03:00
pakiatandClaude Opus 5.5 e6be3e0a70 Relative size follow-ups: fitted boxes, large groups, inline ungroup
Follow-ups to #9716 from its review:
- A text box that fits its text keeps the height of its text whatever
  share of a height it holds, as Word for Windows draws it (five lines
  120.95 pt high where half the margin is 346.9 pt). The share is
  applied once, in `drawn_size`; `float_rect` places the object at the
  size it is given.
- A group's members, scaled with the group, fill it past 4000 pt, up to
  the longest side a share gives (`MAX_SHARE_LEN`), in drawing and in a
  connector's fallback ends alike.
- Ungrouping a group in line with text keeps its members at the size it
  showed them at (its own), not the size its share would give.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 17:12:49 +07:00
pakiatandClaude Opus 5.5 69c9228e44 Resolve the navigated cell change, and list it after a nested table
- Next / Previous Change remembers a table's, row's or cell's change it
  selected, as it does a style's, so Accept or Reject resolves that
  change rather than tracked text that starts the same cell.
- A cell that starts with a nested table lists its changes at its own
  first paragraph.
- A tracked merge kept in a cell's properties before a formatting
  change keeps naming its revision when revisions are compacted.
- A new cell (an inserted row, a split) takes no tracked merge.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 17:07:53 +07:00
batistalucasv 5081e0b065 fix(engine): use drawn size and clear shares in picture.size (#9802) 2026-12-06 06:58:46 -03:00
Martin BallandClaude Opus 5.5 b66f352171 Status bar: run live while the kept comment-draft reason shows (#9790)
#8119 memoised the status bar, but its version did not cover the reason
shown for a comment draft kept after Undo of Reopen, so the bar replayed a
record without it, or with it shortened (main CI red since c28b01dc27:
undoing_comment_reopen_keeps_the_draft_for_the_next_reopen). The reason
stands in for a status message, so it runs live as a status message does.


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

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-06 09:53:22 +00:00
pakiatandClaude Opus 5.5 bd0bbb51de AutoSave never writes over a file another program changed
Each open document now keeps the size and modified time its file had
when it was read or last saved. AutoSave saves with `ifUnchanged`,
which refuses, writing nothing, once another program has changed or
removed that file. The status bar then says so, and AutoSave stops for
the file until the user saves it, as after any AutoSave failure. A save
the user asks for writes as before.

Before, a document saved once (which turns AutoSave on) wrote over any
newer version another tool had written as soon as it was edited again.

Refs #7069

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 16:47:11 +07:00
batistalucasv 4d9252c315 fix(layout): invalidate cached layout when removing section break (#9791) 2026-12-06 06:36:49 -03:00
Martin Ball be120a1279 Merge remote-tracking branch 'origin/main' into merge/9417
Merge main into edited-page-same-frame (resolve #8720 WordPages conflict)
2026-12-06 09:18:26 +00:00
batistalucasv 5f6eccbfd3 test(engine): cover non-Unix Unicode-lowercase guard in accept_canonical_entry (#9776) 2026-12-06 06:09:54 -03:00
batistalucasv 2cb1b80d36 fix(engine): use with_path in validate_text_fill (#9779) 2026-12-06 06:06:01 -03:00
autocraft-bot[bot] e840dfdbb8 Merge main (9de73dda) into the pull request 2026-12-06 08:45:30 +00:00
autocraft-bot[bot] b93d12e5a5 Merge main (9de73dda) into the pull request 2026-12-06 08:44:15 +00:00
batistalucasv 0f009c8eac test(ui-egui): check caret stays put when opening list on focused page (#9755) 2026-12-06 05:33:08 -03:00
pakiatandClaude Opus 5.5 d287f4d93b Keep a tracked cell merge or split, and resolve it as Word does
The document model has a cell's tracked vertical merge or split
(`w:cellMerge`, read and written by craft-docx), as the shared model
does. Review lists it as Word for Windows does, as merged cells or
split cells, by its author. Accepting or rejecting it, one or all,
drops only the record and leaves the cells as they are, as Word does.
Its revision is kept and renumbered like the others' when changes are
resolved or content is pasted, and Compare leaves it out.

Fixes #7207

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 15:28:12 +07:00
RickiNano e9e7246417 fix(validate): only the package's own _rels/.rels gives story roles without an owner (#8937)
story_roles skipped a relationships part only when it had an owning part that
is not reachable. rels_owner_name has no owner for any `<dir>/_rels/.rels`,
so a `word/_rels/.rels` that nothing reads was taken as the package
relationships and its declarations gave story roles to parts nothing links to.
A header relationship there to an unlinked part failed the package with two
MATH-PLACEMENT errors.

A source with no owning part now counts only when it is `_rels/.rels`, the
same root that package reachability starts from.
2026-12-06 09:18:59 +01:00
autocraft-bot[bot] 4675f0a863 Merge pull request #9724 2026-12-06 08:15:10 +00:00
Lucas Batista Vargas 9de73dda6d Caret: skip 16 ms blink-fade repaints when the caret does not animate (#8451) (#8680) 2026-12-06 08:15:10 +00:00
autocraft-bot[bot] d9bc1e7049 Merge pull request #9722 2026-12-06 08:15:10 +00:00
autocraft-bot[bot] 8fc6462b1f Merge pull request #9716 2026-12-06 08:15:10 +00:00
autocraft-bot[bot] 89940704d6 Merge pull request #9668 2026-12-06 08:15:10 +00:00
autocraft-bot[bot] 62e40abe4f Merge pull request #9690 2026-12-06 08:15:10 +00:00
batistalucasv c364381bc3 docs(doc): clarify Counters::seen start override restarts (#9746) 2026-12-06 05:09:56 -03:00
Lucas Batista Vargas c28b01dc27 perf(ui-egui): wire AppShell slot versions for MemoView chrome replay (#8115) (#8119)
* perf(ui-egui): wire AppShell slot versions for MemoView chrome replay (#8115)

* test(chrome): fix E0502 borrow order in ribbon_slot_version invalidation check

* fix(ui-egui): hash missing non-rev state and keep ribbon context menu live in slot versions

* fix(ui-egui): version the status bar on layout page count and expired status messages (#8115)

* fix(ui-egui): drop needless mut on status bar test closure (#8115)

* perf(chrome): use cached_state, hash remembered split-button colours, and trim slot tests (#8115)
2026-12-06 08:08:56 +00:00
batistalucasv b7cdaf5298 test(ui-egui): replace h.run() in nav_pane_tabs_switch_on_click with bounded wait 2026-12-06 05:00:52 -03:00
pakiatandClaude Opus 5.5 f30e3f8efd Keep a share of the page with its object and its drawn page
- A linked box sized as a share of the page or a margin splits its
  chain's text at its size on the page it is drawn on: a pass that
  finds such boxes on even pages lays the document out again with them
  (bounded), as for per-page footnotes and PAGEREFs.
- A linked box in line with text keeps its own size.
- A text box that fits its text does so at the width its share gives.
- A share past 4000 pt keeps its size (Word: 600 % of an A4 margin
  height is 4185 pt), up to 1000 % of a 22-inch page.
- Grouping doesn't hand the first member's share to the group;
  ungrouping a share-sized group places its members as it showed them
  and hands them no share; a size set by dragging replaces the share.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 14:54:27 +07:00
batistalucasv 66ec03bc96 fix(fonts): match joined mono/code names case-insensitively (#9740) 2026-12-06 04:45:07 -03:00
batistalucasv 081975251d docs(typing-parity): note Backspace-restores-i is not yet checked in Word 2026-12-06 04:29:27 -03:00
batistalucasv 782b141088 fix(ui-egui): require pointer hover to start wheel_run_box run (#9732) 2026-12-06 04:21:45 -03:00
pakiatandClaude Opus 5.5 664819bc12 Size mirrored margins, tight outlines and linked boxes as drawn
- A share of the left or right margin follows mirror margins: on an even
  page the two swap, as Word for Windows draws them.
- Tight and Through wrapping work a shape's geometry out at the size the
  share gives it, the size it is drawn at.
- A linked box sized by a share takes its part of the chain's text at
  that size (taken on an odd page, as the text is split before the
  boxes are placed).
- Resizing an object drops the share of the side it changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 14:19:47 +07:00
autocraft-bot[bot] 17bfad4d47 The PR makes styles.modify errors carry the full nested field path. A
The PR makes `styles.modify` errors carry the full nested field path. A gradient stop with a bad `pos` now reports `chr.textEffects.fill.stops[0].pos`. The test `styles_modify_rejects_unknown_para_and_chr_fields`, which came in from main (#9635), still expected the old path ending at `stops[0]`, followed by a backtick. In the merged tree it failed with `chr.textEffects.fill.stops[0].pos: invalid type`. The test was out of date, not the code, so I changed its expected substring to `chr.textEffects.fill.stops[0].pos` and updated the comment. The assertion still checks the path, and I didn't weaken or skip anything. The four `styles_modify` tests pass in the pod, and `cargo fmt --check` is clean. I didn't run clippy, since the only change is a test string.
2026-12-06 07:12:02 +00:00
batistalucasv e91780bf25 test(ui-egui): verify undo depth, reply draft, and missing-caret target on parked resolve refusal 2026-12-06 04:11:06 -03:00
autocraft-bot[bot] 6831888562 Part 1: border_group in crates/layout/src/boxes.rs now returns false w
Part 1: `border_group` in crates/layout/src/boxes.rs now returns false when either paragraph is empty and ends a section. This is the same check `paragraph_props` uses to drop borders. `joined()` goes through `border_group`, so it covers `Rooms::of`, the two uses in flow.rs and the use in boxes.rs. The paragraph before the empty one is no longer treated as joined to it, so it closes the box with its own bottom border. I added the test `a_bordered_paragraph_before_an_empty_section_ending_one_keeps_its_bottom_border` in crates/layout/src/tests.rs. It lays out 'Intro', 'AAA' and an empty section-ending paragraph, with the same top and bottom borders on the last two, and expects two rules. With the check removed it fails with 1 rule; with the fix it passes. `cargo fmt --all --check` and `cargo clippy -p wordcraft-layout --all-targets -- -D warnings` are clean. The `wordcraft-layout` tests gave 982 passed and 1 failed. The failure is `a_megabyte_long_word_lays_out_quickly`, a timing test (limit 15 s) that took about 23 s when I reran it alone. It has no borders or sections in it, so I think it is unrelated to this change, but I did not run it on the base commit.
2026-12-06 07:06:07 +00:00
autocraft-bot[bot] fab9d37e94 Merge main (486d8d88) into the pull request 2026-12-06 06:58:46 +00:00
autocraft-bot[bot] 56f29ad63b Merge pull request #9723 2026-12-06 06:51:16 +00:00
batistalucasv 5365c8cf38 test(ui-egui): step extra frames after nav-pane tab switch to verify highlights stay 2026-12-06 03:51:16 -03:00
pakiatandClaude Opus 5.5 3c17af0b33 Layout: an empty paragraph that ends a section draws no shading or borders
Measured in Word for Windows (#3975): an empty paragraph that ends a
section shows neither its shading nor its borders, whether the next
section is continuous or starts a new page. One with text shows both, as
does an empty paragraph that ends no section, the document's last
included. WordCraft drew a band of the shading, under the next section's
first line when the break is continuous.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 13:48:34 +07:00
batistalucasv f427ffaeb8 fix(engine): allow non-ASCII case and normalization in accept_canonical_entry (#9368) 2026-12-06 03:48:07 -03:00
autocraft-bot[bot] 81606422b0 Merge pull request #9718 2026-12-06 06:44:56 +00:00
batistalucasv 1350088cc9 test(ui-egui): cover missing-caret-target and reply draft in refused resolve test 2026-12-06 03:44:56 -03:00
autocraft-bot[bot] e1395ea0e4 Merge pull request #9717 2026-12-06 06:37:43 +00:00
batistalucasv d4fde6aca1 fix(ui-egui): do not announce missing-font note when opening bullet Font dialog (#9671) 2026-12-06 03:37:43 -03:00
pakiatandClaude Opus 5.5 2230170703 Layout: an anchored object sized relative to the page or a margin takes that size
Word sizes an anchored object by wp14:sizeRelH / wp14:sizeRelV instead of
its own size (#6770). Measured in Word for Windows (A4, margins left 90,
right 54, top 60, bottom 80): a share of the page is of the page's width
or height; of the margin, of the text area; of a margin, of its width.
On an odd page the inside margin across is the right one and the outside
the left, swapped on an even page; down, both are the top margin on an
odd page and the bottom one on an even page. A share of 0 leaves the
object its own size; one past 100 % reaches past the page.

Float::rel_w / rel_h carry the share under craft-wordmodel's names, so
the DOCX bridge brings it once craft-libs reads it, and float_rect sizes
an object on a page by it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 13:36:35 +07:00
autocraft-bot[bot] 8f3e96772d Merge pull request #9713 2026-12-06 06:33:14 +00:00
batistalucasv 09bc4e4a45 test(ui-egui): assert Add Font action row appears in font_box dropdown 2026-12-06 03:33:14 -03:00
batistalucasv 05cf886ab4 fix(ui-egui): keep Print Preview sheet edge bands for sub-point room (#9693) 2026-12-06 03:32:25 -03:00
autocraft-bot[bot] c85379bbe7 Merge pull request #9687 2026-12-06 06:20:33 +00:00
autocraft-bot[bot] 2620a9f1bb Merge pull request #9653 2026-12-06 06:20:33 +00:00
autocraft-bot[bot] 6a3a208a6c Merge pull request #9707 2026-12-06 06:20:33 +00:00
batistalucasv b23a16f8a4 test(ui-egui): drop duplicate page-focused content-control list test 2026-12-06 03:20:33 -03:00
autocraft-bot[bot] f6bda47096 Merge pull request #9705 2026-12-06 06:16:59 +00:00
batistalucasv ac5d86f236 fix(ui-egui): announce missing-font note when family changes with same substitute (#9670) 2026-12-06 03:16:59 -03:00
pakiatandClaude Opus 5.5 5be4504db6 Layout: the keep look-ahead measures a table with its own counters
A table after a paragraph that ends a section was measured with the live
list counters, so a list flagged to restart after the break was counted
on there. It now uses the look-ahead's counters and puts the live ones
back, and a test covers the look-ahead's reset at a section end.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 13:13:28 +07:00
autocraft-bot[bot] 55fdffb5d4 Merge pull request #9704 2026-12-06 06:12:21 +00:00
autocraft-bot[bot] f744ce5c26 Merge pull request #9697 2026-12-06 06:12:21 +00:00
autocraft-bot[bot] ad02ec59dd Merge pull request #9696 2026-12-06 06:12:21 +00:00
autocraft-bot[bot] 97607ddbc1 Merge pull request #9672 2026-12-06 06:12:21 +00:00
pakiatandClaude Opus 5.5 7f417bc8ce Lists: a restarted level starts where the restarting list says
Measured in Word for Windows (CodeRabbit asked): a level a paragraph of a
list restarts, by counting above it, starts again at that list's start
override for it, every time, or else at that list's own definition's
start; a level not restarted yet counts from the abstract list's start.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 13:12:21 +07:00
batistalucasv 1fc3c20a60 docs(engine): restore split doc comment on resolve_comment 2026-12-06 03:11:50 -03:00
autocraft-bot[bot] 858424639f Merge pull request #9654 2026-12-06 06:10:01 +00:00
autocraft-bot[bot] 4afb29ac98 Merge pull request #9624 2026-12-06 06:10:01 +00:00
autocraft-bot[bot] cda273f0bb All three failing checks hit the same clippy error: `clippy::cognitive-c
All three failing checks hit the same clippy error: `clippy::cognitive-complexity` (41, limit 30) on `undoing_comment_reopen_keeps_the_draft_for_the_next_reopen`, which the PR's added assertions had made too complex. I split the test body in `crates/ui-egui/src/canvas/tests/markup.rs` into two helpers, `assert_ordinary_resolved_comment_is_read_only` and `reopen_kept_draft_from_the_pane`. The assertions moved unchanged, so none were dropped or loosened, and no lint was silenced. The test itself was not wrong. `cargo clippy -p wordcraft-ui-egui --all-targets -- -D warnings -D clippy::cognitive-complexity` is clean, `cargo fmt --check` passes, and the Undo/Reopen test passes. I did not run the later gate steps (test, i18n-report, language, doctest, assets, layers, wasm); CI skipped them after the clippy failure.
2026-12-06 06:10:01 +00:00
batistalucasv ef4d2c02e1 test(ui-egui): check 3:1 contrast on rendered print-preview sheet edge 2026-12-06 03:09:11 -03:00
batistalucasv 3586d9dfb3 fix(fonts): split CamelCase tokens in is_mono_name (#9694) 2026-12-06 03:05:18 -03:00
batistalucasv 1c24e278e8 test(ui-egui): rename later-V test to reflect no-paste check 2026-12-06 03:00:33 -03:00
batistalucasv 747246e9d4 fix(ui-egui): hide Navigation Results when find.query differs from nav_query (#9684) 2026-12-06 02:57:01 -03:00
autocraft-bot[bot] 486d8d886d Merge pull request #9683 2026-12-06 05:49:32 +00:00
autocraft-bot[bot] 54e8d50915 Merge pull request #9682 2026-12-06 05:49:32 +00:00
autocraft-bot[bot] 487fcd51f6 Merge pull request #9676 2026-12-06 05:49:32 +00:00
autocraft-bot[bot] 77534eefa2 Merge pull request #9665 2026-12-06 05:49:32 +00:00
autocraft-bot[bot] adfd9c96d9 Part 1: wheel_run_box in crates/ui-egui/src/ribbon/home.rs now saves
Part 1: `wheel_run_box` in `crates/ui-egui/src/ribbon/home.rs` now saves a run's `from` as the value the host applied this pass, not the selection's value at the start of the pass. I added an `applied: fn(&R) -> Option<String>` parameter. The Font box passes its `picked` value. So when a Commit and a following Begin/Update land in the same pass, the run goes on from the committed font A. On the next pass `run.from == current` holds, so the box stays bound to font B and the picker doesn't cancel the run. The Font Size box passes `|_| None`, so its behaviour is unchanged. I did not add a test that drives a Commit and a new wheel gesture in one pass. `cargo fmt` and `cargo clippy -p wordcraft-ui-egui --all-targets -D warnings` are clean apart from an existing unused-dependency warning for `egui_extras` in `Cargo.toml`. `cargo test` on the lib filtered to `font`/`wheel` passed (71 tests). nextest isn't installed here, so I used `cargo test`.
2026-12-06 05:49:32 +00:00
batistalucasv d023b003bc fix(ui-egui): zero gutter in temporary Page Setup margins for any gutter change (#9667) 2026-12-06 02:46:45 -03:00
batistalucasv 928c1209dc fix(ui-egui): validate parked resolveComment target before flushing drafts (#9666) 2026-12-06 02:41:17 -03:00
batistalucasv 4c2a68ead3 docs(engine): document exact negative vertical margins in layout.pageSetup params 2026-12-06 02:39:55 -03:00
pakiatandClaude Opus 5.5 5d83b814a9 Layout: lists restart after a section break in balanced columns and in the keep look-ahead
Balancing lays a section's blocks out again before the next section, and
didn't start the flagged lists over after the paragraph that ends it, so
the next section went on counting. The keep-with-next look-ahead from a
paragraph that ends a section counted the next label on too. Both now
start them over as placing a block does (#7382).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 12:33:59 +07:00
batistalucasv ca5fcfe770 docs(layout-parity): drop stale duplicate Colour emoji row 2026-12-06 02:31:36 -03:00
autocraft-bot[bot] 43d82a9271 Merge pull request #9660 2026-12-06 05:30:53 +00:00
autocraft-bot[bot] 145ed5dcee Merge pull request #9637 2026-12-06 05:30:53 +00:00
batistalucasv d781b24f77 test(engine): test resolve_entry canonicalize-race guard via injected canonicalize 2026-12-06 02:30:53 -03:00
pakiatandClaude Opus 5.5 eb97039efd Lists: a level a list defines itself counts on with its abstract list
A list that defines a level itself (Word's w:lvlOverride/w:lvl) started
that level at its own w:start when used first. Word counts it on with the
abstract list from the abstract list's start, and uses the level's own
start only with a start override, which restarts the level there (#7381).

Measured in Word for Windows, abstract list starting at 5, the second
list defining level 1 as upperLetter starting at 3: lists 1, 2, 2, 1, 2
give 5. F. G. 8. I., and lists 2, 2, 1, 2 give E. F. 7. H.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 12:26:39 +07:00
autocraft-bot[bot] 270e2b4cf5 Merge main (dae72f1f) into the pull request 2026-12-06 05:26:08 +00:00
batistalucasv f517682308 fix(engine): include nested field paths on all deserialize_strict errors (#9663) 2026-12-06 02:26:08 -03:00
batistalucasv ba03cafc06 fix(ui-egui): share wheel-step focus handling for Font Size box (#9351) 2026-12-06 02:21:01 -03:00
batistalucasv 25832e27df docs(layout-parity): update 2026-11-05 metric-notice history entry and status line 2026-12-06 02:19:31 -03:00
pakiatandClaude Opus 5.5 5214c4b4c2 Lists: a list that restarts after a section break starts over there
Word 2013 flags a list definition that starts over after each section
break (w15:restartNumberingAfterBreak). WordCraft's model had no place for
it, so the bridge from craft-docx dropped it on the way in and out, and
the list counted on across the break (#7382).

Measured in Word for Windows, modes 14 and 15: with the flag every level
starts over after a section break, continuous or next page; without it,
or set to 0, the list goes on; a page break doesn't restart it.

AbstractNum::restart_after_section_break carries it under the same name
as craft-wordmodel's, and Counters::section_break starts those lists
over. Every walk that counts labels in document order calls it after a
paragraph that ends a section: layout (and its look-ahead for kept
paragraphs), STYLEREF, word count, numbered references, the table of
contents and the navigation pane.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 12:08:53 +07:00
autocraft-bot[bot] dae72f1fc3 Merge pull request #9646 2026-12-06 05:05:14 +00:00
autocraft-bot[bot] 6e9cdedbd9 Merge main (dae72f1f) into the pull request 2026-12-06 05:05:14 +00:00
batistalucasv 7d28496e44 fix(fonts): match mono/code font fallback by whole word (#9542) 2026-12-06 02:05:14 -03:00
autocraft-bot[bot] dbdc91c0ef Merge pull request #9645 2026-12-06 05:00:43 +00:00
batistalucasv 0d1e17caac test(ui-egui): include U+3400 in CJK recover-font test name 2026-12-06 02:00:43 -03:00
autocraft-bot[bot] ce19d7e489 Merge pull request #9642 2026-12-06 04:57:17 +00:00
batistalucasv cd73cda596 fix(ui-egui): read FontForm state through format.state (#9605) 2026-12-06 01:57:17 -03:00
autocraft-bot[bot] 324c966cd5 Merge pull request #9641 2026-12-06 04:50:41 +00:00
batistalucasv bcdade51c5 test(ui-egui): scope unsaved-changes border flash count to dialog rect after settle 2026-12-06 01:50:41 -03:00
autocraft-bot[bot] 9ea934b827 Merge pull request #9639 2026-12-06 04:46:19 +00:00
batistalucasv 603659448f fix(engine): include stop path on gradient stop decode errors (#9635) 2026-12-06 01:46:19 -03:00
autocraft-bot[bot] f72e79bc42 Part 1: The status-bar hint was not cut short. A debug dump of the paint
Part 1: The status-bar hint was not cut short. A debug dump of the painted text showed the whole sentence "Comment edits paused. Reopen the comment with the draft." in the 1440-px window. The test failed because `paints_inside` needs the text's visual bounds to sit inside the clip rect, and here they overshoot it by 0.2 px (826.6 against 826.4). The product code is unchanged. In `crates/ui-egui/src/canvas/tests/markup.rs` I added a helper, `paints_whole`. It passes only if one painted text shape holds exactly the full hint, so a message shortened with an ellipsis fails it. It allows 1 px of tolerance against the shape's clip rect. `undoing_comment_reopen_keeps_the_draft_for_the_next_reopen` now asserts `paints_whole(&h, KEPT_DRAFT_STATUS)` in place of the failing `paints_inside` check. After the change, the 28 comment tests in `wordcraft-ui-egui --lib` pass, including the Undo/Reopen test. `cargo fmt --check` is clean. `cargo clippy --all-targets` ran with no code warnings, only an existing unused-dependency warning for `egui_extras` in `Cargo.toml`. I did not run the full lib test suite.
2026-12-06 04:44:21 +00:00
autocraft-bot[bot] 26e5ddde7f Merge pull request #9634 2026-12-06 04:37:23 +00:00
batistalucasv 358477e66e fix(layout): scope substituted_fonts_on to placed page lines (#9533) 2026-12-06 01:37:23 -03:00
autocraft-bot[bot] efc27bf2dd Merge pull request #9614 2026-12-06 04:29:13 +00:00
autocraft-bot[bot] 37de70f4be Merge pull request #9460 2026-12-06 04:29:13 +00:00
autocraft-bot[bot] 658baf1abd Merge pull request #9633 2026-12-06 04:29:13 +00:00
autocraft-bot[bot] 2c8603af51 Merge pull request #9632 2026-12-06 04:29:13 +00:00
autocraft-bot[bot] 74a5b8a741 Merge pull request #9622 2026-12-06 04:29:13 +00:00
batistalucasv 1bbed31880 docs(layout-parity): merge duplicate Default font metrics and Thai distributed rows 2026-12-06 01:29:13 -03:00
autocraft-bot[bot] 421b0d057e Merge pull request #9627 2026-12-06 04:29:13 +00:00
batistalucasv 0131ef69a0 fix(ui-egui): validate resolveComment target before saving drafts (#9389) 2026-12-06 01:29:01 -03:00
autocraft-bot[bot] 8c53692712 Merge main (6e1b53ed) into the pull request 2026-12-06 04:27:59 +00:00
autocraft-bot[bot] 38b93f401f Merge pull request #9631 2026-12-06 04:22:34 +00:00
batistalucasv 5a8c22c43c fix(engine): drop pending lowercase i restore when caret moves (#9392) 2026-12-06 01:22:34 -03:00
autocraft-bot[bot] b297bc56a1 Part 1: I removed self.nav_query.clear() from sync_document in `crat
Part 1: I removed `self.nav_query.clear()` from `sync_document` in `crates/ui-egui/src/documents.rs`. `nav_query` is now never cleared on a document switch. It stays in step with the search box's text, which lives in egui memory under the window's id. After A → B → A, `nav_query` still holds A's query. That matches the box and A's restored `find.query`, so A's highlights paint again. On B, `nav_query` equals `find.query` only if B's own query is the same text, so A's matches don't paint there. I added no test for the A → B → A case. `cargo fmt --check` and `cargo clippy -p wordcraft-ui-egui --all-targets -- -D warnings` pass. The `nav` and `find` lib tests pass, including `find_next_from_dialog_does_not_paint_nav_pane_highlights_when_pane_query_differs`.
2026-12-06 04:21:39 +00:00
autocraft-bot[bot] dd426962ef Merge pull request #9630 2026-12-06 04:20:44 +00:00
batistalucasv 39828216a0 test(ui-egui): drop redundant pre-edit Space/Enter leg in #1169 IME test 2026-12-06 01:20:44 -03:00
batistalucasv 52b9178d20 fix(engine): verify canonical entry identity in resolve_entry (#9396) 2026-12-06 01:10:55 -03:00
autocraft-bot[bot] 00fa95054f Merge pull request #9625 2026-12-06 04:10:51 +00:00
batistalucasv 7043ab347b test(ui-egui): clarify plain-V no-paste assertion in Mod+V release test 2026-12-06 01:10:51 -03:00
yoriswind aeb61c4783 fix(ui): explain why a kept draft pauses comment edits 2026-12-05 20:05:54 -08:00
yoriswind fa35464e90 Use fixed-size chunks in the Print Preview edge test 2026-12-05 20:03:01 -08:00
autocraft-bot[bot] 06eead097d Merge pull request #9623 2026-12-06 04:02:46 +00:00
batistalucasv 94b6d6301d test(ui-egui): run font-arrow toggle test through font_box with exact arrow query 2026-12-06 01:02:46 -03:00
yoriswind fc44893e2f fix(ui): keep the Print Preview outline inside the pane 2026-12-05 19:56:44 -08:00
autocraft-bot[bot] d1743bdcb3 Merge pull request #9620 2026-12-06 03:53:59 +00:00
batistalucasv 18df2f117a test(ui-egui): check rendered Picture Format button icons 2026-12-06 00:53:59 -03:00
batistalucasv ee58177dd0 Navigation pane: highlight only results matching the pane's search (#9408) 2026-12-06 00:48:39 -03:00
autocraft-bot[bot] 75578906b3 Merge pull request #9613 2026-12-06 03:46:25 +00:00
yoriswind 90e6eaecdc test(ui): handle midnight in the calendar focus test 2026-12-05 19:46:25 -08:00
autocraft-bot[bot] 454ef61513 Merge pull request #9606 2026-12-06 03:41:23 +00:00
batistalucasv 3233fe2212 docs(mcp): note text-effects fill validation and wrap paragraph 2026-12-06 00:41:23 -03:00
autocraft-bot[bot] 3ae5b604b1 Merge pull request #9600 2026-12-06 03:37:23 +00:00
autocraft-bot[bot] 598d5e919c Merge pull request #9603 2026-12-06 03:37:23 +00:00
batistalucasv 72ce08c5c7 styles.modify: include path and expected fields in nested unknown-key errors (#9411) 2026-12-06 00:37:23 -03:00
yoriswind 9a2b333788 Borrow Page Setup snapshots in the gutter regression 2026-12-05 19:36:35 -08:00
autocraft-bot[bot] 8ee204198d Merge pull request #9602 2026-12-06 03:33:08 +00:00
batistalucasv 2a8df22274 refactor(ui-egui): share RecordingCandidates font spy in test_harness (#7575) 2026-12-06 00:33:08 -03:00
yoriswind 68a700ba03 fix(ui): stage a reduced gutter for Page Setup resizing 2026-12-05 19:31:34 -08:00
autocraft-bot[bot] 796794dec9 Merge pull request #9599 2026-12-06 03:30:26 +00:00
batistalucasv 58658bdeaa Context menu: return focus to page after Wrap Text submenu action (#9421) 2026-12-06 00:30:26 -03:00
autocraft-bot[bot] 5a9f201896 Merge pull request #9562 2026-12-06 03:28:12 +00:00
autocraft-bot[bot] df9a579adf Merge pull request #9551 2026-12-06 03:28:12 +00:00
autocraft-bot[bot] 57e4ca8bd3 Merge main (59e79495) into the pull request
Resolved the conflict in crates/ui-egui/src/dialogs/font.rs (sync_notes)

Resolved the conflict in crates/ui-egui/src/dialogs/font.rs (sync_notes). I kept the PR's live-region announcement logic and switched its stored-name lookups to the box_stored(slot, shown) helper that main introduced. fmt --check and clippy -D warnings pass. The font tests (68) and announce tests (10) pass, including the PR's new test.
2026-12-06 03:28:12 +00:00
autocraft-bot[bot] bc6645f4fd Merge main (59e79495) into the pull request 2026-12-06 03:27:54 +00:00
autocraft-bot[bot] 6e1b53edff Merge pull request #9568 2026-12-06 03:21:11 +00:00
autocraft-bot[bot] 8fff81bc6b Merge pull request #9564 2026-12-06 03:21:11 +00:00
autocraft-bot[bot] e7d01cd622 Merge pull request #9581 2026-12-06 03:21:11 +00:00
batistalucasv 8d83bd1dec layout.pageSetup: keep exact (negative) vertical margins (#9413) 2026-12-06 00:21:11 -03:00
batistalucasv 54372a30bc test(ui-egui): restore page-focused content-control list close test (#7862) 2026-12-06 00:19:32 -03:00
batistalucasv 4179e22d39 test(ui-egui): use inline jobs in nav_pane_tabs_switch_on_click (#9492) 2026-12-06 00:11:23 -03:00
autocraft-bot[bot] 23845f5194 Merge pull request #9565 2026-12-06 03:01:54 +00:00
batistalucasv 084576d6c4 docs(ui-egui): clarify what #1169 IME interrupt test guards (#7564) 2026-12-06 00:01:54 -03:00
Zaxaerith e598afc3ef test(ui): use a deterministic font catalog for missing-font notes 2026-12-06 10:56:19 +08:00
batistalucasv 37d4051f5f test(app): keep stale-key test focused on token replacement (#7527) 2026-12-05 23:54:44 -03:00
autocraft-bot[bot] 51eac9c4cf Part 1: the Font dialog's live-region announcement now uses the same tra
Part 1: the Font dialog's live-region announcement now uses the same translated missing-font note the font box shows (the 'shown as' sentence filled with the typed family and the substitute face, plus the Add Font… advice), instead of the bare substitute name. sync_notes (dialogs/font.rs) gets the words from the app host's word sets, builds one note per changed box (East Asian first, then Latin), and joins them with a space. The test changing_font_to_missing_announces_note_in_live_region now expects the full note. fmt --check and clippy -D warnings pass; the new test, announce:: tests and other font tests pass.
2026-12-06 02:53:35 +00:00
autocraft-bot[bot] eefc1a8dd9 Merge pull request #9473 2026-12-06 02:52:39 +00:00
FredAppsandautocraft-bot[bot] <354215646+autocraft-bot[bot]@users.noreply.github.com> 950bb983bf Merge pull request #8622
Co-authored-by: autocraft-bot[bot] <354215646+autocraft-bot[bot]@users.noreply.github.com>
2026-12-06 02:52:39 +00:00
autocraft-bot[bot] 6cb184a390 Merge pull request #9470 2026-12-06 02:52:39 +00:00
FredAppsandautocraft-bot[bot] <354215646+autocraft-bot[bot]@users.noreply.github.com> 73c17b0cbf Merge pull request #8829
Co-authored-by: autocraft-bot[bot] <354215646+autocraft-bot[bot]@users.noreply.github.com>
2026-12-06 02:52:39 +00:00
autocraft-bot[bot] f874682046 Merge pull request #9560 2026-12-06 02:52:39 +00:00
Zaxaerith cce156e804 docs: update output font metric notices (#9547) 2026-12-06 10:52:39 +08:00
autocraft-bot[bot] eb535d12a4 Merge pull request #9553 2026-12-06 02:48:47 +00:00
batistalucasv e41c4d4604 Tables: refit stretched continuation picture to shortened clip (#9457) 2026-12-05 23:48:47 -03:00
autocraft-bot[bot] 14c6db3736 Merge pull request #9552 2026-12-06 02:41:28 +00:00
batistalucasv 9c8d8c02f0 test(ui-egui): drop duplicate fixed_catalog Inter check (#7582) 2026-12-05 23:41:28 -03:00
batistalucasv 11d671bbac Font dialog: announce missing-font note changes in live region (#9530) 2026-12-05 23:37:34 -03:00
autocraft-bot[bot] 0823da61e4 Merge pull request #9549 2026-12-06 02:34:05 +00:00
batistalucasv 237d13238b test(ui-egui): rename paste-release test after behaviour (#7605) 2026-12-05 23:34:05 -03:00
autocraft-bot[bot] a70f347266 Merge pull request #9462 2026-12-06 02:23:03 +00:00
autocraft-bot[bot] c2389c41e5 Merge pull request #9263 2026-12-06 02:23:03 +00:00
batistalucasv 2bc457a3a6 ci: retrigger flaky ui-egui gate 2026-12-05 23:23:03 -03:00
batistalucasv 5663ff5182 docs(layout): clarify lay_header_box return value and state restore 2026-12-05 23:19:55 -03:00
autocraft-bot[bot] d709bf42f8 Merge pull request #9448 2026-12-06 02:18:37 +00:00
autocraft-bot[bot] 59e7949580 Merge pull request #9525 2026-12-06 02:18:37 +00:00
autocraft-bot[bot] a6739aaebc Merge pull request #9539 2026-12-06 02:18:37 +00:00
autocraft-bot[bot] 4184c09152 Merge pull request #9463 2026-12-06 02:18:37 +00:00
autocraft-bot[bot] 7df0a8686c Merge pull request #9535 2026-12-06 02:18:37 +00:00
autocraft-bot[bot] be63e04530 Merge pull request #9436 2026-12-06 02:18:37 +00:00
autocraft-bot[bot] caa9bf9775 Merge pull request #9531 2026-12-06 02:18:37 +00:00
autocraft-bot[bot] 92b1cfbd5b Merge pull request #9427 2026-12-06 02:18:37 +00:00
autocraft-bot[bot] 5c316c555e Merge pull request #9456 2026-12-06 02:18:37 +00:00
autocraft-bot[bot] c81659936c Merge pull request #9440 2026-12-06 02:18:37 +00:00
autocraft-bot[bot] aa36f59052 Merge pull request #9450 2026-12-06 02:18:37 +00:00
autocraft-bot[bot] a18a726790 Merge pull request #9423
With AutoCraft's conflict resolution b1fd5fdc.
2026-12-06 02:18:37 +00:00
autocraft-bot[bot] c38e66b678 Merge pull request #9447 2026-12-06 02:18:37 +00:00
autocraft-bot[bot] 15e24bca8c Merge pull request #9336 2026-12-06 02:18:37 +00:00
batistalucasv b02b6763a1 Merge remote-tracking branch 'upstream/main' into fix/9232-picture-format-icons
# Conflicts:
#	crates/ui-egui/src/tests/dialogs.rs
2026-12-05 23:18:37 -03:00
batistalucasv ae62492666 ci: retrigger flaky ui-egui gate 2026-12-05 23:16:41 -03:00
batistalucasv e16ff7bba7 ci: retrigger flaky ui-egui gate 2026-12-05 23:16:38 -03:00
batistalucasv a355cc5b87 docs(ui-egui): clarify Recover font test doc comment (#7575) 2026-12-05 23:13:28 -03:00
batistalucasv 9e7e0ce21f Font dialog: resolve missing-font notes with box_stored (#9529) 2026-12-05 23:09:06 -03:00
batistalucasv 37462d31a4 docs(typing-parity): document Backspace restoring lowercase i (#7662) 2026-12-05 23:00:03 -03:00
batistalucasv a1aac642aa test(ui-egui): verify Customize Keyboard linked command follows registry location 2026-12-05 22:54:24 -03:00
autocraft-bot[bot] 2006a07704 The failing test `tests::dialogs_tests::nav_pane_switching_tabs_keeps_se
The failing test `tests::dialogs_tests::nav_pane_switching_tabs_keeps_search_highlights` has nothing to do with the PR's Page Setup change. It fails the same way in the pod, so it is deterministic. The log shows `Harness::run exceeded max_steps (4). It would have settled after 7 steps.` at `tests/dialogs.rs:515`. The test's harness used the default 4-step budget. The sibling test `nav_pane_tabs_switch_on_click` already uses `with_max_steps(8)`, because a page view that comes to rest draws once more at its exact size. I gave this test the same budget (`with_max_steps(8)`) and the same explanatory comment. The test is wrong, not the app. All its assertions are unchanged, so nothing is weakened. After the change both nav_pane tests pass, `cargo fmt --check` is clean, and `cargo clippy --tests` on `wordcraft-ui-egui` is clean. I did not run the full ui-egui suite.
2026-12-06 01:53:15 +00:00
batistalucasv 74f7badb5e fix(ui-egui): keep Auto row height on no-op Enter commit 2026-12-05 22:43:29 -03:00
batistalucasv 6e5566d4b7 docs(mcp): document nested unknown-key checks in styles.modify 2026-12-05 22:40:47 -03:00
autocraft-bot[bot] 47ad5dd540 Merge pull request #9419 2026-12-06 01:40:24 +00:00
Lucas Batista Vargas f1d3b6dccd ci(sonarcloud): pass only SonarCloud secrets explicitly (#3772) (#9114) 2026-12-06 01:40:24 +00:00
autocraft-bot[bot] 6f3b1b7d17 Merge pull request #9415 2026-12-06 01:40:24 +00:00
autocraft-bot[bot] f98a4d004c Merge pull request #9354
With AutoCraft's conflict resolution 297e0f5a.
2026-12-06 01:40:24 +00:00
Lucas Batista Vargas 6b0f28c744 Focus mode: add Exit Focus button to the screen bar (#8985) (#8989) 2026-12-06 01:39:03 +00:00
Lucas Batista Vargasandbatistalucasv fd179f880e Fix: edit Start at and resolve active section in Page Number Format (#5855) (#5869)
* Fix: edit Start at and resolve active section in Page Number Format (#5855)

* Review fixes for #5855: the edited page's section, and the body return caret

Edit Header from the body passes the caret's page again, so a header made on
a later section's page goes in the first section and shows on every page that
links to it, as on main.

A new Session::hf_section records the section of the page whose header or
footer is open, and section commands read it first. That keeps the section
right when a taller footer repaginates the pages, and leaves hf_return as the
body position Close Header and Footer puts back (#3331), so the caret is no
longer moved to the section boundary by a click into another page's header or
footer.

The duplicated return-caret block in edit_hf, create_hf and the canvas is
gone. docs/ui-parity.md, docs/gaps.md and ROADMAP.md record the page-numbering
changes, and the typed-zero dialog test types after choosing Start at, the
flow the dialog advertises.

* Docs: remove literal branch/main labels from ROADMAP.md (#5855)

* Import NumFormat at module scope in engine page tests (#5855)

* Place body caret in section 0 before testing stale hf_section clear (#5855)

* Ignore stale cached layouts in Session::cached_layout (#5855)

* Adapt Page Number Format Escape test to single-Escape modal dismissal (#5855)

* docs(gaps): update live Last updated header for #5855

* insert(pageNumber): target displayed or inherited header/footer part after #3639 (#5855)

---------

Co-authored-by: batistalucasv <[email protected]>
2026-12-06 01:38:56 +00:00
Lucas Batista Vargas a822ef33ea PDF: Thai/Lao text layer keeps original vowels and cluster mappings (#5883) (#5888)
* PDF: Thai text layer ToUnicode CMap marks and cluster mappings (#5883)

* PDF: split only Thai/Lao and RTL clusters in text extraction (#5883)

A run that contains Thai or Lao text no longer splits shared character ranges of other scripts in the same run. Devanagari pre-base vowels and other clusters keep one logical range, so /ActualText extraction stays in reading order. Add a unit test with Devanagari and Thai text sharing a run.

* PDF: keep Thai tone marks in raw ToUnicode extraction (#5883)

HarfBuzz draws SARA AM as NIKHAHIT and SARA AA with the cluster's marks between them, and reuses those glyphs across clusters. Give the two vowel glyphs the vowel's range and each mark its own, then write Thai cluster glyphs in text order, so a glyph reused by นำ and น้ำ keeps one mapping and extractors that ignore /ActualText read the tone mark. Add an exact raw-extraction regression for นำ น้ำ.

* PDF: cover precomposed and fallback Thai cluster paths (#5883)

Test the two-glyph SARA AM path and the fallback used when the shaped glyphs do not match the NIKHAHIT/SARA AA structure.

* PDF: decompose Thai/Lao composite vowels in ToUnicode CMap (#5883)

Decompose composite vowels (SARA AM U+0E33 / U+0EB3) into NIKHAHIT and SARA AA
with distinct ranges in the decomposed text so each glyph receives a unique
ToUnicode CMap mapping. This prevents SARA AA from colliding with standalone
SARA AA and duplicating in raw extractors. Add raw-mode regressions for Thai and Lao.

* PDF: use per-mark ranges for Lao NIKHAHIT clusters and clean parity table (#5883)

* PDF: preserve original Thai/Lao SARA AM in ActualText while keeping decomposed ToUnicode (#5883)

* test(pdf): use distinct Thai SARA AM phrases for body and footer paths (#5883)

* PDF: skip SARA AM decomposition on untagged paths (#5883)
2026-12-06 01:38:48 +00:00
Lucas Batista Vargasandautocraft-bot[bot] <354215646+autocraft-bot[bot]@users.noreply.github.com> 9348c590c0 Font dialog: update missing-font notes when the font changes (#7943) (#7945)
* Font dialog: update missing-font notes when the font changes (#7943)

* fix(dialogs): preserve initial font name mappings across FontDb refreshes

* font dialog: drop stale localized-name mappings when identity family is installed

* I made both changes benandez asked for, in `crates/ui-egui/src/dialogs/f

I made both changes benandez asked for, in `crates/ui-egui/src/dialogs/font.rs` and `crates/ui-egui/src/dialogs/tests.rs`. The new test passes and the other 50 font tests in ui-egui still pass. clippy (`-D warnings`) and `cargo fmt --check` are clean. With the fix switched off, the new test fails.

1. Unedited box keeps its font (font.rs). The author's later commit already merges new name pairs into `names` instead of replacing them. But that merge still deletes or overwrites a pair when a font is added whose own name is the one the box shows, and then OK would send that name. So I used the reviewer's other option as well. When the dialog opens, `FontForm::opened` (used both for a normal open and from Define New Bullet) now saves what each box shows and the font name behind it, and records the starting values. `props` goes through the new `box_stored`: while a box still shows what it opened with, it gives the saved font name. So OK with no edits sends no font, whatever fonts are added or removed meanwhile. The author's merge logic is unchanged.

2. Test (tests.rs): `font_dialog_ok_keeps_the_font_when_fonts_change_while_it_is_open` sets the text in SimSun. It then opens the Font dialog with the box showing another name for it, the way 宋体 stands for SimSun. That needs a small test-only helper, `FontForm::open_on_localized`, because the test setup cannot install a font with a real Chinese name. With the dialog open, the test runs a real `font.add` of a font named exactly as the box shows, presses OK, and checks that `font` and `fontCs` did not change. It then opens the dialog again and does the same with `font.remove`.

---------

Co-authored-by: autocraft-bot[bot] <354215646+autocraft-bot[bot]@users.noreply.github.com>
2026-12-06 01:38:34 +00:00
Lucas Batista Vargas c8186db02c Copy: move the copied fragment into the clipboard instead of cloning it (#8661) 2026-12-06 01:38:26 +00:00
Lucas Batista Vargas c59b417f94 Layout: build unscaled glyph metrics once per kerned shaping segment (#8619) (#8640) 2026-12-06 01:38:18 +00:00
Lucas Batista Vargas 29460b5583 Layout: lay out only the needed prefix rows in table_start_need (#8684) 2026-12-06 01:38:10 +00:00
Lucas Batista Vargasandautocraft-bot[bot] <354215646+autocraft-bot[bot]@users.noreply.github.com> 311fad12b8 Control server: restore tests for stale tokens and spawn aborts (#7317) (#7527)
* Control server: restore tests for stale tokens, spawn aborts, EOF requests, and connection limits (#7317)

* Address review feedback: drop craft-libs-covered tests and guard temp dirs (#7317)

---------

Co-authored-by: autocraft-bot[bot] <354215646+autocraft-bot[bot]@users.noreply.github.com>
2026-12-06 01:33:08 +00:00
Lucas Batista Vargas cb0647a685 test(ui-egui): restore space_and_enter_on_the_canvas_do_not_interrupt_ime (#1169) (#7564)
* test(ui-egui): restore space_and_enter_on_the_canvas_do_not_interrupt_ime (#1169)

Restores the regression test from #7101 for canvas keystroke IME composition preservation:
- space_and_enter_on_the_canvas_do_not_interrupt_ime (#1169, keyboard): Verifies that typing Space and Enter on the focused canvas inserts text into the document model and retains input focus without setting platform_output.ime.should_interrupt_composition (which would trigger XIM context recreation in fcitx/ibus on X11 and drop subsequent keystrokes). Also verifies that clicking on the already-focused canvas preserves the composition context.

* canvas: test Space/Enter with active IME pre-edit and interrupt on primary click (#1169)

* Address review feedback: revert caret.rs change and test both no-pre-edit and pre-edit Space/Enter (#1169)
2026-12-06 01:33:00 +00:00
Lucas Batista Vargas 044bbce813 test(ui-egui): restore non_latin_names_in_the_recover_list_get_a_face test (#7317, #3545) (#7575)
* test(ui-egui): restore non_latin_names_in_the_recover_list_get_a_face test (#7317, #3545)

* Address review feedback: verify Hani FontCandidates request via spy in Recover list test (#7317, #3545)
2026-12-06 01:32:52 +00:00
Lucas Batista Vargasandautocraft-bot[bot] <354215646+autocraft-bot[bot]@users.noreply.github.com> dfa1223a01 test(ui-egui): restore clicking_the_font_arrow_toggles_dropdown_and_preserves_caret_on_field_click test (#7317, #6722) (#7582)
* test(ui-egui): use WordCraft font_picker with fixed assets/fonts catalog (#7317, #6722)

* test(font_picker): isolate fixed_font_catalog with Os::None

* test(ui-egui): restore missing imports and reuse fixed_catalog in widgets::tests

---------

Co-authored-by: autocraft-bot[bot] <354215646+autocraft-bot[bot]@users.noreply.github.com>
2026-12-06 01:32:43 +00:00
Lucas Batista Vargasandautocraft-bot[bot] <354215646+autocraft-bot[bot]@users.noreply.github.com> 28f0c40503 test(keys): restore paste_release_modifiers_fall_back_to_those_held_with_mod test (#7317) (#7605)
Co-authored-by: autocraft-bot[bot] <354215646+autocraft-bot[bot]@users.noreply.github.com>
2026-12-06 01:32:34 +00:00
Lucas Batista Vargas 63cc890f30 fix(keytips): suppress legacy hint on JT/JL prefix and adapt table-tab test (#7317) (#7615)
* fix(keytips): suppress legacy hint on JT/JL prefix and adapt table-tab test (#7317)

* test(keytips): speed up table-tab test and unit-test legacy hint gate

* test(keytips): split table-tab keytips test and trim extra frames
2026-12-06 01:32:25 +00:00
autocraft-bot[bot] 5e9afcc8dc Merge main (e194d86d) into the pull request 2026-12-06 01:31:35 +00:00
autocraft-bot[bot] faeffc42da Merge main (e194d86d) into the pull request 2026-12-06 01:31:35 +00:00
autocraft-bot[bot] c516e5ffe1 Merge main (e194d86d) into the pull request 2026-12-06 01:31:32 +00:00
Lucas Batista Vargas e194d86db6 test(ui-egui): stabilize main CI tests after #8720 page settle renders (#9492)
Both tests failing on main CI since #8720 (f333552fe5) hit the same
asynchronous TextureLoader wake race (loader.rs:208) introduced when the
canvas settles page rects and requests a 1:1 device-pixel re-render:

- chrome::tests::status_bar_controls_width_cache_is_per_window_and_avoids_discard_loops:
  WordApp::new and Kit::new used ThreadJobs, so the background page
  rasterization triggered after the 400 -> 1200 resize could finish during
  the verification pass and wake the context (delay 0ns). Run jobs inline
  via InlineJobs on both Kit and Host, wait for two consecutive calm
  passes (up to 8), and assert that steady state was reached.
- tests::dialogs_tests::nav_pane_switching_tabs_keeps_search_highlights:
  #8720 raised max_steps to 8 in the sibling nav_pane_tabs_switch_on_click
  test but missed this test (#9229), causing Harness::run to exceed its
  default 4-step limit when TextureLoader wakes the harness. Use InlineJobs
  and with_max_steps(8) so tab switching settles deterministically.

Test-only change; production behaviour unchanged. Refs #8720.
2026-12-06 01:30:16 +00:00
autocraft-bot[bot] 1494736a84 The failing test was `tests::dialogs_tests::nav_pane_switching_tabs_keep
The failing test was `tests::dialogs_tests::nav_pane_switching_tabs_keeps_search_highlights`, from #9229. It panicked at dialogs.rs:515 with `Harness::run exceeded max_steps (4). It would have settled after 7 steps` on both Windows and macOS. The PR only touches `ribbon/picture.rs`, so the failure comes from this test combined with main's current code. The harness default allows 4 steps, but a Navigation pane tab switch needs about 7 because a page view that comes to rest draws once more at its exact size. The sibling test `nav_pane_tabs_switch_on_click` already uses `with_max_steps(8)` for the same reason. I gave the failing test the same budget, with a short comment, in `crates/ui-egui/src/tests/dialogs.rs`. This changes only the harness setting. Every assertion is unchanged, including both search-highlight counts after each tab click. In the pod, both `nav_pane` tests and the three `picture_format` tests pass. `cargo fmt --check` and `cargo clippy -p wordcraft-ui-egui --features craft/ui-testing --lib --tests -D warnings` are clean. I did not run the full suite, so I haven't confirmed the other 1,200 tests still pass.
2026-12-06 00:38:41 +00:00
autocraft-bot[bot] 8b8bf12dcf Fixed the clippy lint (cognitive complexity 32/30 on Windows and macOS)
Fixed the clippy lint (cognitive complexity 32/30 on Windows and macOS) in `execute_command` in crates/ui-egui/src/app/commands.rs by moving the pre-Resolve reply-draft flush into `flush_reply_before` and the post-command IME interruption blocks into `interrupt_ime_after_replacement`. Behaviour is unchanged. On Linux the function went from 30 to 27, so Windows and macOS should land around 29/30, a margin of one that I could not run on those platforms. fmt --check and clippy pass, and 87 `ime`/`comment` lib tests pass. The remaining gate failure, `nav_pane_switching_tabs_keeps_search_highlights`, fails deterministically here but comes from main (#9229 / #9280), not this PR. Open PR #9473 already fixes it, so I left it alone. The Windows-only `status_bar_controls_width_cache_is_per_window_and_avoids_discard_loops` failure looks flaky: it passes locally and the PR doesn't touch chrome code.
2026-12-05 23:27:59 +00:00
autocraft-bot[bot] 5c60f87492 Merge main (c658b7a3) into the pull request 2026-12-05 22:58:09 +00:00
autocraft-bot[bot] 8ddb4a414a Merge main (c658b7a3) into the pull request 2026-12-05 22:55:17 +00:00
autocraft-bot[bot] f34cb0492f Merge main (c658b7a3) into the pull request 2026-12-05 22:55:09 +00:00
yoriswind ab27abf81a Wait for Navigation Pane highlights in the tab-switch test 2026-12-05 14:51:33 -08:00
autocraft-bot[bot] 5fcbcaffed Merge main (c658b7a3) into the pull request 2026-12-05 22:02:41 +00:00
yoriswind c36b405ab2 Keep comment draft IDs with their document across windows 2026-12-05 14:02:41 -08:00
autocraft-bot[bot] 37d10db9b4 Merge main (d89f0352) into the pull request 2026-12-05 21:58:03 +00:00
autocraft-bot[bot] 7aa3f4e226 Merge main (d89f0352) into the pull request 2026-12-05 21:58:03 +00:00
yoriswind 1b76cf78e2 Test keyboard focus after using content controls 2026-12-05 13:39:02 -08:00
yoriswind cc67903c6c Keep comment edit drafts bound to the original reply 2026-12-05 13:27:58 -08:00
batistalucasv 54dd6e77d2 fix(xtask): cover craft facade aliases that enable UI features (#9187) 2026-12-05 18:14:55 -03:00
yoriswind 386099fdec Apply pending Markdown before reading the Font dialog 2026-12-05 13:13:24 -08:00
yoriswind a85633c709 fix(ui-egui): keep comment drafts when Undo restores resolution 2026-12-05 13:08:41 -08:00
yoriswind e97cf13087 Use the stable UI scope for the print preview well 2026-12-05 13:08:03 -08:00
yoriswind 77bb865114 fix(ui-egui): paint the print-preview outline outside the paper texture 2026-12-05 12:52:16 -08:00
autocraft-bot[bot] b965f4207e Merge main (c658b7a3) into the pull request 2026-12-05 20:45:52 +00:00
f333552fe5 Page text on screen: sharp baselines, system text settings, subpixel (LCD) edges (#8720)
Lands #7089 by @nikolazius on current main. Refs #7089, #2408.

Co-Authored-By: Nick <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-05 20:45:52 +00:00
autocraft-bot[bot] c658b7a3ba Merge pull request #9307 2026-12-05 20:45:52 +00:00
autocraft-bot[bot] 6ee905628e Merge main (c658b7a3) into the pull request 2026-12-05 20:45:52 +00:00
autocraft-bot[bot] d89f035219 Merge pull request #9406 2026-12-05 20:45:52 +00:00
autocraft-bot[bot] 860d728dfd Merge pull request #9369 2026-12-05 20:45:52 +00:00
autocraft-bot[bot] 0282a6124f Merge pull request #9364 2026-12-05 20:45:52 +00:00
autocraft-bot[bot] 3bb8a438b0 Merge pull request #9344 2026-12-05 20:45:52 +00:00
yoriswind 396507fc2f fix(ui): keep Latin fallback from showing the Asian font picker 2026-12-05 12:45:02 -08:00
yoriswind 9a36468569 Scope core font notices to the glyphs on rendered pages 2026-12-05 12:39:57 -08:00
yoriswind 3748663e77 fix(layout): skip repeated turned lines across pages 2026-12-05 12:39:31 -08:00
autocraft-bot[bot] 77a3c3556a Merge main (55ee6bfc) into the pull request
Resolved the conflict in crates/ui-egui/src/ribbon/picture.rs by keeping

Resolved the conflict in crates/ui-egui/src/ribbon/picture.rs by keeping main's `primary_picture` guard on the Change button and the PR's `resetGraphic` icon on Reset. No conflict markers remain; fmt is clean and the three picture_format tests pass.
2026-12-05 20:35:53 +00:00
yoriswind e9d2d57c3d fix(engine): enable Picture Format for shape-first text ranges 2026-12-05 12:27:05 -08:00
yoriswind 1d0e468a0d fix(ui-egui): validate page setup with the submitted gutter 2026-12-05 12:18:35 -08:00
yoriswind ba1b2d5951 fix(layout): retry only the header measured for the body 2026-12-05 12:12:41 -08:00
aiongg d10bb1dab2 Render the caret's page in the pass that asks for it
The page view's source renders the page holding the caret synchronously and
returns it as a finished picture, for its whole-page request and for the part
in view when zoomed in, so a typed letter shows in the frame of its key. Every
other page still renders on a worker. Both paths share one page-picture render.
2026-12-05 20:10:22 +00:00
yoriswind 38f277cb10 fix(cli): scope metric font notes to rendered output 2026-12-05 12:06:36 -08:00
yoriswind 63dbe61cda fix(layout): clip a split continuation background to its row 2026-12-05 11:55:39 -08:00
Zinadin Zidan 722ee1b60d test(ui-egui): read the balloon's painted text, not its name (#9218)
The check that the reverted comment text is back searched the window's accessible names, which the picture Size dialog's "Original size", Compare's "Original document" and the balloon card's own name (built from the stored comment, so it reads "Original" even while a draft shows) all satisfy while the card paints nothing.

`paints_inside` now walks the frame's text shapes, cutting each one by its own clip rect so a card scrolled out of the balloon column does not count, and `escape_reverts_a_comment_draft` reads paint for both sides: the restored text and the absence of the discarded draft, with the draft asserted painted before Escape so that absence is not vacuous. A new test, `the_balloon_check_reads_painted_text_not_its_name`, covers the case the change moves: a card in view paints the comment's text, and the same card scrolled out of view keeps its name while painting none of it.

Only the test file changes; no product code is touched.

Fixes #9218
2026-12-06 01:44:18 +06:00
autocraft-bot[bot] 53e426820a Merge pull request #9262
With AutoCraft's conflict resolution bd18087b.
2026-12-05 19:30:09 +00:00
autocraft-bot[bot] 55ee6bfcb8 Merge pull request #9379 2026-12-05 19:30:09 +00:00
autocraft-bot[bot] e77669a552 Merge pull request #9349 2026-12-05 19:30:09 +00:00
yoriswind b6adce3262 fix(ui-egui): apply typed table row heights on commit 2026-12-05 11:30:09 -08:00
autocraft-bot[bot] 68c94e9a2b Part 1: entry in crates/pdf/src/exporter.rs no longer returns early
Part 1: `entry` in `crates/pdf/src/exporter.rs` no longer returns early when the existing entry has children. Now, when a piece contains the heading's first line and the existing entry is not already a heading, that entry becomes the heading tag, even if an earlier piece gave it children (the list number drawn before a column break). An entry that already has children keeps its reading-order position; an empty one still moves to the heading's position. I added the test `numbered_heading_after_column_break_keeps_heading_tag` in `crates/pdf/src/tests.rs`. It exports a 2-column section with a numbered Heading1 that opens with a column break, and checks that exactly one H1 tag is produced. The test passes with the fix. I did not confirm that it fails without the fix: that check was interrupted. `cargo fmt --check` and `cargo clippy` (all targets, `-D warnings`) are clean, and all 108 tests in the `wordcraft-pdf` crate pass.
2026-12-05 19:23:17 +00:00
autocraft-bot[bot] ae713e05a8 Merge pull request #9353 2026-12-05 19:22:59 +00:00
autocraft-bot[bot] b8ba467e54 Merge pull request #9325 2026-12-05 19:22:59 +00:00
autocraft-bot[bot] 71a3072fec Merge main (58a3e6cf) into the pull request
Resolved conflicts in picture.rs and specs.rs. Main already fixed the bu

Resolved conflicts in picture.rs and specs.rs. Main already fixed the bug with has_any_picture, which relies on a primary-only has_picture. I took main's each_picture fast path, reverted the PR's widening of has_picture, removed the now-redundant has_primary_picture (crop/altText/change use has_picture again) and kept main's has_any_picture import. The PR's two tests remain and pass. fmt and clippy are clean, and the 60 engine lib tests with 'picture' in their names pass.
2026-12-05 19:22:59 +00:00
yoriswind 25af5ed462 Validate numeric variant tags in style text fills 2026-12-05 11:11:12 -08:00
autocraft-bot[bot] 8a24807722 Added a narrower guard has_primary_picture in select.rs (requires the
Added a narrower guard `has_primary_picture` in select.rs (requires the primary selected object to be a picture) and switched picture.crop, picture.altText and picture.change in specs.rs to it, so they are disabled when a shape is the primary object instead of silently acting on the shape. The other Picture Format commands keep the widened has_picture plus each_picture. Added a regression test, single_object_picture_commands_need_the_picture_selected_first. The 67 cmd::objects tests pass, fmt is clean and clippy reports no errors.
2026-12-05 19:02:30 +00:00
yoriswind a269d3e13d Import JSON Value in the positional style-fill regression 2026-12-05 11:01:42 -08:00
autocraft-bot[bot] b5d21f1ba9 The merged batch failed clippy with clippy::cognitive_complexity (31/3
The merged batch failed clippy with `clippy::cognitive_complexity` (31/30) on `execute_command` in crates/ui-egui/src/app/commands.rs:160. The pull request's resolve-comment save added one `if` to that function. I moved the `review.resolveComment` commit of the open comment edit into a small helper, `save_comment_edit_before`, which `execute_command` calls first. Behaviour is the same. The `egui_extras` message at crates/ui-egui/Cargo.toml:29 is only a warning. fmt --check passes, clippy with `--all-targets --locked -D warnings` on wordcraft-ui-egui finishes with no errors, and the 23 comment-related library tests pass. I did not run the full suite or build the `wordcraft` crate.
2026-12-05 19:01:40 +00:00
autocraft-bot[bot] 8bda45fefa Part 1: DocLayout::turned_line in crates/layout/src/hit.rs now looks a
Part 1: `DocLayout::turned_line` in crates/layout/src/hit.rs now looks at the adjacent page only when the caret is in `StoryRef::Body`. In a header, a footer or a text box in one, it stops at the first or last turned line on the page, as it did before the PR. That fixes the wrap-around. I updated the doc comment to match. I added the test `tests::vertical::turned_line_does_not_cross_pages_in_a_header_text_box`. It puts a vertical text box with paragraphs "ab" and "cd" in the header of a multi-page document. Stepping from the first column to the second still works. Stepping past either edge returns `None` on pages 1 and 2. The test fails when the body-only guard is removed. All 9 `tests::vertical` tests pass, including the PR's `turned_line_crosses_page_boundary`, and fmt --check and clippy with -D warnings are clean on wordcraft-layout. I did not run the crate's other tests.
2026-12-05 18:59:47 +00:00
yoriswind ba31d08b3f Validate text fills in positional style arguments 2026-12-05 10:43:40 -08:00
yoriswind b6ced6363b fix(engine): reject unknown keys in style text fills 2026-12-05 10:31:58 -08:00
autocraft-bot[bot] 3c22bd688c Merge pull request #9342 2026-12-05 18:14:11 +00:00
autocraft-bot[bot] 7460b7f916 Merge pull request #9332
With AutoCraft's conflict resolution e79e763d.
2026-12-05 18:14:11 +00:00
autocraft-bot[bot] bcaba5a37c Merge pull request #9337 2026-12-05 18:14:11 +00:00
autocraft-bot[bot] e927cd7e8e Merge pull request #9278
With AutoCraft's conflict resolution 4454ac74.
2026-12-05 18:14:11 +00:00
autocraft-bot[bot] cc1f3231a7 Merge pull request #9339 2026-12-05 18:14:11 +00:00
autocraft-bot[bot] f5930f52ca Merge pull request #9288
With AutoCraft's conflict resolution 8cb3f502.
2026-12-05 18:14:11 +00:00
autocraft-bot[bot] 777aae19e5 Merge pull request #9366 2026-12-05 18:14:11 +00:00
yoriswind d81b0b503e test(layout): cover merged row minimum-height guards 2026-12-05 10:14:11 -08:00
yoriswind 538597a7ea fix(layout): draw continued merged-cell pictures behind borders 2026-12-05 10:09:43 -08:00
autocraft-bot[bot] 58a3e6cf5b Merge pull request #9348 2026-12-05 17:43:34 +00:00
autocraft-bot[bot] 53c9e64e98 Merge pull request #9359 2026-12-05 17:43:34 +00:00
autocraft-bot[bot] 3ee43d57d2 Merge pull request #9327 2026-12-05 17:43:34 +00:00
autocraft-bot[bot] 6c3c3d181e Merge pull request #9356 2026-12-05 17:43:34 +00:00
autocraft-bot[bot] 5b4302828e Merge pull request #9306 2026-12-05 17:43:34 +00:00
autocraft-bot[bot] 08e21b1abc Merge pull request #9352 2026-12-05 17:43:34 +00:00
autocraft-bot[bot] a188a76506 Merge pull request #9360 2026-12-05 17:43:34 +00:00
autocraft-bot[bot] e219a5a9c3 Merge pull request #9341 2026-12-05 17:43:34 +00:00
autocraft-bot[bot] 7810b05973 Merge pull request #9358 2026-12-05 17:43:34 +00:00
autocraft-bot[bot] 89f0d39e7f Merge pull request #9340 2026-12-05 17:43:34 +00:00
vangel76 946a626f5c #9279: Read the reservation through the flow test harness 2026-12-05 18:43:34 +01:00
autocraft-bot[bot] 9769b941c4 Merge pull request #9338 2026-12-05 17:43:34 +00:00
autocraft-bot[bot] 769a799620 Merge pull request #9315 2026-12-05 17:43:34 +00:00
autocraft-bot[bot] 0de7b3a5aa Merge pull request #9314 2026-12-05 17:43:34 +00:00
autocraft-bot[bot] 9f813636cf Merge pull request #9259
With AutoCraft's conflict resolution 1e860fd9.
2026-12-05 17:43:34 +00:00
autocraft-bot[bot] 7e70097130 Merge pull request #4619
With AutoCraft's conflict resolution 32931db3.
2026-12-05 17:43:34 +00:00
vangel76 4cb1d22b0e #9279: Check the reservation directly at the pagination boundary 2026-12-05 18:41:34 +01:00
vangel76 d9b3a8eb9c Keep the caret at the end when resolving tracked paragraphs 2026-12-05 18:39:55 +01:00
vangel76 9bb2d72898 Keep serif and monospace substitutes for missing unclassified fonts 2026-12-05 18:36:41 +01:00
vangel76 3c73997925 #9335: Save parked comment drafts before resolving a thread 2026-12-05 18:36:23 +01:00
vangel76 d7748aa732 8950: Show the East Asian theme fallback used by layout 2026-12-05 18:36:09 +01:00
batistalucasv f5a9d415b8 fix(layout): step across page boundaries in turned_line (#9151) 2026-12-05 14:35:51 -03:00
vangel76 a5b4b22ebf #9279: Make the balanced columns spacing regression distinguish the fix 2026-12-05 18:35:36 +01:00
vangel76 4f7d01edac #9298: Document command results and save confirmations on stdout 2026-12-05 18:33:55 +01:00
Zinadin Zidan 5aa1a78082 test(ui-egui): find the reverted comment text inside its balloon (#9218)
`escape_reverts_a_comment_draft` checked that the comment's text came back after Escape with `h.query_by_label_contains("Original")`, which searches the whole window. Any other on-screen label containing that word — the picture Size dialog's "Original size", Compare's "Original document" — satisfied it, so the assertion could pass with the balloon showing nothing.

Look the comment's card rect up in `canvas.balloon_rects` and require a node whose label contains "Original" to lie inside it. The following window-wide "Discarded" absence check is left as it was.

Fixes #9218
2026-12-05 23:31:04 +06:00
batistalucasv 6a8650e66d fix(ui-egui): use distinct icons on Picture Format ribbon buttons (#9232) 2026-12-05 14:25:06 -03:00
autocraft-bot[bot] 9986d9b4cd Merge pull request #9333 2026-12-05 17:19:17 +00:00
batistalucasv dd017d865d fix(ui-egui): preserve exact margin sizes when turning orientation in Page Setup (#9330) 2026-12-05 14:19:17 -03:00
batistalucasv 393103ffdd fix(layout): share header margin-area fallback with header_table_areas (#9225) 2026-12-05 14:15:55 -03:00
vangel76 c7661b2b0e #8902: Keep PDF heading tags after leading breaks 2026-12-05 18:15:31 +01:00
vangel76 20dd292da4 #8902: Tag a heading only where it starts in a PDF 2026-12-05 18:13:51 +01:00
vangel76 988cfaa5f1 #8433: Repair note separators and Quick Parts on JSON open 2026-12-05 18:13:08 +01:00
vangel76 0bd4878a34 #8508: Resolve the style change selected by Next Change 2026-12-05 18:11:28 +01:00
batistalucasv 737a19bbb0 test(validate): pin rejection diagnostics in observations/generate.py 2026-12-05 14:11:27 -03:00
vangel76 c5f0865fa7 #9321: Show and commit the edited table column width 2026-12-05 18:10:48 +01:00
vangel76 319838ab02 #9155: Use the theme selection tint for equation arguments 2026-12-05 18:10:45 +01:00
vangel76 21b1ceb1c1 #8557: Keep mixed-font leading beside tall inline pictures 2026-12-05 18:09:37 +01:00
vangel76 845df1cd48 Return keyboard focus to the page from content controls 2026-12-05 18:08:20 +01:00
vangel76 0c9e6054d9 #8682: Clarify which tabs can extend past the right indent 2026-12-05 18:08:10 +01:00
vangel76 8f6a40d3f4 #8508: Use the remappable Review commands in the ribbon menu 2026-12-05 18:08:10 +01:00
batistalucasv 9ce63943af fix(engine): enable Picture Format commands when a shape is selected first (#9158) 2026-12-05 14:07:40 -03:00
vangel76 74ffe933cf #8899: List Read Mode layout under Contextual Tabs 2026-12-05 18:07:37 +01:00
autocraft-bot[bot] 306040b646 Merge pull request #9317 2026-12-05 17:00:57 +00:00
batistalucasv 65960089a8 fix(ui-egui): compute Caption Numbering example via NumberingForm::prepare (#9312) 2026-12-05 14:00:57 -03:00
batistalucasv ec4922027f fix(engine): keep pending sentence-capital AutoCap alongside automatic I (#9308) 2026-12-05 13:54:08 -03:00
autocraft-bot[bot] cb919da767 Merge pull request #9305 2026-12-05 16:44:02 +00:00
autocraft-bot[bot] aadcc80cab Merge pull request #9304 2026-12-05 16:44:02 +00:00
autocraft-bot[bot] 6bf2ef18bb I moved the Unix symlink check out of the #[cfg(windows)] test `window
I moved the Unix symlink check out of the `#[cfg(windows)]` test `windows_finds_the_real_case_and_refuses_devices`, where it was dead code. It is now its own `#[cfg(unix)]` test, `a_sibling_symlink_into_the_write_root_is_rejected`, in `crates/engine/src/file_access.rs`. The test uses `folders("sibling-link")` to build its own roots and links `evil` to the write root. It asserts that `Access::Write` on the link fails with "outside the write root". The Windows test is back to its original checks. `cargo fmt --check` and `cargo clippy -p wordcraft-engine --lib --tests -- -D warnings` are clean. `cargo test -p wordcraft-engine --lib file_access` passes (11 tests), including the new one. One limit on what the test proves: it covers a link that already exists before the check. The code rejected that before this PR too. It does not exercise the race the `canonicalize` fix guards against, where a link is swapped in after `symlink_metadata`, because that can't be reproduced deterministically in a unit test.
2026-12-05 16:44:02 +00:00
batistalucasv 3b929eac31 fix(layout): skip header retry when header was not measured for body top (#9226) 2026-12-05 13:36:34 -03:00
yoriswind a895098132 fix(engine): limit promote and demote to selected table cells 2026-12-05 08:35:41 -08:00
autocraft-bot[bot] 82887db8bb Part 1: when a vertical merge's last row splits across pages, the part l
Part 1: when a vertical merge's last row splits across pages, the part left on the page now treats that merge as continuing, so its shading and cell area end with that part instead of running off the page or down to the page's bottom limit. In `crates/layout/src/table.rs`, `MergeEdges` has a new `ends` list for merges that end in a row. `split_row_with` adds it to the first part's `spans` and carries it on the remainder, so later splits keep it too. `table_flow.rs` did not need to change.

I added the test `a_vertical_merge_whose_last_row_splits_ends_with_each_part` in `crates/layout/src/tests.rs`. With the old `table.rs` it fails with an 843.8 pt fill running past rows that end at 720; with the fix it passes.

Checks on `wordcraft-layout`: `cargo fmt --all --check` and clippy with `-D warnings` pass. All other tests pass (955 passed, 2 ignored), run with two timing tests skipped. Of those two:
- `a_long_unbreakable_word_lays_out_in_linear_time` failed in the full run and passed when rerun single-threaded.
- `a_megabyte_long_word_lays_out_quickly` fails on its time limit (about 24 s) both with and without my change to `table.rs`.

I did not run `cargo xtask layers` or `cargo xtask wasm`.
2026-12-05 16:34:37 +00:00
batistalucasv ac99969305 test(cli): remove dir_resets_leftover_state scaffolding test (#9300) 2026-12-05 13:33:29 -03:00
batistalucasv 76b74dec50 fix(engine): keep resolve_entry within resolved_folder on canonicalize (#9292) 2026-12-05 13:32:20 -03:00
autocraft-bot[bot] 2daca588a4 Merge pull request #9301 2026-12-05 16:29:45 +00:00
autocraft-bot[bot] ae4f2dbf48 Merge pull request #9284 2026-12-05 16:29:45 +00:00
autocraft-bot[bot] 591a5ace12 Merge pull request #9254 2026-12-05 16:29:45 +00:00
autocraft-bot[bot] f6d1207be2 Merge pull request #9269 2026-12-05 16:29:45 +00:00
autocraft-bot[bot] 77aab09d31 Merge main (4bc5b97c) into the pull request
I resolved the one conflict, in `crates/ui-egui/src/ribbon/tests.rs`. Bo

I resolved the one conflict, in `crates/ui-egui/src/ribbon/tests.rs`. Both sides had added tests at the same place, so I kept all of them: the pull request's two Font box tests (arrow keys and wheel) and main's Font Size test for a stray wheel event with Enter. `home.rs` needed no hand edits, so the pull request's Font box change is unaltered.

On the merged tree, `cargo fmt --all --check`, `cargo xtask layers` and clippy for `wordcraft-ui-egui` with `-D warnings` passed; clippy showed only a manifest warning about the unused `egui_extras` dependency. All 64 ribbon tests passed, including both Font box tests and main's new test.

I did not run the rest of the `wordcraft-ui-egui` tests on this merge. In earlier runs on this pull request, `previews::tests::symbol_thumbnails_read_in_the_strips_real_tiles` failed. It covers equation symbol previews, which this pull request does not touch, but I have not run it on main alone. `cargo xtask wasm` was not run.
2026-12-05 16:29:45 +00:00
autocraft-bot[bot] ee9a8153d3 Merge pull request #9265 2026-12-05 16:29:45 +00:00
batistalucasv 5ad1be0472 fix(engine): reject unknown keys in nested structs in styles.modify (#9291) 2026-12-05 13:29:17 -03:00
autocraft-bot[bot] ae876e0cdc Part 1: resolving a comment while its edit is open now saves the typed t
Part 1: resolving a comment while its edit is open now saves the typed text first and then resolves, which ends the edit. Both resolved-comment guards that AutoCraft's checks flagged are back exactly as they were, so a resolved comment still takes no edits.

The save happens in `execute_command` (`app/commands.rs`) just before `review.resolveComment`, using a new `commit_open_comment_edit` in `panes/comments.rs`. This covers commands run on the shown document. It writes whichever comment edit is open, even if you resolve a different comment. If that write is refused, the resolve is refused too and the draft is kept.

By reading the code, two rarer paths can still drop a draft: a control request that resolves a comment in a background document using `doc`, and an undo or redo that makes the comment resolved while its edit is open. I did not test either.

I added the test `resolving_a_comment_mid_edit_keeps_the_typed_text`. The same typing and Resolve sequence lost the text before the fix.

Checks on `wordcraft-ui-egui`: `cargo fmt --all -- --check` passed, and clippy with `--all-targets -D warnings` finished without errors (Cargo printed a manifest warning that `egui_extras` is unused).

The full test run had 1169 library passes and 2 failures, and all integration tests passed. One failure was the new test checking for the edit field one frame too early. After fixing that, I reran the 23 library tests matching "comment" and all passed; I did not rerun the full suite.

The other failure is `previews::tests::symbol_thumbnails_read_in_the_strips_real_tiles`, which covers equation symbol thumbnails that this change does not touch. I did not run it without the change. I did not run `cargo xtask layers` or `cargo xtask wasm`.
2026-12-05 16:25:25 +00:00
autocraft-bot[bot] f0b95f73fb Merge pull request #9294 2026-12-05 16:22:37 +00:00
batistalucasv 4c8296a5b1 fix(layout): keep 20pt minimum span for Joint::fit areas (#9160) 2026-12-05 13:22:37 -03:00
autocraft-bot[bot] 9b1ef01485 Merge pull request #9293 2026-12-05 16:22:11 +00:00
batistalucasv a46514f5df docs(mcp): document strict CharProps/ParaProps key checks for styles.modify (#9290) 2026-12-05 13:22:11 -03:00
autocraft-bot[bot] 6af5d8c650 Part 1: in crates/ui-egui/src/print_page/preview.rs, render now comp
Part 1: in `crates/ui-egui/src/print_page/preview.rs`, `render` now computes `side` as `(request.side as usize).saturating_sub(2).max(1)`. The scale and the clamped `w`/`h` come from that smaller value. The `[w + 2, h + 2]` image therefore never goes past the requested side, which is capped at the device texture limit. The texture store no longer shrinks it by a whole factor of 2. I added a short comment explaining the 2 px reservation. `cargo fmt --check` and `cargo clippy -p wordcraft-ui-egui --lib --tests -D warnings` are clean. The 15 `print_page` and related tests pass, including `preview_texture_follows_the_gpu_texture_limit` and `sheet_edge_sits_outside_printed_content`. I did not add a test for the new size cap.
2026-12-05 16:18:21 +00:00
autocraft-bot[bot] 1e91f5cc1e Merge pull request #9289 2026-12-05 16:16:21 +00:00
batistalucasv bd9529b083 test(engine): exercise file_setting_in for customDictionary tilde expansion (#9283) 2026-12-05 13:16:21 -03:00
batistalucasv a7396929c7 fix(layout): limit table page-end trimming to continuing merge spans (#9191) 2026-12-05 13:14:32 -03:00
autocraft-bot[bot] 42df428b01 Merge pull request #9287 2026-12-05 16:13:18 +00:00
batistalucasv fbb26d0b85 docs(engine): move #865 doc comment back to modify_style_takes_hex_colours_like_format_color (#9282) 2026-12-05 13:13:18 -03:00
batistalucasv 84a8675092 fix(layout): draw merged cell background picture on continuation pages (#9192) 2026-12-05 13:07:58 -03:00
autocraft-bot[bot] bfa3d12bfa Merge pull request #9280 2026-12-05 16:04:08 +00:00
batistalucasv e92a4d45f8 fix(ui-egui): keep Navigation pane search highlights across tabs (#9229) 2026-12-05 13:04:08 -03:00
batistalucasv f4431d6b63 fix(ui-egui): keep print preview sheet edge outside printed content (#9189) 2026-12-05 12:58:57 -03:00
autocraft-bot[bot] 5203e2e7dc Merge pull request #9272 2026-12-05 15:41:19 +00:00
autocraft-bot[bot] bdae1b73ae Merge pull request #9268 2026-12-05 15:41:19 +00:00
autocraft-bot[bot] bdb955d2c6 Merge pull request #9267 2026-12-05 15:41:19 +00:00
autocraft-bot[bot] d78467b616 Merge pull request #9260 2026-12-05 15:41:19 +00:00
autocraft-bot[bot] 069a69a5eb Part 1: every pending comment and reply draft is now written before `rev
Part 1: every pending comment and reply draft is now written before `review.resolveComment` runs, with or without an id. I did this with `flush_comment_drafts` in `execute_command` (crates/ui-egui/src/app/commands.rs), so the pane, balloons, ribbon and scripts calling `execute` all get it. It replaces the earlier flush in `run`, which only saved the comment whose id was passed.

I also removed the lines in `comment_field` (crates/ui-egui/src/panes/comments.rs) that cleared the drafts of resolved comments. A draft the document refuses to write, for example in a read-only document, is now kept instead of silently deleted. Because a pending new reply is a draft too, Resolve now posts it first.

I added the test `resolving_a_thread_without_an_id_commits_a_reply_draft`, which passes, as does the pull request's own test. I did not run the new test against the old code.

Checks: fmt, clippy on `wordcraft-ui-egui` and `cargo xtask layers` passed, and so did the three integration test binaries. The library tests had 1170 passes and 1 failure, `previews::tests::symbol_thumbnails_read_in_the_strips_real_tiles` ("= is a speck"). That test draws equation symbols, which this change does not touch; I did not run it on the base commit. I did not run `cargo xtask wasm`.

The pull request description is now out of date: it says the flush is in `WordApp::run` and that `comment_field` clears leftover drafts as a fallback.
2026-12-05 15:41:19 +00:00
yoriswind 50f4b803a6 Derive linked shortcut categories from the command registry 2026-12-05 07:33:34 -08:00
batistalucasv b81f67dfab test(cli): clean up custom dictionary temp directory with a Drop guard (#9266) 2026-12-05 12:31:30 -03:00
yoriswind ddcaffe387 Enable multi-picture formatting when a shape is selected first 2026-12-05 07:25:10 -08:00
autocraft-bot[bot] 11f830907d Part 1: a wheel step in the focused Font box now applies the next font a
Part 1: a wheel step in the focused Font box now applies the next font and leaves the keyboard in the box.

The cause differed from the finding. At this head the wheel never reached a `Commit`. `home.rs` rebuilt the box's family from the engine on every pass, so the picker cancelled the wheel run (`HostChanged`) on the next frame and the font did not change at all.

Changes in `crates/ui-egui/src/ribbon/home.rs`:
- The Font box now sits in a new `font_family_box` function, which keeps showing the proposed family while a wheel run is going on.
- The `Commit` that ends a wheel run now counts as a step, even in a frame with no wheel input, so the focus does not move to the document.
- `stepped_in_box` no longer has the wheel check that could never be true. Up and Down behave as before.

I added the test `the_wheel_in_the_font_box_steps_the_font_and_keeps_focus` in `ribbon/tests.rs`. It sends two wheel notches and failed before the fix, because the first notch did not change the font.

Checks: `cargo fmt --all --check`, clippy for `wordcraft-ui-egui` with `-D warnings` (only a manifest warning about the unused `egui_extras` dependency) and `cargo xtask layers` passed. In the full `wordcraft-ui-egui` tests, 1170 passed and 1 failed: `previews::tests::symbol_thumbnails_read_in_the_strips_real_tiles` ("= is a speck"). It also fails when run alone. It covers equation symbol previews, which this change does not touch, but I did not run it without my change. `cargo xtask wasm` was not run.

The pull request description still says `stepped_in_box` detects a `Set` from a `MouseWheel`, which is no longer true.
2026-12-05 15:22:00 +00:00
batistalucasv 3512da9553 fix(ui-egui): darken print preview sheet edge to meet 3:1 contrast (#9179) 2026-12-05 12:21:10 -03:00
batistalucasv 9a349bf372 fix(engine): keep caret in its story after Replace All under Track Changes (#9186) 2026-12-05 12:17:44 -03:00
batistalucasv 202b71cb31 fix(xtask): flag craft UI features enabled below L6 (#9187) 2026-12-05 12:15:01 -03:00
batistalucasv 16b7706a4d fix(ui-egui): keep resolved comment balloons read-only (#9190) 2026-12-05 12:12:45 -03:00
pakiatandClaude Opus 5.5 cb75865b58 Tables: a right-to-left table moves by its last cell's left border from Word 2013
From Word 2013 layout (compatibility mode 15) Word moves a right-to-left
table (w:bidiVisual) by the w:left border of its first row's last cell, as
XML names them, as measured in Word for Windows:

- inline, it moves in from the right margin by half that border as well as
  half its first cell's;
- floating, it moves left of its offset by half that border, and right by
  0.72 pt when its first cell has no w:left border.

A table w:right border, the first cell's w:right and later rows' borders
don't move it, nor do any of these before Word 2013 or in a left-to-right
table. This closes the gap #8949 recorded: the 130 floating or Word 2013
cases measured are within 0.1 pt of Word.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-05 22:09:07 +07:00
batistalucasv ffdc0c2332 fix(ui-egui): commit pending comment draft before resolving (#9196) 2026-12-05 12:09:05 -03:00
batistalucasv d813e02661 fix(layout): skip kept_tail_end when paragraph closes a balanced section (#9206) 2026-12-05 12:05:26 -03:00
autocraft-bot[bot] b2c183fc8b Merge pull request #7725 2026-12-05 15:03:18 +00:00
autocraft-bot[bot] f900ac06c2 Merge pull request #7108
With AutoCraft's conflict resolution 38b67959.
2026-12-05 15:03:18 +00:00
autocraft-bot[bot] 4bc5b97c31 Merge pull request #5749 2026-12-05 15:03:18 +00:00
autocraft-bot[bot] 3f70941206 Merge pull request #6663 2026-12-05 15:03:18 +00:00
autocraft-bot[bot] f1583c3417 Merge pull request #9258 2026-12-05 15:03:18 +00:00
autocraft-bot[bot] f4f182b900 Merge pull request #7662 2026-12-05 15:03:18 +00:00
autocraft-bot[bot] f966ceaa25 Merge pull request #6747
With AutoCraft's conflict resolution 23961b41.
2026-12-05 15:03:18 +00:00
autocraft-bot[bot] 9b9dc5b103 Merge pull request #7316 2026-12-05 15:03:18 +00:00
batistalucasv 2c70194a5b fix(engine): reject unknown para and chr fields in styles.modify (#9203) 2026-12-05 12:03:18 -03:00
autocraft-bot[bot] 57bdc13e28 Merge pull request #7660 2026-12-05 15:03:18 +00:00
autocraft-bot[bot] f302f189a6 Merge pull request #8283 2026-12-05 15:03:18 +00:00
autocraft-bot[bot] a12799387d Merge pull request #9255 2026-12-05 14:59:00 +00:00
autocraft-bot[bot] c3696df3d9 Merge pull request #9256 2026-12-05 14:59:00 +00:00
batistalucasv b6022a338c fix(layout): drop suppressed space_before in next_first_line (#9208) 2026-12-05 11:59:00 -03:00
batistalucasv 1e4c3d52de fix(engine): expand customDictionary tilde paths with expand_home (#9246) 2026-12-05 11:56:15 -03:00
batistalucasv 3c1ea66dd9 fix(ui-egui): keep focus in Font box when stepping with arrows or wheel (#9247) 2026-12-05 11:52:11 -03:00
autocraft-bot[bot] 55992a696b Merge pull request #9253 2026-12-05 14:45:29 +00:00
batistalucasv eaec70d125 fix(ui-egui): narrow Font Size step detection to combo Set events (#9248) 2026-12-05 11:45:29 -03:00
yoriswind b4db8a407c Use array chunks in the custom dictionary fixture 2026-12-05 06:38:58 -08:00
yoriswind 4094828264 Use platform home paths for custom dictionaries 2026-12-05 06:31:27 -08:00
autocraft-bot[bot] 6f7afc6a5d Merge pull request #9243 2026-12-05 12:54:17 +00:00
autocraft-bot[bot] c634f6c83e Merge pull request #9240 2026-12-05 12:54:17 +00:00
autocraft-bot[bot] 6cc86be260 Part 1: stepping in the Font Size box with Up, Down or the wheel no long
Part 1: stepping in the Font Size box with Up, Down or the wheel no longer hands focus to the document, so repeated presses keep stepping. craft-libs sends a `Set` for steps, list picks and folded Enter commits alike, so `home.rs` now skips `focus_page` when the frame carries an ArrowUp/ArrowDown key press or a mouse-wheel event. Enter and list picks still return the keyboard to the page. I added the test `down_in_the_font_size_box_steps_the_size_again_and_keeps_focus`, which presses Down twice, expects two steps and checks the page never gets focus. It fails without the guard and passes with it. fmt and clippy pass for `wordcraft-ui-egui`, and the new test and the existing Font Size box tests pass. I didn't run the rest of the crate's tests or test the wheel.
2026-12-05 12:54:17 +00:00
yoriswind f5d1d992a2 Keep selection offsets when resolving tracked text 2026-12-05 04:52:28 -08:00
autocraft-bot[bot] f550268bab Merge pull request #9241 2026-12-05 12:42:08 +00:00
yoriswind b3c7338b3c Accept Windows home-relative folder options 2026-12-05 04:42:08 -08:00
Martin BallandClaude Sonnet 5.5 a1e458a1c0 #9233: Enter in the Font Size box returns the keyboard to the document
The box kept focus after a commit, so the wheel kept stepping the size. After a commit (Enter or list pick) the page now takes focus; the Font box does the same after a pick.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-12-05 12:31:24 +00:00
yoriswind 31b7bd6a63 Keep TXT table rows intact without stray spaces 2026-12-05 04:13:59 -08:00
autocraft-bot[bot] 63e43ae563 Merge pull request #9220 2026-12-05 11:21:07 +00:00
batistalucasv c479c88bbc refactor(ui-egui): drop duplicate Queryable import in escape_reverts_a_comment_draft (#9216) 2026-12-05 08:21:07 -03:00
autocraft-bot[bot] af3179b7e8 Merge pull request #9221 2026-12-05 10:45:26 +00:00
batistalucasv 31001fc6df refactor(ui-egui): share edit_field helper across open_edit and escape_reverts_a_comment_draft (#9217) 2026-12-05 07:45:26 -03:00
autocraft-bot[bot] 259c86f8f8 Merge pull request #9205 2026-12-05 10:20:57 +00:00
autocraft-bot[bot] 0d5052d76d Merge pull request #9200 2026-12-05 10:20:57 +00:00
batistalucasv c2d4f64766 docs(ui-egui): clarify zero-settle comment in escape_reverts_a_comment_draft (#9198) 2026-12-05 07:20:57 -03:00
pakiatandClaude Opus 5.5 2804833dae Docs: say it is WordCraft that puts a floating right-to-left table at its offset
The rows said the table's edge is at the offset in every mode "as measured
in Word", then listed where Word differs from Word 2013 layout on. Say that
WordCraft puts it there and keep Word's measured behaviour, gap included,
apart from that.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-05 17:06:19 +07:00
pakiatandClaude Opus 5.5 00eaa42e0d Docs: record the remaining mode-15 offset of a floating right-to-left table
The rows for #8517 and the comment on float_offset_shift said a floating
right-to-left table has its left edge at the offset in every mode. That is
what the layout does, and it matches Word before Word 2013 layout. From it
Word still puts the table 0.72 pt right of the offset with no w:left border
at its start, and 0.36 pt left of it with a 2 pt w:left border on its second
cell, as the pull request said. Record that gap instead of claiming a full
match.

Fixes #8949.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-05 16:54:44 +07:00
autocraft-bot[bot] 308d4b6b05 Merge pull request #9193 2026-12-05 09:42:44 +00:00
Mat Strangeandopencode b6eafa3d09 Compare a srcset candidate the way the other attributes are compared
A candidate URL now ends at ASCII whitespace, so it can end with a space of
another kind, while the clipboard text beside it is trimmed of any whitespace.
The two stopped matching when the URL ended with one, so the candidate is
trimmed at the comparison, as the src, alt and title already are.

Co-Authored-By: opencode <[email protected]>
2026-12-05 09:42:44 +00:00
autocraft-bot[bot] 6f4652f976 Merge pull request #9143 2026-12-05 09:39:18 +00:00
autocraft-bot[bot] f70664a13c Merge pull request #5545
With AutoCraft's conflict resolution 07d9f6f4.
2026-12-05 09:39:18 +00:00
autocraft-bot[bot] ba4d06c12d Merge main (610ec993) into the pull request 2026-12-05 09:39:18 +00:00
Mat Strangeandopencode e319029fdf End a srcset candidate URL at ASCII whitespace
The srcset parser ended a candidate URL at any Unicode whitespace while it
trimmed candidates of ASCII whitespace only, so a URL with a space of another
kind was cut short and a candidate that started with one made the parser spin
forever, freezing the paste path. The srcset syntax ends a candidate URL at
ASCII whitespace, so the URL now ends where the trimming does.

Fixes #8940

Co-Authored-By: opencode <[email protected]>
2026-12-05 09:24:13 +00:00
autocraft-bot[bot] 4431cc1fea Merge pull request #7068
With AutoCraft's conflict resolution df35a25d.
2026-12-05 09:22:08 +00:00
autocraft-bot[bot] 010b065dad Merge pull request #9182 2026-12-05 09:22:08 +00:00
autocraft-bot[bot] c8629cfe9c Merge pull request #9161 2026-12-05 09:22:08 +00:00
batistalucasv 0dcf26fcd1 test(ui-egui): assert reverted comment text in accessibility tree after Escape (#9148) 2026-12-05 06:22:08 -03:00
batistalucasv 2b6160b528 docs(localization-parity): clarify carry-over .wasm figure is not shipped in English-only web build (#9178) 2026-12-05 06:21:59 -03:00
autocraft-bot[bot] 167bde7ed4 Merge pull request #9139
With AutoCraft's conflict resolution bdff97c8.
2026-12-05 09:09:38 +00:00
autocraft-bot[bot] 1a79ad29d8 Merge pull request #9137 2026-12-05 09:09:38 +00:00
autocraft-bot[bot] 45a00707c7 Merge main (d417b835) into the pull request 2026-12-05 09:09:38 +00:00
autocraft-bot[bot] f81608db32 Merge pull request #9176 2026-12-05 09:01:19 +00:00
batistalucasv add2a11697 test(engine): cover arrow-key navigation in vertical text (#9152) 2026-12-05 06:01:19 -03:00
autocraft-bot[bot] a917d2a4de Merge pull request #9173 2026-12-05 09:01:17 +00:00
batistalucasv 739454c0f3 test(ui-egui): skip only Arabic in ribbon_groups_fit_above_their_labels when Arab font is absent (#9165) 2026-12-05 06:01:17 -03:00
autocraft-bot[bot] 887e2c7af0 Merge pull request #9169 2026-12-05 09:01:15 +00:00
batistalucasv a82e4003c9 test(ui-egui): rename narrow mini toolbar test to the_bar_stays_inside_a_narrow_window (#9150) 2026-12-05 06:01:15 -03:00
autocraft-bot[bot] 35dafa9376 Merge pull request #9166 2026-12-05 08:59:20 +00:00
autocraft-bot[bot] 85a7c754b3 Merge main (d417b835) into the pull request 2026-12-05 08:59:20 +00:00
autocraft-bot[bot] dffc8f903c Merge pull request #9154 2026-12-05 08:59:14 +00:00
autocraft-bot[bot] 26ef54f4df Merge main (d417b835) into the pull request 2026-12-05 08:59:14 +00:00
autocraft-bot[bot] 81d0cf4a01 Merge pull request #6980
With AutoCraft's conflict resolution 3f8cc02a.
2026-12-05 08:29:06 +00:00
autocraft-bot[bot] 82c9dc4a51 Merge pull request #9167 2026-12-05 08:29:06 +00:00
batistalucasv 9866095090 Show pointing hand on Ctrl/Cmd over linked pictures and shapes (#9145) 2026-12-05 05:29:06 -03:00
batistalucasv 41532af120 docs(ui-egui): clarify that equation argument shade is painted over text (#9156) 2026-12-05 05:28:17 -03:00
autocraft-bot[bot] 4d90a255ab Merge pull request #9162 2026-12-05 08:22:52 +00:00
batistalucasv fa1687eedf Keep text cursor on Ctrl/Cmd+Shift inside a linked text box (#9146) 2026-12-05 05:22:52 -03:00
batistalucasv 918772e8ed test(canvas): verify pointing hand cursor when hovering a link with Ctrl/Cmd (#9147) 2026-12-05 05:22:14 -03:00
autocraft-bot[bot] 9fa7295ea6 Merge pull request #9153 2026-12-05 08:14:37 +00:00
batistalucasv 6d09c5069c Key recent symbol tiles by symbol and font (#9004) 2026-12-05 05:14:37 -03:00
autocraft-bot[bot] c7fe2a479d Merge pull request #9144 2026-12-05 08:04:45 +00:00
Mat Strange 6eadc423fd #8955: folder settings expand ~/ from the profile folder on Windows
`folder_setting` expanded `~/` from `HOME` only: with `HOME` unset it left
the path relative and refused it, and with `HOME` set to another home it
expanded there, disagreeing with the recent list (#8865). Read the home
folder the same way the recent list does — `USERPROFILE` first on Windows,
`HOME` first elsewhere — and refuse `~/` with a clear message when there
is no home folder to expand under.
2026-12-05 08:04:45 +00:00
batistalucasv 2502cb5467 Skip all layout-hidden tracked deletions in Ctrl+Left and Ctrl+Right (#9030) 2026-12-05 05:04:27 -03:00
yoriswind 916b99cd1f Restore the saved header and footer selection on refusal 2026-12-04 23:43:41 -08:00
autocraft-bot[bot] c8b88a23a1 Merge pull request #9141 2026-12-05 07:42:32 +00:00
yoriswind a22cb3d822 Use a valid sparse row for the stale table grid test 2026-12-04 23:42:32 -08:00
yoriswind 49a5373fa2 Preserve table cell spacing in plain-text export 2026-12-04 23:37:06 -08:00
autocraft-bot[bot] 610ec99314 Merge pull request #9126 2026-12-05 07:35:57 +00:00
aiongg c555672b56 Merge pull request #8416 from davidmann4/feat/agents-open-window
feat(automation): agents in the open window through the ArtCraft Launcher's switch
2026-12-05 02:35:57 -05:00
autocraft-bot[bot] d417b835b0 Merge pull request #9130
With AutoCraft's CI fix 680f106b for the pull requests merged with it.
2026-12-05 07:35:57 +00:00
autocraft-bot[bot] 4e35526836 Merge pull request #9105 2026-12-05 07:35:57 +00:00
autocraft-bot[bot] 3094b3e02f Merge pull request #9129 2026-12-05 07:35:57 +00:00
autocraft-bot[bot] 071dfbb228 Merge pull request #9073
With AutoCraft's conflict resolution 28b4b098.
2026-12-05 07:35:57 +00:00
autocraft-bot[bot] d98742d1cb Merge pull request #9068
With AutoCraft's conflict resolution 7522113e.
2026-12-05 07:35:57 +00:00
autocraft-bot[bot] 20f26da670 Merge pull request #9135 2026-12-05 07:35:57 +00:00
autocraft-bot[bot] 1b284b7532 Merge pull request #9134 2026-12-05 07:35:57 +00:00
autocraft-bot[bot] 74a6b48bf6 Merge pull request #9131 2026-12-05 07:35:57 +00:00
autocraft-bot[bot] 005e028be7 Merge pull request #9124 2026-12-05 07:35:57 +00:00
autocraft-bot[bot] 882cac2672 Merge pull request #9119 2026-12-05 07:35:57 +00:00
autocraft-bot[bot] e6b39f3d0f Merge pull request #9011 2026-12-05 07:35:57 +00:00
autocraft-bot[bot] 08b54d1166 Merge pull request #9113 2026-12-05 07:35:57 +00:00
autocraft-bot[bot] b1aabef2cf Merge pull request #9107 2026-12-05 07:35:57 +00:00
autocraft-bot[bot] 044f06a9c6 Merge pull request #9106 2026-12-05 07:35:57 +00:00
autocraft-bot[bot] 183342276b Merge pull request #9100 2026-12-05 07:35:57 +00:00
autocraft-bot[bot] ba4c143c9d Merge pull request #9074 2026-12-05 07:35:57 +00:00
autocraft-bot[bot] 95748dc79d Merge pull request #9053 2026-12-05 07:35:57 +00:00
yoriswind 009a94b4d0 Keep default headers and footers when removing a first-page variant 2026-12-04 23:29:22 -08:00
Martin BallandClaude Sonnet 5.5 c1a23c6a1f #8872: a merge's continuing fill no longer covers the cell's side borders
The continuation fill was pushed after the row's items, so it painted over the inner half of the side and bottom borders. Fills now go first, the opening top rules last.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-12-05 07:19:01 +00:00
yoriswind 79f0fef906 Measure the actual Index stop for hidden tabs 2026-12-04 22:42:56 -08:00
codeiouandClaude Code 22325c2575 Home: centre the Paragraph ribbon rows horizontally
Opt the Paragraph group into centred natural-width rows while preserving
existing two-row callers, control sizes, vertical spacing and collapse
behaviour. Cover expanded and collapsed layouts in both directions with
relational geometry assertions.

Co-Authored-By: Claude Code <[email protected]>
2026-12-05 17:22:36 +11:00
codeiouandClaude Code 37981b4fca Docs: qualify control input ordering by viewport
Limit the clickText-to-type FIFO guarantee to the same viewport and explain
that changing the active window can select another queue. Keep the existing
warning that a reply does not establish completed input.

Co-Authored-By: Claude Code <[email protected]>
2026-12-05 17:22:36 +11:00
batistalucasv a4ad65c372 docs(layout-parity): fix rows_outrank_grid_total module path (#9076) 2026-12-05 03:12:17 -03:00
yoriswind 4781d91473 Preserve Index leaders when the page-number tab is hidden 2026-12-04 22:08:54 -08:00
Martin BallandClaude Sonnet 5.5 04a3c76c10 #8872: a merged cell keeps its fill across a column break and a page start
A column change now starts a merge continuation like a page change; closing a page
trims only items this table placed there; a row laid out alone for a page start
still knows the restart fills of earlier rows.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-12-05 06:04:47 +00:00
batistalucasv e8414db9a5 xtask(layers): forbid craft-ui, craft-window, craft-update below L6 and update architecture docs (#6057) 2026-12-05 03:01:39 -03:00
Martin BallandClaude Opus 5.5 fbe41cca76 #9111: no test for a pixel loop; an empty sheet image is left alone
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCXNomWeGUu3duixKdm
2026-12-05 05:55:54 +00:00
Martin BallandClaude Sonnet 5.5 553f0058ee #9111: Print preview shows the sheet's edge, so a portrait page no longer looks like a landscape sheet
The preview pane's background is as white as the paper, so the sheet's own shape was invisible: a portrait sheet centred in a wide pane read as a landscape sheet with the page off to one side. The sheet and orientation logic were correct (Auto keeps the page's own orientation, page centred). The drawn sheet now has a one-pixel grey edge.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCXNomWeGUu3duixKdm
2026-12-05 05:50:55 +00:00
bmh129 c4ab2fea70 Windows: a click makes its window active, so View › New Window copies its document (#9128)
A window became active only when it gained focus. GNOME can keep focus on
the first window when New opens another, so clicking the first window
again sent no focus change, and the commands it fired ran in the new
window. A press or key in a window now makes it the active one.
2026-12-04 23:45:22 -06:00
yoriswind 47ef5ce7b3 Keep the tab leader with a relocated Index field 2026-12-04 21:44:15 -08:00
batistalucasv 824d3c431e test(ui): skip Arabic ribbon tests without embedded Arab face unless CRAFT_FONTS_REQUIRED=1 (#8000) 2026-12-05 02:41:31 -03:00
batistalucasv d2c8ba2787 docs(localization-parity): confirm RFC-0011 release env and record binary sizes (#7861) 2026-12-05 02:39:10 -03:00
yoriswind 8370cf558d Use the laid-out Index page-number tab leader 2026-12-04 21:18:13 -08:00
yoriswind 257bc77e69 Comments pane: keep resolved comment text read-only 2026-12-04 21:06:12 -08:00
batistalucasv c7b4dfab8b test(ui-egui): trim comment balloon harness frames under 1 s (#9110) 2026-12-05 01:51:48 -03:00
yoriswind 0171216a13 Tests: count connector reroute lookup work 2026-12-04 20:28:44 -08:00
yoriswind f0a323fdce Tests: give continuous-view page navigation room to reverse 2026-12-04 20:14:08 -08:00
yoriswind 6a3a18eba5 Fields: retain REF ancestors for literal %0 labels 2026-12-04 20:08:54 -08:00
yoriswind 0242af0fdb Fields: keep counted zeros in STYLEREF numbering 2026-12-04 20:05:09 -08:00
yoriswind 4f8ac61c76 Text: import vertical tabs as manual line breaks 2026-12-04 19:59:54 -08:00
yoriswind d7c01bcd05 Index dialog: preserve style-inherited tab leaders 2026-12-04 19:50:57 -08:00
autocraft-bot[bot] 789cabd832 Merge pull request #9097 2026-12-05 03:48:27 +00:00
batistalucasv 6545c44f0a Engine tests: serialize dictionary-mutating tests and layout cache test on DICT_TEST_LOCK (#8886) 2026-12-05 00:48:27 -03:00
autocraft-bot[bot] b22e901c45 Merge pull request #9095 2026-12-05 03:45:18 +00:00
Martin BallandClaude Sonnet 5.5 c60c82d960 #8915: formula editor shades the active argument translucently, so its text shows
Cause: the port painted the argument shading with the opaque accent.soft token over the text. Fix: accent.solid at alpha 40, as v0.19.1's translucent shade.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCXNomWeGUu3duixKdm
2026-12-05 03:45:18 +00:00
autocraft-bot[bot] 67bfa46a3d Merge pull request #9093 2026-12-05 03:38:03 +00:00
batistalucasv 513ff0541f Windows: add valid child control case to cascade skip test (#9075) 2026-12-05 00:38:03 -03:00
yoriswind d4a565447f Format the clipboard shortcut regression 2026-12-04 19:35:13 -08:00
autocraft-bot[bot] 6f7b8156dc Merge pull request #6361
With AutoCraft's conflict resolution bb27a377.
2026-12-05 03:32:03 +00:00
autocraft-bot[bot] a21324bf78 Merge pull request #9090 2026-12-05 03:32:03 +00:00
batistalucasv a39f6adf9f docs(layout-parity): state tblGrid width mismatch condition in table row and summary (#9077) 2026-12-05 00:32:03 -03:00
autocraft-bot[bot] b2dd74729f Merge pull request #9089 2026-12-05 03:30:34 +00:00
batistalucasv 5ea160c706 Layout: test stale_grid_widths refusal for gridAfter (#9079) 2026-12-05 00:30:34 -03:00
autocraft-bot[bot] 8a7fef3ec6 Merge pull request #9061 2026-12-05 03:27:47 +00:00
autocraft-bot[bot] 84118adcf9 Merge pull request #9088 2026-12-05 03:27:47 +00:00
yoriswind 0ec775a9b9 Text: honor either BOM for the generic UTF-32 label 2026-12-04 19:27:47 -08:00
autocraft-bot[bot] caf9c8de8b Left/Right in rotated table cells no longer jump to another cell, and th
Left/Right in rotated table cells no longer jump to another cell, and they step along the text at the edge of a cell's lines. `turned_line` now only counts turned lines with the same parent path as the caret's paragraph (same story level or same table cell). The engine's `line_step` falls back to `lr_along` when there is no such line. I added a layout test for the cell case and updated the typing-parity row. fmt, clippy and the layout and engine caret and vertical tests pass.
2026-12-05 03:21:26 +00:00
autocraft-bot[bot] 135c1f72b1 Merge pull request #7560
With AutoCraft's conflict resolution e90d6670.
2026-12-05 03:20:54 +00:00
aionggandautocraft-bot[bot] <354215646+autocraft-bot[bot]@users.noreply.github.com> c07b649e7b Merge pull request #8978
Co-authored-by: autocraft-bot[bot] <354215646+autocraft-bot[bot]@users.noreply.github.com>
2026-12-05 03:20:54 +00:00
autocraft-bot[bot] c70ad1bab2 Merge pull request #9083 2026-12-05 03:20:54 +00:00
yoriswind 4358f546d8 Insert Field: use language defaults for dates and times 2026-12-04 19:20:54 -08:00
autocraft-bot[bot] 6b79b722d3 Part 1: quit() in crates/ui-egui/src/windows.rs now returns true right
Part 1: `quit()` in crates/ui-egui/src/windows.rs now returns true right away when a quit is already pending and no print job is busy. It no longer calls `close_requested()` in that case, so a second quit can't use up `quit_recheck` or clear `quit_requested`. If a print job is busy, a second quit still goes through `close_requested()` and refuses, as before. On a first quit that is allowed, `quit_recheck` is set to true. I added no new test. Checks: `cargo fmt --all --check` passes. `cargo clippy -p wordcraft-ui-egui --all-targets -- -D warnings` passes; its only warning is the existing unused `egui_extras` dependency. The 9 lib tests matching `quit` pass, including `quit_commits_the_focused_fields_draft_before_asking`. I did not run the rest of the lib suite.
2026-12-05 03:17:04 +00:00
autocraft-bot[bot] eba89475f6 Merge pull request #9067 2026-12-05 03:15:57 +00:00
autocraft-bot[bot] 64ef08c60a Merge pull request #9065 2026-12-05 03:15:57 +00:00
autocraft-bot[bot] bc71452511 Merge pull request #9062 2026-12-05 03:15:57 +00:00
autocraft-bot[bot] fb9276c4a6 Part 1: in enter_outdents_an_empty_list_item_and_drops_direct_indents
Part 1: in `enter_outdents_an_empty_list_item_and_drops_direct_indents` (crates/engine/src/tests/typing.rs), the style sheet edit is now `Arc::make_mut(&mut doc.styles).upsert(..)` instead of `doc.styles.upsert(..)`. The lib tests build again and the new test passes. `cargo fmt --check` and `cargo clippy --all-targets` on wordcraft-engine report nothing. All 213 `typing` tests pass. I did not run the rest of the crate's tests.
2026-12-05 03:15:57 +00:00
Martin BallandClaude Sonnet 5.5 ce2b01e005 #8855: touchpad scrolling glides on after the fingers lift again on Linux
The v0.19.1 scroll code synthesised touchpad momentum where the system sends none. The craft-ui port moved wheel handling to craft-libs' canvas, whose touchpad_glide option is off by default and was never enabled. Enable it on the platforms v0.19.1 used (not macOS, Windows, web).

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCXNomWeGUu3duixKdm
2026-12-05 03:15:27 +00:00
yoriswind c2a370cd67 Index dialog: keep the existing tab leader 2026-12-04 19:15:21 -08:00
batistalucasv 0a31f5de5d Replace All: restore selection under Track Changes when original story has no match 2026-12-05 00:10:08 -03:00
batistalucasv 1129aa51f2 Replace All: skip hidden stories via Document::shown_stories (#9064) 2026-12-05 00:08:38 -03:00
Martin BallandClaude Sonnet 5.5 4ad6272409 #8975: Ctrl/Cmd over a link shows the pointing hand
Cause: the page tool's cursor never considered links; Word shows the hand when Ctrl/Cmd is held over one (a click then follows it). Link style (Hyperlink char style) was already applied by insert.link and renders underlined.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCXNomWeGUu3duixKdm
2026-12-05 03:04:15 +00:00
yoriswind 70e181a966 Lists: reset direct indents when Enter outdents an empty item 2026-12-04 18:58:48 -08:00
autocraft-bot[bot] 496d276873 Merge pull request #9039 2026-12-05 02:58:25 +00:00
Martin BallandClaude Opus 5.5 32ad05fe64 #8832: a failed multi-picture edit puts the picture originals and looks back too
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCXNomWeGUu3duixKdm
2026-12-05 02:58:25 +00:00
Martin BallandClaude Sonnet 5.5 b2dd18c916 #8986: test vertical arrow line stepping in layout with the fixed fonts
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCXNomWeGUu3duixKdm
2026-12-05 02:57:53 +00:00
autocraft-bot[bot] dc9327501c Merge pull request #9058 2026-12-05 02:56:29 +00:00
batistalucasv b2021313ab Fix flaky continuous-view and connector-reroute engine tests (#9056) 2026-12-04 23:56:29 -03:00
autocraft-bot[bot] 41b351d770 Merge pull request #9057 2026-12-05 02:50:04 +00:00
batistalucasv 3fbc536eba test(canvas): derive tooltip wait frames from harness step time (#9052) 2026-12-04 23:50:04 -03:00
Martin BallandClaude Sonnet 5.5 7342c32b1e #8986: arrow keys follow vertical text like Word
Cause: Up/Down looked for horizontal lines only (turned lines are skipped), found none and
jumped to the story start/end; Left/Right always stepped along the text.
Fix: in turned text Up/Down step along the line and Left/Right move to the next/previous line
(direction by the text direction), via new DocLayout::turn_at and turned_line.

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

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

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

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCXNomWeGUu3duixKdm
2026-12-05 02:10:01 +00:00
kiwi4boy 1f6eb8eceb Merge remote-tracking branch 'origin/main' into tight-gap-6316
Conflicts with main's right-to-left floating table offset (FloatPlace) in
boxes.rs, the line-end kerning helper in para/lines.rs and new rows in
docs/layout-parity.md; both sides kept. The hidden-mark joined-line areas
main added (#3986) are AreaKind::Object, as every non-table area was the
previous bool's false.
2026-12-04 21:07:21 -05:00
autocraft-bot[bot] 087bf2535b Merge pull request #9017 2026-12-05 02:05:47 +00:00
autocraft-bot[bot] 7a408c7eb3 Part 1: I added mod reproducible_pdf; to apps/wordcraft-cli/tests/it/m
Part 1: I added `mod reproducible_pdf;` to apps/wordcraft-cli/tests/it/main.rs, between `mod picture_then_typing;` and `mod strict;`. The moved tests are now compiled into the `it` test binary again. `cargo fmt --check` is clean. `cargo clippy --offline -p wordcraft-cli --all-targets -- -D warnings` finished with no errors. `TZ=UTC cargo test --offline -p wordcraft-cli --test it reproducible_pdf` now runs 5 tests and all pass.
2026-12-05 02:05:47 +00:00
autocraft-bot[bot] 7b213b331b Merge pull request #9028 2026-12-05 02:00:10 +00:00
batistalucasv d62508ca40 Docs: document stale_grid_widths handling of missing or mismatched tblGrid (#8924) 2026-12-04 23:00:10 -03:00
batistalucasv a1ad0f4cbc docs(layout-parity): document autofit table row-width rule (#8923) 2026-12-04 22:59:52 -03:00
batistalucasv 9c54fc1446 test(docx): verify run style and resolved emphasis across saves (#8936) 2026-12-04 22:57:24 -03:00
autocraft-bot[bot] fbde8c47a3 Merge pull request #9024 2026-12-05 01:57:02 +00:00
batistalucasv 481207f29d docs: update typing-parity Tab / Shift+Tab row (#8933) 2026-12-04 22:57:02 -03:00
Martin BallandClaude Sonnet 5.5 e3f9ed8134 #8945: regression test for Navigation pane tab clicks
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-12-05 01:55:48 +00:00
autocraft-bot[bot] 4add275c07 Merge pull request #9022 2026-12-05 01:53:36 +00:00
batistalucasv 5f39de62f8 Tests: set en-US explicitly in Change Case English control check (#8953) 2026-12-04 22:53:36 -03:00
autocraft-bot[bot] 830065bd62 Merge pull request #9021 2026-12-05 01:53:08 +00:00
batistalucasv 31b2be75f4 Windows: test zero-size, non-finite, and skipped cascade predecessors (#8944) 2026-12-04 22:53:08 -03:00
autocraft-bot[bot] 195f103ceb I put escape_reverts_a_comment_draft back on the balloon path. It now
I put `escape_reverts_a_comment_draft` back on the balloon path. It now uses the comment harness, `click_balloon`, types a draft, presses Escape (one frame), then calls `leave_field`, which really clicks on the page. The final check that nothing is written is back. I added one assertion before it: the page click must have left the balloon (no balloon selected), so `deselect_balloon`/`write_back` really ran.

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

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

Checks: `cargo fmt --check` is clean, clippy on wordcraft-ui-egui with all targets and `-D warnings` is clean, and all 20 tests in canvas::tests::markup pass. As a temporary check, I put a draft back just before `leave_field`. The final assertion then failed with "Discarded" written over "Original", so it can catch the regression the review describes. I then reverted that change.
2026-12-05 01:52:39 +00:00
autocraft-bot[bot] 96b8c1c58b Merge pull request #9020 2026-12-05 01:51:30 +00:00
batistalucasv de30199f1f test(ui-egui): cover multi-candidate srcset clipboard offers (#8941) 2026-12-04 22:51:30 -03:00
autocraft-bot[bot] 14ed0bfa28 Merge pull request #3309
With AutoCraft's conflict resolution e8108806.
2026-12-05 01:49:31 +00:00
autocraft-bot[bot] bf54864f37 Merge pull request #9019 2026-12-05 01:49:31 +00:00
batistalucasv 61893e1950 test(docx): assert full run emphasis mark list in run_props 2026-12-04 22:49:31 -03:00
batistalucasv b6777d494c test(wordcraft-cli): move reproducible_pdf integration tests into tests/it 2026-12-04 22:38:32 -03:00
autocraft-bot[bot] 434d9b223e Merge pull request #9016 2026-12-05 01:38:10 +00:00
autocraft-bot[bot] 802a2e2120 Merge pull request #9015 2026-12-05 01:38:10 +00:00
batistalucasv 83f437ec89 Tests: restore selection-based mixed-run Change Case check (#8952) 2026-12-04 22:38:10 -03:00
batistalucasv 3bae0c1cdb test(engine): pass whole: false in staged table-end select.all test (#8961) 2026-12-04 22:38:04 -03:00
autocraft-bot[bot] aa2c33e5a9 Merge pull request #9013 2026-12-05 01:32:46 +00:00
autocraft-bot[bot] c26f801e20 Merge pull request #9012 2026-12-05 01:32:46 +00:00
batistalucasv 7b1d234029 test(cli): clean up temp script on drop in failed_run_commands_still_exit_with_an_error 2026-12-04 22:32:46 -03:00
autocraft-bot[bot] 7361228721 Merge pull request #9009 2026-12-05 01:32:46 +00:00
batistalucasv 05dda70d5c tests(engine): simplify select_all_then_delete_removes_tables after #8862 2026-12-04 22:31:35 -03:00
Martin BallandClaude Sonnet 5.5 17fecc43ec #8872: an unshaded merge does not take the shading of an earlier one
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCXNomWeGUu3duixKdm
2026-12-05 01:29:10 +00:00
autocraft-bot[bot] 0d8409ea36 Merge pull request #9010 2026-12-05 01:27:59 +00:00
batistalucasv 4281ebbcb1 docs(layout-parity): clarify first-pass 648 pt cap and second-pass 1584 pt rewrap for turned text (#8976) 2026-12-04 22:27:59 -03:00
batistalucasv 3843ada39b docs(ui-egui): document params.pointer(at) precedence in colors::current_of (#8982) 2026-12-04 22:27:33 -03:00
autocraft-bot[bot] ed17e883e5 Merge pull request #9008 2026-12-05 01:24:45 +00:00
batistalucasv a0ca3766b3 xtask(wasm): unit-test wasm summary instead of running cargo check 2026-12-04 22:24:45 -03:00
Martin BallandClaude Sonnet 5.5 1a7b691293 #8872: a merged cell crossing a page break closes at the page end and continues on the next page
Rows are laid out before pagination, so a vertically merged cell had no border where a
page ended and no fill or top border where it went on. Rows now carry the merge's closing
bottom border and its continuation fill and top border; place_table adds them when a page
ends or starts inside a merge, and the cell areas end with the last row on the page.

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

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCXNomWeGUu3duixKdm
2026-12-05 01:13:02 +00:00
autocraft-bot[bot] ecd8b5db7b Merge pull request #9003 2026-12-05 01:08:28 +00:00
batistalucasv ffadc1d8de fix(ui): run edit.paste directly from context and ribbon Paste menu items (#8849) 2026-12-04 22:08:28 -03:00
Martin BallandClaude Sonnet 5.5 06d7d3e9a6 #8945: Navigation pane Headings, Pages and Results tabs switch views again
The pane read TabStrip's overflow-menu pick (out.picked) instead of the selection event a click or key raises, so tabs never switched and search results stuck. Read the selection event.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-12-05 00:41:46 +00:00
autocraft-bot[bot] e4e2c2d9d7 Merge pull request #7110
With AutoCraft's conflict resolution 6f202ab6.
2026-12-05 00:08:07 +00:00
autocraft-bot[bot] dba4269b25 Merge pull request #8805 2026-12-05 00:08:07 +00:00
batistalucasv 7888d77bbd caret: skip hidden tracked deletions in Ctrl+Left and Ctrl+Right (#8772) 2026-12-04 21:08:07 -03:00
autocraft-bot[bot] 94aa34729c Ask about a focused field's typed text when quitting from the menu
Ask about a focused field's typed text when quitting from the menu

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

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

Testing:
- The new test passes. I did not rerun it without the fix; AutoCraft's investigation showed the same core assertions failing on the default branch.
- The crate's 62 quit and close tests pass.
- `cargo fmt --all --check` passes.
- `cargo clippy -p wordcraft-ui-egui --all-targets -- -D warnings` passes; its only warnings are unused workspace dependencies in the manifest that were already there.
- The full `wordcraft-ui-egui` lib suite was started but did not finish before the session's shell time ran out, so I can't report it.
- Not run: `cargo xtask layers`, `cargo xtask wasm`, and the tests in `apps/wordcraft`, including its ⌘Q test.
2026-12-04 22:40:52 +00:00
autocraft-bot[bot] 51ef42c9f5 Merge pull request #7948 2026-12-04 22:28:41 +00:00
autocraft-bot[bot] a57a77d4c5 Two of the three changes were already in the head commit (c984354a9). Th
Two of the three changes were already in the head commit (c984354a9). The second was only half done: its cross-font test single-clicked the tile and then pressed Insert, so it never tested double-clicking. I changed that test to double-click, and I reworded the harness comment. The tests have not run: formatting passes, but the test build never finished.

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

`cargo fmt --all -- --check` passes. I could not confirm that the `dialogs::dialogs_insert::tests::` tests pass. The first run timed out waiting for build room. The second sat with no output for about 78 minutes while the build pod restarted several times, and I stopped it. CI needs to show that the changed test passes.
2026-12-04 22:28:41 +00:00
autocraft-bot[bot] d0dbc425ee I made both changes FredApps asked for in crates/doc/src/numbering.rs. A
I made both changes FredApps asked for in crates/doc/src/numbering.rs. A start override of 0 now makes the first item 0, and the new test `start_override_of_zero_starts_at_zero` sets `start_overrides = vec![(0, 0)]` and gets the labels ["0.", "1.", "2."].

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

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

Test results: formatting and clippy are clean for wordcraft-doc, and its 148 tests pass. The wordcraft-docx tests pass. In wordcraft-layout, 325 tests pass and 6 fail (line justification, tabs, widow control, footnotes, a floating table, linear-time layout). None of those 6 builds a list, so the failures don't come from this change, but I did not run them without it to confirm.
2026-12-04 21:26:59 +00:00
autocraft-bot[bot] 6e67012f78 I made both changes FredApps asked for in crates/formats/src/txt.rs. Fir
I made both changes FredApps asked for in crates/formats/src/txt.rs. First, in the table branch of `blocks_text`, the two identical branches are now one: `if c.covered || depth > 8 { cells.push(String::new()); } else { ... }`. This fixes the clippy::if_same_then_else error. Second, the test `test_table_export_colspan_covered_and_newline_cleaning` now builds its cells as `let mut c1 = Cell { colspan: 2, ..Default::default() };` and `let c3 = Cell { covered: true, ..Default::default() };`. c1 stays `mut` because the test adds a paragraph to it afterwards, and c3 no longer needs `mut`. `cargo fmt --check` passes. `cargo clippy --offline -p wordcraft-formats --all-targets -- -D warnings` finished with no warnings, so neither lint fires now. I only ran the three txt tests, and all of them pass; the full wordcraft-formats test run timed out in the build pod, so it wasn't run. Nothing else changed.
2026-12-04 21:24:50 +00:00
autocraft-bot[bot] 79ab962f36 Merge pull request #8819
With AutoCraft's conflict resolution ba887ee7.
2026-12-04 19:46:28 +00:00
autocraft-bot[bot] 43f636055e Merge pull request #8798
With AutoCraft's conflict resolution e7b9c769.
2026-12-04 19:46:28 +00:00
autocraft-bot[bot] 76e76b7697 Merge pull request #8789
With AutoCraft's conflict resolution 367694e5.
2026-12-04 19:46:28 +00:00
autocraft-bot[bot] 4c467c1485 Merge pull request #8766
With AutoCraft's conflict resolution 2541c1f4.
2026-12-04 19:46:28 +00:00
autocraft-bot[bot] f9b8b60873 Merge pull request #7955 2026-12-04 19:46:28 +00:00
autocraft-bot[bot] 259870a313 Merge pull request #7197 2026-12-04 19:46:28 +00:00
autocraft-bot[bot] b864439f5c The cause is in the PR's new test, not the app. The test takes the picke
The cause is in the PR's new test, not the app. The test takes the picker's Close button as the first node labelled "Close" inside the picker. The Add a language dialog has two: one in its title bar, at y0=208 in a 1440x900 frame, and the footer's at y0=670. Which one comes first in the accessibility tree depends on node ids. On macOS in the batch it picked the title-bar one, so the test computed the list's visible bottom as 208, above its top of 275. That is the `(reason, top, bottom)` of `Some((… y0: 390 …), 275.0, 208.0)` in the log, so the fit assertion at line 1744 failed. I did not run it on macOS. On Linux the test passed before and after the change, and I printed the nodes there to confirm the title-bar Close at y0=208. The fix is in the test helper in `crates/ui-egui/src/language_packs.rs`. It now collects every Close inside the picker. It keeps only those below the Search field and takes the topmost, which is the footer's. The test is no looser: it still checks that the whole reason fits in the list's visible area. `cargo fmt --check` is clean. Clippy is clean with `-D warnings`. All 18 `language_packs` tests pass.
2026-12-04 19:46:28 +00:00
autocraft-bot[bot] cd7c14e776 Merge pull request #8865 2026-12-04 17:53:43 +00:00
autocraft-bot[bot] 85dd661854 Merge pull request #7856
With AutoCraft's conflict resolution 61f8e8d7.
2026-12-04 17:53:43 +00:00
Dylan M. Taylor b7f512d037 Merge pull request #8864 from storytold/docs/freebsd-15-release-requirement
docs: specify the FreeBSD release requirement
2026-12-04 12:53:43 -05:00
autocraft-bot[bot] 62ff8ba0c2 Merge pull request #8722
With AutoCraft's conflict resolution f72513fa.
2026-12-04 17:53:43 +00:00
autocraft-bot[bot] 4680b9a270 Merge pull request #7067
With AutoCraft's conflict resolution 1c87a92b.
2026-12-04 17:53:43 +00:00
skylar taylorandskylartaylor 29c67c62d7 Release: bump WordCraft to v0.20.1 (#8889)
Co-authored-by: skylartaylor <[email protected]>
2026-12-04 11:37:41 -06:00
autocraft-bot[bot] 0866c5bfaa Merge pull request #8870 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 68680e0665 Merge pull request #8867 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 78d6825d3b Merge pull request #8873 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] be1f9c0a1f Merge pull request #8866 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] f329ff6e81 Merge pull request #8863 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 8f330f5e26 Merge pull request #8862 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] a6ee9f22a4 Merge pull request #8858 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] cf95e5a37a Merge pull request #8845 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 1469c44e81 Merge pull request #8844 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] d184ccbfb4 Merge pull request #8833 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 0adadeed56 Merge pull request #8826 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] b3dbe51f1a Merge pull request #8817 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] b1a17b688f Merge pull request #8816 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 3adb7b5055 Merge pull request #8815 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 92c65bc00b Merge pull request #8807 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 61b83a4927 Merge pull request #8806 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 84d46c47f4 Merge pull request #8804 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] ae760626cf Merge pull request #8803 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] c2d2e93500 Merge pull request #8802 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 995746d24e Merge pull request #8688
With AutoCraft's conflict resolution 10509511.
2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 21671b9b66 Merge pull request #1259
With AutoCraft's conflict resolution 198d76f0.
2026-12-04 16:37:24 +00:00
autocraft-bot[bot] e2079632f3 Merge pull request #8003
With AutoCraft's conflict resolution e89186d1.
2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 22f774fb9f Merge pull request #6974
With AutoCraft's conflict resolution 504e41b8.
2026-12-04 16:37:24 +00:00
autocraft-bot[bot] d847fa225e Merge pull request #6525
With AutoCraft's conflict resolution 3e473b5a.
2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 6a91bc63f6 Merge pull request #4582
With AutoCraft's conflict resolution 5a6712e2.
2026-12-04 16:37:24 +00:00
autocraft-bot[bot] a8628f3969 Merge pull request #4322
With AutoCraft's conflict resolution 9f1ca725.
2026-12-04 16:37:24 +00:00
autocraft-bot[bot] d46178a145 Merge pull request #5954
With AutoCraft's conflict resolution ffbe0065.
2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 489d61cd10 Merge pull request #4995
With AutoCraft's conflict resolution f4a74773.
2026-12-04 16:37:24 +00:00
autocraft-bot[bot] f71bf017a7 Merge pull request #3089
With AutoCraft's conflict resolution 199d64f9.
2026-12-04 16:37:24 +00:00
autocraft-bot[bot] da8845c810 Merge pull request #8797 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 7605fd3c8a Merge pull request #8796 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 51b1933480 Merge pull request #8794 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] d0fc72a7ba Merge pull request #8788 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] e4950a63b5 Merge pull request #8781 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 7b7e2a7ff6 Merge pull request #8765 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 1f57c527a2 Merge pull request #8762 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 450938fe00 Merge pull request #8764 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] a9917af050 Merge pull request #8761 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 9757882dda Merge pull request #8760 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] e85e15ee14 Merge pull request #8757 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 5abe5745ce Merge pull request #8754 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 522597264c Merge pull request #8753 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 78bec40359 Merge pull request #8748 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] d3508c9d18 Merge pull request #8724 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 366ecb731e Merge pull request #8713 2026-12-04 16:37:24 +00:00
autocraft-bot[bot] 0dac42909e Merge pull request #8712 2026-12-04 16:37:24 +00:00
Martin BallandClaude Opus 5.5 3f33f90f31 #8838: a document window can be maximized and taken full screen again on Windows (#8871)
* #8838: a document window can be maximized and taken full screen again on Windows

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

Closes #8838, closes #8861

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

Fixes #8441. Fixes #8517.

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

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

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

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

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

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

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

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

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

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

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

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

---------

Co-authored-by: FredApps <[email protected]>
2026-12-04 06:11:22 +01:00
Max MittelstädtandGPT-6-Luna 9621688eae Insert mid-document TOCs before paragraphs at offset zero
Fixes #8768

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


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

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

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

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

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

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-04 01:58:38 +01:00
batistalucasv 77d00e0ee1 Layout: re-apply space before below a second stacked Top-and-Bottom object 2026-12-03 21:46:39 -03:00
yoriswind 9cda9db296 Customize Keyboard: keep categories for unimplemented commands 2026-12-03 16:44:55 -08:00
autocraft-bot[bot] 500e150132 Merge pull request #8733 2026-12-04 00:42:46 +00:00
autocraft-bot[bot] 416db1b645 Merge pull request #7727 2026-12-04 00:42:46 +00:00
batistalucasv 3c79eca060 Tests: merge Turkic Change Case checks into typing.rs (#8423) 2026-12-03 21:42:17 -03:00
autocraft-bot[bot] a1aa614bf1 Merge main (5073f8e7) into the pull request
Resolved the conflict in crates/ui-egui/Cargo.toml. I kept the pull requ

Resolved the conflict in crates/ui-egui/Cargo.toml. I kept the pull request's `craft-html = { workspace = true }` line and took main's craft-libs pin 5299d8d9 for craft-fonts-build, which matches the workspace pin. Cargo.lock already lists craft-html and craft-fonts-build under wordcraft-ui-egui and has no references to the old d73e274a pin, so I left it alone. No conflict markers remain. I couldn't build or test the result: `cargo check --offline` fails because the egui git dependency can't be checked out without network access.
2026-12-04 00:36:14 +00:00
yoriswind 71abe1c4c9 Windows: preserve client size when cascading documents (#8752) 2026-12-03 16:10:28 -08:00
yoriswind 5ca9917471 Caret: follow editor visibility for tracked deletions (#8746) 2026-12-03 15:40:57 -08:00
yoriswind 37c8061088 Caret: skip wholly deleted paragraphs in No Markup (#8743) 2026-12-03 15:31:05 -08:00
yoriswind d53ba37903 Web: accept the screenshot helper inline data flag (#8726) 2026-12-03 14:28:42 -08:00
yoriswind 8633e63909 Review: format the middle paragraph regression cases 2026-12-03 11:42:51 -08:00
yoriswind 91a75c8103 Review: keep selection on surviving text after middle paragraph removal 2026-12-03 11:30:16 -08:00
yoriswind db329f1d84 Layout: avoid rescanning footnote paragraphs for each split 2026-12-03 08:58:49 -08:00
Mauro Mazzieri 48fca374b3 #7108: describe the rule, not measurements 2026-12-03 10:19:54 +01:00
Mauro Mazzieri 11323ff0dd #7110: describe the rule, not measurements
The test's comment, fit_height's doc comment and the parity history row
state the rule the code implements; test logic and assertions unchanged.
2026-12-03 10:13:46 +01:00
Mauro Mazzieri 5833546550 #7108: Page Setup keeps an exact margin it didn't change
An exact (negative) top or bottom margin the dialog still shows as the
section has it, on a page not turned, is left out of layout.margins, which
keeps a side left out; the fit checks count an exact margin at its size.
Regression test dialogs::tests::page_setup_keeps_an_exact_margin_it_didnt_change;
the parity history row names the existing command test correctly.
2026-12-03 10:00:35 +01:00
autocraft-bot[bot] 08eb9ccbb2 Part 1: kept_tail_end (flow.rs) now applies only when the balancing heig
Part 1: kept_tail_end (flow.rs) now applies only when the balancing height is below the uncapped column height, so the full-height fallback pass keeps the original layout and places every block. Part 2: kept_tail_end leaves the tail in place when the tail plus the next paragraph's start is taller than the uncapped column, the same check keep_together makes. Added tests a_continued_tail_that_cannot_fit_with_the_next_paragraph_stays_in_place (fails without the part 2 check) and balancing_fallback_places_every_paragraph (passes with either fix alone, so it does not isolate part 1). fmt and clippy are clean and the five columns tests pass. The full layout run has 758 passed and 2 failed: two timing tests of a single very long word, a_megabyte_long_word_lays_out_quickly and a_long_unbreakable_word_lays_out_in_linear_time, which also fail when run alone in this slow workspace. I did not confirm they fail without my change.
2026-12-03 00:04:37 +00:00
David MannandClaude Opus 5.5 e31df586db fix(automation): dialogs an agent opened keep its folders; agent_folders before the first call
A file dialog keeps the folders in force when it opened and handles its
answer inside them, so a path an agent typed into the fallback chooser can't
reach outside its folders on the later frame the answer arrives. Before any
call, agent_folders names the folders the next call will work in, the
roots given to mcp included.

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

Closes #8415.

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-02 22:19:18 +01:00
autocraft-bot[bot] ead0870d33 I updated docs/layout-parity.md, the only file changed. I changed no Rus
I updated docs/layout-parity.md, the only file changed. I changed no Rust code, so I did not run fmt, clippy or tests; only the doc was edited. (1) The header now reads "Last updated 2026-11-05" and its Change field leads with this change. (2) The "Default font metrics" checklist row now says that `wordcraft-cli convert` reports a core family (Times New Roman, Arial, Courier New, Calibri, Cambria) with no font and no open metric twin, naming the family drawn instead. It points to `fonts::word::missing_metric_fonts`. (3) I added a revision-history row dated 2026-11-05. It records the fallback and the author's page-count measurement: 120 two-line paragraphs are 6 pages in Word, 8 with no twin and 6 with Liberation Serif; 90 one-line paragraphs are 3 pages in all three. The row says these figures are the PR author's, that only page counts were compared, and that the Liberation files are still in open craft-fonts PRs. The row names the tests that exist: `core_font_notice_uses_the_actual_installed_face`, `a_listed_but_uninstalled_carlito_does_not_hide_the_chosen_fallback` and `missing_calibri_without_carlito_reports_the_drawn_fallback`. It does not name `a_missing_core_font_is_reported_only_without_a_metric_twin`, which does not exist. That wrong test name is still in the PR description, which I cannot edit; the author needs to fix it there.
2026-12-02 20:14:34 +00:00
autocraft-bot[bot] b3302eeef3 Part 1: in a document protected as read only, comments only or forms, Re
Part 1: in a document protected as read only, comments only or forms, Replace All now keeps only the matches inside the editable regions, in every story. A placeholder repeated in a header, footer, footnote or text box, or in locked body text, is left alone instead of making the whole command fail. The editable matches are replaced as before. I added `editable_ranges` in cmd/protect.rs: exception ranges the author may edit for read only and comments, and the interiors of fillable controls for forms. `replace_all` in cmd/edit.rs filters each story's matches through it before the locked-content check and the replacement. I added the test `replace_all_in_a_protected_document_skips_protected_matches` in cmd/protect/tests.rs, with an editable body region and `[NAME]` in a header, a footnote and locked body text. I did not check that it fails without the fix. `cargo fmt --all --check` is clean. The six `replace_all` tests pass, including the new one. The full engine test run was 1215 passed and 2 failed. The failures are `page_down_and_up_never_stay_on_a_line_in_the_continuous_views` and `rerouting_many_pages_does_not_rescan_all_objects_per_connector`. Neither touches Replace All, and I did not re-run them on the base commit. `cargo clippy -p wordcraft-engine --all-targets -- -D warnings` stops on one existing needless-range-loop lint at cmd/table_draw.rs:768, which I did not touch. I did not run clippy without test targets. One behaviour change: matches in locked body text of a protected document are now skipped silently. Before, they made the whole command fail.
2026-12-02 19:34:24 +00:00
autocraft-bot[bot] 1b8c2047dd Made drop_direct_indents reachable from the text module (pub(in crate::c
Made drop_direct_indents reachable from the text module (pub(in crate::cmd) in para/format.rs, re-exported from para.rs) and called it, only when the level actually changes, in tab, indent_by_tab (line-start, style-numbered case) and back_tab in enter_tab.rs. Extended changing_a_list_level_drops_a_direct_indent with text.tab (caret at item start) and text.backTab cases comparing a dragged item to a fresh one. fmt and lib clippy are clean; the typing tests pass. The full engine suite timed out in this workspace, so I ran only the tests matching changing_a_list_level, tab and list, plus the typing tests. A preexisting needless_range_loop clippy error in a test in cmd/table_draw.rs (not my change) stops --all-targets clippy. The indent_by_tab path has no new test.
2026-12-02 19:25:01 +00:00
Khawar Zamman Wani 5c41ef2f08 Merge PR branch head into rich-clipboard paste fix
# Conflicts:
#	crates/ui-egui/Cargo.toml
2026-12-02 15:41:14 +05:30
FredApps 1955eea91d Merge current main into browser-image paste branch 2026-12-02 08:50:20 +01:00
yoriswind 6db58aa0c0 fix(pdf): keep heading numbers in bookmarks 2026-12-01 15:57:27 -08:00
MaheshDesu b95bfbbb37 test(ui): pin the exact painted cursor over the font size box (#7757)
Signed-off-by: MaheshDesu <[email protected]>
2026-11-30 18:09:37 +05:30
MaheshDesu 3383d8a9f1 fix(ui): keep the ribbon font cursor visible on Windows (#7757)
Signed-off-by: MaheshDesu <[email protected]>
2026-11-30 18:09:37 +05:30
MaheshDesu be96af974d test(ui): pin the ribbon font fields' Windows cursor (#7757)
Signed-off-by: MaheshDesu <[email protected]>
2026-11-30 18:09:07 +05:30
batistalucasv 1342420920 test(comments): assert draft remains empty after clicking away 2026-11-30 01:50:11 -03:00
Khawar Zamman Wani 664980b32b Preserve rich clipboard content during ordinary paste 2026-11-30 09:14:12 +05:30
Khawar Zamman Wani 349556de8a Merge upstream main into clipboard paste fix 2026-11-30 09:13:40 +05:30
batistalucasv c984354a97 fix(ui): preserve selected recent symbol across cross-font load 2026-11-29 18:24:12 -03:00
batistalucasv a1dae5ad32 fix(ui): check pointer before command match in colors::current_of 2026-11-29 17:59:05 -03:00
batistalucasv e98df65d23 Symbol: double-clicking a recent symbol inserts it (#7947) 2026-11-29 16:54:00 -03:00
batistalucasv 654e1745f9 Format Shape: apply More Colors to solid fills and gradient stops (#7954) 2026-11-29 16:54:00 -03:00
554159685b fix(engine): resolve and reopen a comment's whole thread, replies included
review.resolveComment changed only the addressed comment's resolved flag, so
resolving a discussion left its replies open, and acting on a reply left its
parent and siblings unchanged.

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

Co-Authored-By: GPT-6.2 Astra <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-28 10:52:10 +10:00
FredApps 13dc60f05c Restore picture paste when Ctrl+V has image+HTML and no plain text
The merge of main into this branch dropped the post-fill hook in
commands.rs that pastes a clipboard picture when edit.paste has no
plain text. fill() only auto-inserts a bitmap when the HTML looks like
a single image offer, so a browser image plus fallback HTML failed
mod_v_pastes_rich_only_clipboard_and_preserves_picture_routing.
2026-11-28 07:03:14 +07:00
FredApps 2813a0961d Merge origin/main into fix/2909-browser-image-paste 2026-11-28 05:04:48 +07:00
batistalucasv b917ca74c1 Address review feedback: drive balloon editor and leave_field in escape_reverts_a_comment_draft (#1348) 2026-11-27 01:11:56 -03:00
batistalucasv 03070810eb Address review feedback: verify mini toolbar stays inside narrow viewport and canvas (#7317) 2026-11-27 00:47:26 -03:00
jayzed80 eff8661a58 Canvas: port context menu focus restoration onto craft-libs Menu (#6715) 2026-11-26 21:28:39 +00:00
jayzed80 acf8e9950d Merge remote-tracking branch 'upstream/main' into HEAD
# Conflicts:
#	crates/ui-egui/src/canvas/context_menu.rs
2026-11-26 18:46:48 +00:00
batistalucasv 4b772c030c test(mini_toolbar): pass rtl arg and verify bar placement in narrow viewport (#7317) 2026-11-26 14:01:26 -03:00
batistalucasv 3794d9718e Merge remote-tracking branch 'upstream/main' into HEAD 2026-11-26 13:55:13 -03:00
kiwi4boy 97daa4b3ed Layout: main's balanced-column test marks its float as an object (AreaKind, #6316) 2026-11-25 19:36:46 -05:00
kiwi4boy 7b03696d8c Merge remote-tracking branch 'origin/main' into tight-gap-6316
# Conflicts:
#	docs/layout-parity.md
2026-11-25 19:32:35 -05:00
batistalucasv bbad606bc3 test(ui-egui): run escape_reverts_a_comment_draft directly against comment_field 2026-11-25 12:46:16 -03:00
ViktorBystrov72 8a58d674b7 Preserve the restored letter’s hyperlink 2026-11-24 20:44:16 +05:00
Khawar Zamman Wani ddeab752da Prefer browser image pixels when the clipboard also offers RTF 2026-11-24 20:45:48 +05:30
Khawar Zamman Wani 81ed00867e Preserve picture-only Paste during equation editing 2026-11-24 18:10:19 +05:30
Khawar Zamman Wani 473942d205 Prefer the bitmap when pasting a browser image (#2909) 2026-11-24 16:59:31 +05:30
ViktorBystrov72 ef81c547af Captions: preview the number at the insertion point 2026-11-24 16:26:23 +05:00
dotCooCoo 4d1b530601 Language packs test: the refused reason is as wide as Install and fits the list once scrolled
The reason must be at least as wide as its row's Install button. The test
then scrolls the list until the reason is in view and checks that all of
it sits inside the list's visible area, below the Search field and above
the Close footer.
2026-11-24 00:09:38 -08:00
ViktorBystrov72 3d53abc13a AutoCorrect: let Backspace keep a lowercase i 2026-11-23 22:35:29 +05:00
ViktorBystrov72 2ee73a0d33 PDF: keep hyperlinks on page references 2026-11-23 21:12:42 +05:00
batistalucasv 49f89569d0 test(ui-egui): restore escape_reverts_a_comment_draft regression test (#1348)
Restores the regression test from #7101 for comment draft cancellation:
- escape_reverts_a_comment_draft (#1348, data-loss): Verifies that pressing Escape in a comment balloon field cancels the uncommitted draft buffer without mutating the original comment text, and asserts that subsequently unfocusing/leaving the field does not trigger delayed writes.
2026-11-22 22:11:50 -03:00
batistalucasv 408dcc0367 test(mini_toolbar): restore test for tiny viewport anchor rect (#7317)
Restores the `a_viewport_narrower_than_the_bar_still_yields_a_rect` test (#7317, tag: keyboard) adapted to the post-#7101 `visible_anchor` implementation in `crates/ui-egui/src/mini_toolbar/tests.rs`.
2026-11-22 20:13:40 -03:00
dotCooCoo 16160b1e4b Language packs test: the reason starts inside its row
In the Add a language picker, a row's bounds stop at the list's visible
edge, while its failure notice can run past that edge. On CI the Catalan
row ended at y 367 and its notice ran from 349 to 376, so the check that
the notice ends inside the row failed. The test now checks that the
notice starts inside the row and lies within the row's width.
2026-11-22 12:59:53 -08:00
dotCooCoo e414882ffe Merge main into fix/language-picker-row-error
# Conflicts:
#	crates/ui-egui/src/language_packs.rs
2026-11-22 07:44:19 -08:00
Josias Eli Rodriguez b4f129911d test(cli): reset the wrote_on_stdout scratch dir between runs (#7070) 2026-11-22 00:13:40 -06:00
Josias Eli Rodriguez 3ecce1f442 cli: keep saving after a closed stdout in run (#7070)
A reader that hung up made the `wrote ...` confirmation fail with
StdoutClosed, and the `?` ended the save loop, so later outputs (a PNG,
which is only written there) were skipped while the command still exited 0.
The confirmation now ignores StdoutClosed and the loop goes on; any other
error still returns.
2026-11-22 00:50:48 +00:00
Mauro MazzieriandClaude Opus 5.5 dbc0c30fe1 Merge main into claude/header-margin-anchor-body-bottom (#5542)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-21 18:52:40 +01:00
Mauro MazzieriandClaude Opus 5.5 caf58cd52a Merge main into fix/missing-sans-font-calibri (#7064)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-21 18:52:40 +01:00
Mauro MazzieriandClaude Opus 5.5 ee3ec16a52 Merge main into fix/small-caps-spaces-and-line-height (#7062, #7063)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-21 18:52:40 +01:00
Mauro MazzieriandClaude Opus 5.5 aaecdd6313 Merge main into fix/picture-line-page-bottom (#7109)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-21 18:52:09 +01:00
Mauro MazzieriandClaude Opus 5.5 5d43bb5414 Merge main into fix/exact-page-margins (#7107)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-21 18:52:08 +01:00
Neil Cawse 509bfce556 Merge remote-tracking branch 'upstream/main' into fix/fonts-fallback-coverage 2026-11-21 17:07:02 +00:00
dotCooCoo 2c6d291c9b Language packs: American spelling in the picker row comment 2026-11-21 07:38:17 -08:00
dotCooCoo d750887f3c Language packs: a refused install's reason shows in its picker row
In Add a language, a row's failure notice (an agent's Install refused
while downloading is off, or a failed install) was added as a second
component under the row, beside the licence line. ListRow puts those
components on one line, so the notice got whatever width the licence
left, and a row with a short licence line, such as Dutch, showed no
notice at all. A row now has one component there: the licence, or a
notice with the failure and the licence.

The new test clicks Install as an agent on the Dutch and Catalan rows
and checks that the reason is inside that row.
2026-11-21 07:24:31 -08:00
Mauro MazzieriandClaude Opus 5.5 63f5623990 Merge main into fix/exact-page-margins (#7107)
The UI port (#7101) deleted crates/ui-egui/src/canvas/margins.rs: the
ruler's margin handles now come from craft-libs (craft::pages::ui), whose
margin_range clamps a drag against the opposite margin as given. The
ruler fix of this branch (an exact, negative top or bottom margin counts
at its size) moves to rulers.rs: page_edges hands the ruler the top and
bottom margins' sizes, so a drag of the opposite edge keeps an inch of
text and layout.margins accepts it, and the ruler shows the edge where
the layout puts the body. margin_params sends only the moved edge, so an
exact margin stays exact unless it is the one dragged.

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-21 09:27:40 +01:00
kiwi4boy 0ee236e6a4 Merge remote-tracking branch 'origin/main' into tight-gap-6316
# Conflicts:
#	crates/layout/src/para/lines.rs
#	docs/layout-parity.md
2026-11-20 19:22:23 -05:00
Neil Cawse b9e2eaf05c Merge remote-tracking branch 'fork/fix/fonts-fallback-coverage' into fix/fonts-fallback-coverage 2026-11-20 21:12:18 +00:00
Neil Cawse 007970517b fonts: check circle fallback coverage, clear caches on rescan, and keep Supplemental Arrows-C text-style 2026-11-20 21:12:18 +00:00
Mauro MazzieriandClaude Opus 5.5 0c461485fb Fonts: a complex-script run is shaped in the face its script font lookup gives (#7064)
A complex-script segment that the run's complex-script face covers kept
no face of its own, so the shaping loop let style() look the font up
again as a run font, through lookup_family, which now draws a missing
font in Calibri or in the core font its name starts with. The text
could then be shaped in a face other than the one lookup_script_family
chose, checked for coverage and reported as the substitute (a missing
w:cs "Courier Foo" came out in Courier New's face). Such a segment now
passes that face as an override, as East Asian text does with its
font's face.

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-20 13:42:52 +01:00
Josias Eli Rodriguez f0933342d4 cli: print the wrote ... confirmations on stdout (#7070)
convert, run --save and zotero --save confirmed a successful write on
stderr, so a script capturing stdout got nothing. The three confirmations
now go through write_stdout, the same locked handle the other results use,
so a closed stdout still ends quietly (#508). Errors and diagnostics stay
on stderr; message text, exit codes and written files are unchanged.
2026-11-20 10:53:38 +00:00
mmazzieriandClaude Opus 5.5 1131c3120d layout: a page's last line of only pictures at multiple spacing fits while the pictures do (#7109)
With multiple spacing above single, a page's last line may let its leading run into the bottom
margin as long as its text fits (`fit_height`: baseline plus `text_desc`). A line holding only
pictures has nothing below them: they end at the bottom of the font's room and the spacing adds
its share below (`Breaker::measure`, `pictures_alone`). `text_desc` still held the font's
descent, so such a line had to fit a descent it does not have, and a picture Word keeps on the
page moved to the next.

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

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

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

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

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

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-20 08:18:45 +01:00
mmazzieriandClaude Opus 5.5 db6a9105de docs: layout parity row for missing fonts named after a core font (#7064)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-19 14:31:06 +01:00
mmazzieriandClaude Opus 5.5 d6a8db16b4 Fonts: a missing font named after a core font is drawn in that font, as in Word (#7064)
Word for Windows 16.0.20625 draws a missing font whose name starts with
Arial or Helv in Arial (Arial MT, ArialFoo, Arial Narrow Foo, Helvetica
Foo), with Times in Times New Roman, with Courier in Courier New and with
Segoe UI in Segoe UI, whatever its font table family class; the font
table alternate still comes first. Other names (Verdana MT, Tahoma Foo,
Georgia Foo, Foo Arial) are drawn in Calibri.

Without this, the Calibri rule of the previous commit drew real documents
set in "Arial MT" in Calibri, where Word draws Arial.

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-19 14:01:18 +01:00
mmazzieriandClaude Opus 5.5 048f21dc77 docs: layout parity for Small Caps spaces and line height (#7062, #7063)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-19 13:39:13 +01:00
mmazzieriandClaude Opus 5.5 7addc314f9 Fonts: a missing font that isn't roman is drawn in Calibri, as in Word (#7064)
A run font that isn't installed, has no font table alternate that can be
drawn and isn't classed roman fell through lookup_family to the generic sans
substitutes (Carlito, Helvetica Neue, Arial...), which on Windows, where
Carlito usually isn't installed, land on Arial. Word for Windows 16.0.20625
draws such a font in Calibri for every family class but roman (swiss,
modern, auto, decorative, script). lookup_family now looks it up as Calibri,
which resolves to Calibri where it is installed and to Carlito or the
generic list elsewhere.

East Asian and complex-script fonts go through lookup_script_family, which
keeps the alternate and roman rules but not Calibri, which has no CJK,
Arabic or Hebrew. Thai, symbol, fallback lists and fonts with substitutes of
their own keep their name as before.

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

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-19 13:21:03 +01:00
jayzed80 859e03246f #6829: keep the space after a kept tail and its rows in balanced columns
The room a continued paragraph's tail needs before the next paragraph starts
counted the next paragraph's space before but not the tail's own space after,
so with a large space after it the next paragraph moved on and the tail stayed
behind. `gap_after` adds the merged gap (or both spaces when the document sums
them), with contextual and list spacing suppression kept.

`kept_tail_end` also picked its new end without settling it, so it could land
in the middle of a row beside a floating object, which `settled_end` keeps
whole. The end now backs up to the row's first line.

Tests: `balanced_columns_keep_a_continued_tail_with_the_space_after_it` and
`balanced_columns_keep_a_continued_tail_row_together`; both fail without the
change.
2026-11-19 08:28:15 +00:00
jayzed80 0a29a6d73a Canvas: keep the keyboard in the frame right after a context menu action (#6715)
A menu item's click takes focus from the page, and the page is drawn before the
menu, so `canvas.focused` (which gates the keys) was only recomputed on the next
pass: a character typed in the frame right after the click reached no widget and
was lost. The spelling, synonym and generic item paths now claim the keyboard in
the same pass, as a click on the chrome already does, and keep `want_focus` for
the later frames.

The test types into the very next pass and checks the character lands.
2026-11-19 07:29:55 +00:00
jayzed80 0c7ea7278c Merge remote-tracking branch 'upstream/main' into fix/keep-next-tail-6829 2026-11-19 07:04:14 +00:00
jayzed80 a29663bd95 Canvas: request a repaint when a context menu action hands focus back (#6715) 2026-11-19 03:59:15 +00:00
jayzed80 a7e02482fe Merge remote-tracking branch 'upstream/main' into fix/context-menu-focus-6715 2026-11-19 03:45:54 +00:00
Hamza a3758cd90c Merge remote-tracking branch 'origin/main' into reproducible-saved-dates
# Conflicts:
#	crates/engine/src/io_ext.rs
2026-11-18 15:32:14 +05:00
Neil Cawse 74345b2e25 fix(fonts): invalidate cached file coverage when a font is replaced in place 2026-11-18 03:47:59 +00:00
Neil Cawse 0759433433 Merge remote-tracking branch 'upstream/main' into fix/fonts-fallback-coverage 2026-11-18 03:44:40 +00:00
jayzed80 8619e257a7 #6829: balanced columns keep a continued paragraph's end with the next paragraph
Keep with next was only checked where a paragraph starts. In columns being balanced, the piece of a paragraph begun in an earlier column that holds its last line now has to leave room for the next paragraph to start; otherwise its last lines (two under widow/orphan control) go over with it, and the balancing pass tries taller columns, as in Word.
2026-11-18 01:12:15 +00:00
jayzed80 c158887d9a #6899: Compare clears a foreign del from an inserted paragraph's mark
A whole paragraph inserted by compare took only the compare's ins on its
mark, but kept a del the revised document's mark already carried (a
pending deletion by another author). On accept, resolve_para took the
deletion branch and removed or joined away the inserted paragraph,
losing the inserted break. mark_block now takes a mark-only step, and
the revised side clears del on every paragraph mark it stamps,
including inside table cells; run-level revisions are left alone.
2026-11-17 23:49:12 +00:00
Matt Van Horn 6e55462d5a Merge upstream main into fix/6629-unchecked-language-host-dict
Resolve the engine test conflict with #6944: keep upstream's zxx comment
and this branch's format.state assertion.
2026-11-17 12:22:32 -08:00
Mauro MazzieriandClaude Opus 5.5 4b30633e03 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:20 +00:00
Neil Cawse fa3eb9f303 Merge remote-tracking branch 'upstream/main' into fix/fonts-fallback-coverage 2026-11-17 13:00:58 +00:00
Martin Ball 6f6bf92576 Merge branch 'main' into fix/context-menu-focus-6715 2026-11-17 13:42:57 +01:00
Martin Ball d6e7695538 Merge branch 'main' into fix/autofit-stale-grid 2026-11-17 13:42:47 +01:00
Martin Ball b66f579e7b Merge branch 'main' into fix/context-menu-focus-6715 2026-11-17 08:26:46 +01:00
Neil Cawse a5f3120d59 Merge remote-tracking branch 'upstream/main' into fix/fonts-fallback-coverage 2026-11-17 03:22:04 +00:00
jayzed80 7df90b72cf Return focus to canvas after context menu actions (#6715) 2026-11-15 02:12:03 +00:00
Neil Cawse fadbfdf0e6 Merge remote-tracking branch 'upstream/main' into fix/fonts-fallback-coverage 2026-11-14 18:04:36 +00:00
Matt Van Horn 117c098553 fix: unchecked-language tests must not depend on a missing French dictionary
Fixes #6629
2026-11-14 05:57:47 -08:00
Neil Cawse 12a29586d0 Merge remote-tracking branch 'upstream/main' into fix/fonts-fallback-coverage 2026-11-13 22:55:33 +00:00
Neil Cawse ace0cc6a10 Merge remote-tracking branch 'upstream/main' into fix/fonts-fallback-coverage 2026-11-13 19:46:00 +00:00
Neil Cawse 832462d0cf Merge remote-tracking branch 'upstream/main' into fix/fonts-fallback-coverage 2026-11-13 19:00:46 +00:00
Fin Warman 925ec333cf Autofit tables take complete point-width rows over a stale grid
When an autofit table's stated width differs from its tblGrid total but
matches complete point-width rows (spans allowed), columns take the cell
widths.
2026-11-12 16:07:16 +00:00
kiwi4boy f94aecace7 Merge remote-tracking branch 'origin/main' into tight-gap-6316 2026-11-11 18:00:18 -05:00
kiwi4boy 366b89341d Layout: a span beside floats takes the minimum of its own two edges (#6316)
A table splitting a span first left its 20pt minimum on the far piece, so a
19pt gap bordered only by a picture was refused in that order alone. Each span
now keeps its left and right edge's minimum separately.
2026-11-11 17:04:09 -05:00
kiwi4boy 0c7f425e91 Layout: text goes beside a floating picture in an 18pt gap, as in Word (#6316)
A line goes beside a floating picture or shape when the gap from the column
edge to its wrap area is at least 18pt (was 20), and beside a tight or through
one at least 9pt before Word 2013 layout; floating tables keep 20pt. Each span
takes the largest minimum of the objects bordering it. WrapArea's table flag
becomes AreaKind (Object, Tight, Table) so tight objects without an outline
are known too.
2026-11-11 16:20:53 -05:00
Neil Cawse 02bcba5f71 Merge remote-tracking branch 'upstream/main' into fix/fonts-fallback-coverage 2026-11-11 18:35:52 +00:00
Mauro MazzieriandClaude Opus 5.5 3b0469da57 Header Margin anchors: the declared-margin retry counts list labels and equation numbers once
Snapshot the counters before the header is laid out and keep the state of the layout that is kept (CodeRabbit review).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JesQG7ckr7g2qSfBwGkTqM
2026-11-11 16:53:50 +00:00
Mauro MazzieriandClaude Opus 5.5 0320a14c0a 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
Neil Cawse 2d986748df test(fonts): use drop guards for temp files and dirs in fontdb tests 2026-11-11 02:17:33 +00:00
Neil Cawse c80709b51e Merge remote-tracking branch 'origin/main' into fix/fonts-fallback-coverage 2026-11-11 02:15:33 +00:00
Neil Cawse 78126b013a test(fonts): remove temporary TTC file before assertions 2026-11-09 22:39:06 +00:00
Neil Cawse d7ec5e2ed2 Merge remote-tracking branch 'origin/main' into fix/fonts-fallback-coverage 2026-11-09 22:38:15 +00:00
Mauro MazzieriandClaude Opus 5.5 72f0577d0c Header Margin anchors: a wrapping picture can't grow the header past the measured body top
body_top_for measures the header with the declared margins; the final layout uses the rendered
body. A tall picture bottom-aligned on the Margin with square wrapping, lifted by a footer taller
than its margin, crossed the header's lines in the final layout only, pushing them below the
picture while the body top stayed where it was measured. If the final placement makes the header
taller than that body top and the measured layout is shorter, the measured one is kept.

Reported by CodeRabbit on #5545.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 15:53:35 +01:00
Mauro MazzieriandClaude Opus 5.5 3cda5d277b Merge fix: the PageFrame main added in floats.rs uses margin_area
main added a PageFrame literal with margin_top, which this branch renames to margin_area.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 15:53:35 +01:00
Mauro Mazzieri 02c2bb66e4 Merge remote-tracking branch 'origin/main' into claude/header-margin-anchor-body-bottom
# Conflicts:
#	docs/layout-parity.md
2026-11-09 15:44:20 +01:00
Neil Cawse d593088a31 refactor(fonts): share compact/MAX_FACES/MAX_RANGES in fallback_data and test sys.tried rescan 2026-11-09 14:21:05 +00:00
Adithya Shankaran 154982988a Merge branch 'main' into fix/automation-roots-exact-names 2026-11-08 23:28:42 +05:30
Neil Cawse 525a6a8f89 refactor(fonts): deduplicate TTC cmap reads, preserve coverage index across rescan, and test fallback skip/rescan 2026-11-08 13:34:26 +00:00
Neil Cawse 6102a64112 refactor(fonts): deduplicate coverage index sync and test >40 MiB TTC coverage 2026-11-08 13:34:26 +00:00
Neil Cawse 477bda7726 fonts: check family cmap coverage before loading fallback fonts and clear caches on rescan 2026-11-08 13:34:26 +00:00
Adithya Shankaran cf6d23c918 Say what the touched tests check
Doc comments only, on the file-access tests that had none.
2026-11-06 16:17:03 +00:00
Adithya Shankaran 80eef0e4ac docs/mcp.md: say how names are compared on Windows now 2026-11-06 12:59:04 +05:30
Adithya Shankaran 5e097aa288 Merge remote-tracking branch 'upstream/main' into fix/automation-roots-exact-names 2026-11-06 10:00:43 +05:30
Adithya Shankaran 417cc45a1c Credit my name in the About window 2026-11-06 00:14:48 +05:30
Adithya Shankaran ff7d032da6 Automation roots: compare names exactly and refuse COM¹ to LPT³
On Windows a folder can be set to tell case apart, and then IN beside the root in passed as inside
it, because names were compared with to_lowercase. Both paths have the spelling the file system
gives them by then, so another spelling of the root still matches with an exact compare. A missing
name keeps the spelling it was given, but it can only match a root that exists, and resolve has
already found that one in its real spelling.

is_device_name also missed COM¹, COM², COM³ and LPT¹, LPT², LPT³, which Windows reserves too.
It also cut the name only at a period, so COM1: and NUL:x were not seen as device names.
2026-11-06 00:14:47 +05:30
Hamza 531a0d1f1d Merge remote-tracking branch 'origin/main' into reproducible-saved-dates
# Conflicts:
#	apps/wordcraft-cli/src/main.rs
#	crates/engine/src/cmd.rs
#	crates/engine/src/print.rs
2026-11-05 15:09:39 +05:00
Harrison Booth 0aaef7a5bd Merge origin/main into metric font work 2026-11-05 03:23:57 -06:00
Harrison Booth ae0f30fa23 Document emphasis round-trip test 2026-11-04 20:04:50 -06:00
Harrison Booth 55da823f01 Make emphasis dot test value explicit 2026-11-04 19:47:14 -06:00
Harrison Booth f7eadd7781 Resolve duplicate emphasis in DOCX fixture 2026-11-04 19:30:43 -06:00
Harrison Booth ecab532500 Merge latest main into East Asian emphasis marks 2026-11-04 19:24:24 -06:00
Harrison Booth be5fe3d36f Merge remote-tracking branch 'origin/main' into upkeep-4619 2026-11-04 19:21:43 -06:00
Harrison Booth f053740960 Format metric font fallback iterator 2026-11-04 17:24:52 -06:00
Harrison Booth 7581392111 merge latest origin main 2026-11-04 17:21:15 -06:00
Dhruv 9cdc60b2c1 Home › Numbering: add the a. b. c. preset; picking another preset changes a numbered list instead of turning it off (#4281) 2026-11-04 10:30:53 -06:00
Dhruv 2973a2f4f3 A list item that changes level takes the new level's indents and drops a direct indent (#4287) 2026-11-04 10:30:11 -06:00
Dhruv 8e90f8f336 Replace All replaces in every story: headers, footers, footnotes, endnotes and text boxes (#3300) 2026-11-04 10:29:46 -06:00
Harrison Booth 1121b3146c Merge origin/main into DOCX emphasis branch 2026-11-04 07:59:32 -06:00
Harrison Booth 04e8e61e82 Merge latest main into metric font reporting 2026-11-04 07:56:35 -06:00
Harrison Booth 36a64b39c4 Merge origin/main into wc-docx-emphasis 2026-11-04 06:38:59 -06:00
Harrison Booth 64e9f2d24f DOCX: retain emphasis test assertions through save cycles 2026-11-04 06:38:52 -06:00
Harrison Booth bf95e83642 Merge remote-tracking branch 'origin/main' into wc-metric-fonts 2026-11-04 05:34:28 -06:00
Harrison Booth bec88fd149 Fonts: cover Calibri fallback without Carlito 2026-11-04 05:34:28 -06:00
Harrison Booth 1b34471bc8 Fonts: test missing core font fallbacks 2026-11-04 05:26:49 -06:00
Harrison Booth 44badab540 Merge remote-tracking branch 'origin/main' into wc-metric-fonts 2026-11-03 22:04:37 -06:00
Harrison Booth 52773d2f7b Merge remote-tracking branch 'origin/main' into wc-harfrust 2026-11-03 22:04:02 -06:00
Harrison Booth e209b4f6fd Format metric font resolution helper 2026-11-03 18:44:59 -06:00
Harrison Booth 68de4560b5 Merge origin/main and fix core font notices 2026-11-03 18:23:49 -06:00
Harrison Booth 3ecc43c062 Merge remote-tracking branch 'origin/main' into wc-harfrust 2026-11-03 17:58:55 -06:00
Harrison Booth 2be939832b Document East Asian emphasis preservation 2026-11-03 17:20:16 -06:00
Hamza 2525eaee12 SOURCE_DATE_EPOCH: warn when it is set and unusable, and show it dates the file, not the edits in it 2026-11-03 17:39:39 +05:00
Mauro MazzieriandClaude Opus 5.5 a11e4daae6 Header Margin anchors: centre in the rendered body, bottom included (#2485 follow-up)
#2485 made a header drawing anchored to the Margin measure from the rendered body top when the
header reaches past the top margin, but its area still ran down to the declared bottom margin.
Word measures between the rendered body's top and bottom: with a footer that reaches past the
bottom margin, a picture centred (or bottom-aligned) on the margins in the header sits higher.

A full-page letterhead picture centred on the margins of a page with near-zero margins (the
usual "picture watermark" letterhead) was drawn 24 pt low in 0.15.0, its footer band cut at the
page edge; 0.14.0 and Word draw it at the top.

PageFrame::margin_top becomes margin_area (top, bottom) and both Margin paths (floats and
floating header tables) share margin_y, keeping the 18 pt floor of text_height.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 10:36:32 +01:00
Hamza ed14477f19 A creation date the PDF writer cannot read is pinned too
`pdf_document` stood in for the date only when `core.created` was empty, but the
.docx reader takes that property as it finds it, so a file can arrive holding
something like `not-a-date`. `metadata` cannot put that in a PDF and falls back
to the clock, so two exports of one document differed although SOURCE_DATE_EPOCH
was set -- the one thing it is there to stop (noted in review).

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

Also a flake in this test harness, which the added iterations made likely rather
than introduced: the temporary directory was named from the pid and `as_nanos`,
and `as_nanos` carries microsecond granularity on macOS, so two of these tests
starting in the same microsecond took the same directory and overwrote each
other's input. It takes a sequence number as well now, and `create_dir` rather
than `create_dir_all`, so a name that does repeat fails there instead of quietly
sharing. Eight consecutive runs of the file: 3 failures before, 0 after.
2026-11-02 15:51:32 +05:00
Harrison Booth 53e520e805 DOCX: merge main into East Asian emphasis marks 2026-10-30 13:46:38 -05:00
Harrison Booth 01a6084673 DOCX: preserve East Asian emphasis marks 2026-10-29 08:00:54 -05:00
Harrison Booth a848e90b3a DOCX: preserve run grid and web-hidden properties 2026-10-29 07:34:21 -05:00
Harrison Booth b1c6aafc33 Merge origin/main into wc-metric-fonts 2026-10-28 15:49:25 -05:00
Harrison Booth 45299ba839 wc-upkeep-6: report resolved font substitutions 2026-10-28 15:04:32 -05:00
Hamza 77af00b4e5 Saving and exporting: SOURCE_DATE_EPOCH stands in for the clock
A saved document recorded the second it was saved in, and a PDF export
recorded the second it was exported in, so saving or exporting one document
twice gave different bytes although the content matched.

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

Rebased onto main, 785 commits on: engine's cmd/mod.rs is cmd.rs now, and
`stamp_save` moved to session/history.rs, so `saved_iso` is applied there.
Upstream has since added a `numeral` option to the PDF export, which is kept
alongside this PR's change to the document the exporter is given.
2026-10-28 20:29:14 +05:00
Harrison Booth 78ea592cf4 Fonts: a metric twin counts only when resolution draws it; prefer Arimo, Tinos and Cousine; docs 2026-10-27 19:14:00 -05:00
Harrison Booth c1a20368dc Merge origin/main into wc-metric-fonts 2026-10-27 19:13:00 -05:00
Harrison Booth 999f0c0973 Fonts: a run the shaper could not finish falls back to the cmap, run by run 2026-10-27 19:09:43 -05:00
Harrison Booth 6117f95e1c Merge origin/main into wc-harfrust 2026-10-27 19:07:31 -05:00
Harrison Booth 32d4d32292 Fonts: say which Word core font drew in place of a missing one, and when no metric twin is installed 2026-10-27 15:07:56 -05:00
Harrison Booth 6c8a6bd6f7 Merge remote-tracking branch 'origin/main' into wc-merge-4582
# Conflicts:
#	crates/fonts/src/lib.rs
2026-10-27 14:27:11 -05:00
Harrison Booth fe2b22792d deps: harfrust 0.15 (Font, ShaperFont and Buffer replace FontRef, ShaperData and UnicodeBuffer) 2026-10-27 08:44:30 -05:00
Divyanshu Gupta 59e818424c fix(doc): handle start 0 list counters and preserve literal %0 placeholders 2026-10-16 07:31:55 +05:30
Divyanshu Gupta 02e7bbc640 fix(formats): support UTF-32 BOM decoding, preserve vertical tabs in text import, and handle colspan in table export 2026-10-16 05:28:22 +05:30
ahutsunshin e3db9896fb security: use explicit u64 literal for 2 GB file size limit
Change '2 << 30' to '2u64 << 30'. While Rust's type inference handles the
comparison with meta.len() (u64), making the type explicit documents intent
and guards against potential debug-mode overflow traps if the constant is
ever increased past the i32 boundary.
2026-10-14 12:34:49 +08:00
321 changed files with 25673 additions and 2881 deletions
+3 -1
View File
@@ -21,4 +21,6 @@ jobs:
with:
# Same craft-fonts commit as ci.yml: the UI glyph tests need its CJK and Arabic fonts.
fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
secrets: inherit
secrets:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
SONAR_CLOUD_PAT: ${{ secrets.SONAR_CLOUD_PAT }}
+1 -1
View File
@@ -73,7 +73,7 @@ WordCraft is a Rust word processor targeting Microsoft Word parity, for macOS, W
- `unsafe`: none; the workspace forbids it. Typing behaviour is pinned by `crates/engine/src/tests/typing.rs` and described in `docs/typing-parity.md`.
- Attribution: `ATTRIBUTION.md`, a row per asset file, checked by `cargo xtask assets`. Icons are our own SVG set in `crates/ui-egui/icons/` (draw new icons there); sample content is in `crates/engine/src/sample.rs` and `cmd/design.rs`.
- Fonts and language data come from other repositories as optional build inputs: craft-fonts through `CRAFT_FONTS_DIR`, and craft-i18n's `language-data/` through `CRAFT_I18N_DIR` (pinned by `craft-i18n.rev`; CI checks it out). Without craft-i18n the app builds with fallback spelling and no pattern hyphenation, so proofing tests need it. Proprietary font requests use installed fonts or the open substitutes in `crates/fonts/src/word.rs`. Layout tests use the fixed fonts in `assets/fonts/` ([docs/testing.md](docs/testing.md)).
- Run: `cargo run --release -p wordcraft -- --sample --control 7981` starts the app with a sample document and the control channel. It takes JSON lines on `127.0.0.1:7981`: authenticate once per connection with the token from `~/.config/wordcraft/control-key.local-7981` (macOS: `~/Library/Application Support/WordCraft/`), `{"id":1,"method":"auth","params":{"token":"…"}}`, then send requests without a token; methods are in `crates/ui-egui/src/control.rs`, docs in `docs/control-protocol.md` (Token). Headless screenshots: `cargo run --release -p wordcraft-ui-egui --example ui_shot -- script.jsonl`. CLI: `wordcraft-cli convert|run|commands|parity`. MCP: `wordcraft-cli mcp --automation-read-root DIR --automation-write-root DIR` (both required; `--connect` is refused until the app confines its control channel, #3695), see `docs/mcp.md`.
- Run: `cargo run --release -p wordcraft -- --sample --control 7981` starts the app with a sample document and the control channel. It takes JSON lines on `127.0.0.1:7981`: authenticate once per connection with the token from `~/.config/wordcraft/control-key.local-7981` (macOS: `~/Library/Application Support/WordCraft/`), `{"id":1,"method":"auth","params":{"token":"…"}}`, then send requests without a token; methods are in `crates/ui-egui/src/control.rs`, docs in `docs/control-protocol.md` (Token). Headless screenshots: `cargo run --release -p wordcraft-ui-egui --example ui_shot -- script.jsonl`. CLI: `wordcraft-cli convert|run|commands|parity`. MCP: plain `wordcraft-cli mcp` reaches the open window while ArtCraft Launcher › Settings › AI agents is on (`crates/ui-egui/src/agents.rs`, `crates/mcp/src/live.rs`); `--headless`, or the switch off, needs `--automation-read-root DIR --automation-write-root DIR`; see `docs/mcp.md`.
- Headless column ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): `cargo xtask parity` marks a catalog feature `headless: yes` only when its command is in the engine registry that `wordcraft-cli` and the MCP server load (never a `ui.*` id). A missing feature takes its `no`/`partial` value and `reach:` (`window`, `os` or `engine-gap`) from `HEADLESS` in `crates/engine/src/catalog.rs`, or reads `unknown`. When a command lands, delete its mark; `headless_marks_are_current` fails on a stale one.
- Notes and progress: `plan/` is an optional gitignored notebook. Committed: `ROADMAP.md` (progress log), `docs/gaps.md`, `docs/roadmap.md`, `docs/target-app-parity.md`, `docs/architecture.md` and the parity checklists.
- Contributor credits: `docs/contributors.md`.
Generated
+258 -116
View File
File diff suppressed because it is too large Load Diff
+41 -41
View File
@@ -13,7 +13,7 @@ run_slots = 3
test_threads = 4
[workspace.package]
version = "0.20.0"
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 = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920", version = "=0.1.0" }
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920", version = "=0.1.0" }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920", version = "=0.1.0" }
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920", 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 = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0", default-features = false }
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35" }
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920", version = "=0.1.0" }
craft = { git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920", version = "=0.1.0", default-features = false }
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920", version = "=0.1.0" }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920", version = "=0.1.0" }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920", version = "=0.1.0" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920" }
# foundation
kurbo = { version = "0.13", features = ["serde"] }
@@ -75,7 +75,7 @@ regex-automata = { version = "0.4", default-features = false, features = ["std",
# text / rendering / formats
skrifa = "0.47"
harfrust = "0.13"
harfrust = "0.15"
# WOFF / WOFF2 web fonts added by the user (#582): pure Rust (MIT); its brotli and zlib decoders
# (brotli-decompressor, flate2) are already in the tree.
wuff = "0.2.9"
@@ -85,28 +85,28 @@ wuff = "0.2.9"
brotli-decompressor = "5"
vello_cpu = "0.2"
image = { version = "0.25", default-features = false }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0", default-features = false, features = ["write"] }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920", version = "=0.1.0" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920", version = "=0.1.0" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920", version = "=0.1.0", default-features = false, features = ["write"] }
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0", features = ["doc"] }
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0", features = ["text"] }
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0", features = ["flow"] }
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0", features = ["detect"] }
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35", version = "=0.1.0" }
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920", version = "=0.1.0" }
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920", version = "=0.1.0" }
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920", version = "=0.1.0" }
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920", version = "=0.1.0", features = ["doc"] }
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920", version = "=0.1.0" }
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920", version = "=0.1.0" }
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920", version = "=0.1.0", features = ["text"] }
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920", version = "=0.1.0" }
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920", version = "=0.1.0", features = ["flow"] }
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920", version = "=0.1.0" }
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920", version = "=0.1.0" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920", version = "=0.1.0", features = ["detect"] }
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920", version = "=0.1.0" }
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920", version = "=0.1.0" }
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920", version = "=0.1.0" }
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920", version = "=0.1.0" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920", version = "=0.1.0" }
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920", version = "=0.1.0" }
# zlib streams (compressed metafile pictures in `.doc` drawings); already in the lock as a dependency of other crates.
miniz_oxide = "0.9"
cfb = "0.15"
@@ -174,14 +174,14 @@ debug = 0
# The framework's patches, which Cargo does not carry over to dependents: its vendored crates from craft-libs,
# and the egui and winit forks it builds with.
[patch.crates-io]
krilla = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35" }
hayro = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "5299d8d97dc04648dff735d1bd6f60bd18f10b35" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920" }
hayro = { git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "0a15c60d5aee340c9430ced36af7c23fba9d1920" }
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" }
+9 -2
View File
@@ -205,13 +205,17 @@ Web: `cd apps/wordcraft-web && trunk serve`, then open <http://127.0.0.1:8771/?s
WordCraft was designed to be driven by people *and* by AI agents.
With ArtCraft Launcher › Settings › AI agents on, AI apps reach the open WordCraft window through
the launcher's one `ArtCraft` entry: tool calls act in the window, and files go to the agent folder
(`Documents/ArtCraft/Agents/WordCraft`, or the folders in File › Options › Agents). Without the
launcher:
```sh
# headless documents; the agent reads only inside the first folder and writes only inside the second
claude mcp add wordcraft -- wordcraft-cli mcp --automation-read-root DIR --automation-write-root DIR
```
Both roots are required. Bridging an agent to the running app (`mcp --connect`) is refused until
the app confines its control channel to the same roots (#3695).
A headless server needs both roots.
Tools include `list_commands`, `execute`, `batch`, `type_text`, `select_text`, `inspect_document`,
`render_page` and `save_document`. Agents
@@ -386,9 +390,12 @@ emerge --ask app-office/wordcraft-bin
### FreeBSD
Prebuilt FreeBSD release archives target FreeBSD 15.1 or newer; FreeBSD 14.x is not supported by these builds.
| Build | File |
|---|---|
| x86_64 | `wordcraft-<ver>-freebsd-x86_64.tar.gz` |
| aarch64 | `wordcraft-<ver>-freebsd-aarch64.tar.gz` |
### Web (WebAssembly)
+9 -1
View File
File diff suppressed because one or more lines are too long
+209 -50
View File
@@ -54,16 +54,25 @@ USAGE:
wordcraft-cli commands [--json] list every command
wordcraft-cli parity [--markdown] feature-catalog parity
wordcraft-cli validate <file> [--json] structural integrity check (exit 0 pass, 1 fail, 2 incomplete, 3 usage/IO)
wordcraft-cli mcp --automation-read-root DIR --automation-write-root DIR [--author NAME]
MCP server on stdio, with a headless session.
Both roots are required: the agent's commands read
files (open, insert text or picture, mail-merge data,
templates…) only inside the read root and write them
(save, export, merge output…) only inside the write
root, links followed; the same folder may be both.
--connect HOST:PORT (bridge to the running app) is
refused until the app confines its control channel
(#3695, #5819).
wordcraft-cli mcp [--automation-read-root DIR --automation-write-root DIR] [--headless]
[--when-closed launch|headless|error] [--author NAME]
MCP server on stdio. While AI agents are on in
ArtCraft Launcher › Settings › AI agents, each tool
call goes to the open WordCraft window, working in
its agent folder (File › Options › Agents); while
WordCraft is closed, --when-closed or that page's
choice decides: open it, work without a window, or
ask to open it. Otherwise, and with --headless, a
headless session, which needs both roots: the
agent's commands read files (open, insert text or
picture, mail-merge data, templates…) only inside
the read root and write them (save, export, merge
output…) only inside the write root, links followed;
the same folder may be both. Given with AI agents
on, the roots replace the agent folder for headless
work. --author names the author of a headless
session's tracked changes and comments.
--connect HOST:PORT is deprecated and ignored.
wordcraft-cli zotero <command> <file> [--cmd 'id={json}' …] [--save OUT] [--trace] [--port P]
run a Zotero command on a document (Zotero must be
running): addEditCitation, addEditBibliography,
@@ -261,6 +270,17 @@ fn find_option_arg<'a>(args: &'a [String], name: &str) -> OptionArg<'a> {
}
}
/// `mcp --author NAME`: absent is the default author; a flag without a name, or given twice, is a
/// usage error, never an unnamed session or the next option taken as the name.
fn mcp_author(args: &[String]) -> Result<Option<String>, String> {
match find_option_arg(args, "--author") {
OptionArg::Absent => Ok(None),
OptionArg::Duplicate => Err("mcp: duplicate --author option".into()),
OptionArg::MissingValue => Err("mcp: --author requires a name".into()),
OptionArg::Value(name) => Ok(Some(name.to_string())),
}
}
fn parse_page_arg(command: &str, args: &[String]) -> Result<Option<u64>, String> {
match find_option_arg(args, "--page") {
OptionArg::Absent => Ok(None),
@@ -376,13 +396,86 @@ const VALIDATE_OPTIONS: &[OptionSpec] = &[OptionSpec { name: "--json", takes_val
const MCP_NEEDS_ROOTS: &str = "mcp: give both --automation-read-root DIR and --automation-write-root DIR: an agent's \
commands may read only inside the read root and write only inside the write root (the same folder may be both)";
/// Why `mcp --connect` is refused: the running app would not confine the agent's file access.
// lean: refused outright; allow it once the app confines its control channel and reports both roots.
const MCP_CONNECT_REFUSED: &str = "mcp: --connect is refused for now: the desktop app does not confine its control \
channel to automation roots yet (storytold/wordcraft#3695, #5819). Use the headless server: wordcraft-cli mcp \
--automation-read-root DIR --automation-write-root DIR";
/// Why `mcp` won't start while the suite's AI-MCP flag is on but the launcher's switch keeps agents
/// out of the window: without roots it would have no folders to work in.
const MCP_NEEDS_ROOTS_OR_AGENTS: &str = "mcp: give both --automation-read-root DIR and --automation-write-root DIR, or \
turn on AI agents in ArtCraft Launcher › Settings › AI agents to work in WordCraft's open window and its agent folder";
const MCP_OPTIONS: &[OptionSpec] = &[OptionSpec { name: "--connect", takes_value: true }, OptionSpec { name: "--author", takes_value: true }];
/// `--connect HOST:PORT`, from before plain `mcp` found the window by itself: kept for one release,
/// ignored with this note on stderr, then removed.
const MCP_CONNECT_DEPRECATED: &str = "wordcraft-cli: --connect is deprecated and will be removed in the next release: \
plain `wordcraft-cli mcp` finds the open WordCraft window by itself while AI agents are on in ArtCraft Launcher › \
Settings › AI agents. The address given is not used.";
const MCP_OPTIONS: &[OptionSpec] = &[
OptionSpec { name: "--headless", takes_value: false },
OptionSpec { name: "--when-closed", takes_value: true },
OptionSpec { name: "--author", takes_value: true },
];
/// Takes the deprecated `--connect` out of `args`, with its value (written apart, unless it is
/// another option, or as `--connect=…`): whether it was there.
fn take_connect(args: &mut Vec<String>) -> bool {
let mut found = false;
let mut i = 0;
while let Some(arg) = args.get(i) {
if arg == "--connect" {
found = true;
let with_value = args.get(i + 1).is_some_and(|v| !v.starts_with("--"));
args.drain(i..if with_value { i + 2 } else { i + 1 });
} else if arg.starts_with("--connect=") {
found = true;
args.remove(i);
} else {
i += 1;
}
}
found
}
/// The suite's AI-MCP flag and whether the ArtCraft Launcher's switch lets agents use WordCraft.
#[cfg(not(test))]
fn agents_state() -> (bool, bool) {
let flag = wordcraft_mcp::live::mcp_flag();
(flag, flag && wordcraft_mcp::live::agents_allowed_now())
}
/// Unit tests run `mcp` as without the suite's flag, whatever this machine's flags say; the plan
/// itself is tested for every combination (`mcp_plan`), and the binary's tests set the flag.
#[cfg(test)]
fn agents_state() -> (bool, bool) {
(false, false)
}
/// How `mcp` runs.
#[derive(Debug)]
enum McpPlan {
/// A headless session confined to both roots.
Headless(std::sync::Arc<wordcraft_engine::file_access::AutomationRoots>),
/// The open window while agents may use it, otherwise a headless session in the given roots
/// or the app's agent folder ([`wordcraft_mcp::Live`]).
Live(Option<std::sync::Arc<wordcraft_engine::file_access::AutomationRoots>>),
}
/// `mcp`'s plan. With `--headless`, or without the suite's AI-MCP flag (`flag`), a headless session
/// that needs both roots (shared rule 18). With the flag, the live client when the launcher's
/// switch lets agents in (`switch`) or both roots are given, so nothing it does is unconfined;
/// otherwise a refusal.
fn mcp_plan(
roots: Option<std::sync::Arc<wordcraft_engine::file_access::AutomationRoots>>,
headless: bool,
flag: bool,
switch: bool,
) -> Result<McpPlan, &'static str> {
let both = roots.clone().filter(|r| r.read_root().is_some() && r.write_root().is_some());
if headless || !flag {
return both.map(McpPlan::Headless).ok_or(MCP_NEEDS_ROOTS);
}
if switch || both.is_some() {
return Ok(McpPlan::Live(roots));
}
Err(MCP_NEEDS_ROOTS_OR_AGENTS)
}
const ZOTERO_OPTIONS: &[OptionSpec] = &[
OptionSpec { name: "--cmd", takes_value: true },
OptionSpec { name: "--save", takes_value: true },
@@ -517,8 +610,10 @@ fn run_convert(rest: &[String], open: impl Fn(&str, Option<&str>) -> Result<Sess
let markup = rest.iter().any(|a| a == "--markup");
let strict = rest.iter().any(|a| a == "--strict");
// Before the input is opened: a wrong output type is a usage error, not a file error.
let to_png = o.to_ascii_lowercase().ends_with(".png");
if strict && !(to_png || o.to_ascii_lowercase().ends_with(".pdf")) {
let lower_output = o.to_ascii_lowercase();
let to_png = lower_output.ends_with(".png");
let rendered = to_png || lower_output.ends_with(".pdf");
if strict && !rendered {
return Err("convert: --strict needs a .pdf or .png output".into());
}
let password = password_from(rest)?;
@@ -538,8 +633,12 @@ fn run_convert(rest: &[String], open: impl Fn(&str, Option<&str>) -> Result<Sess
if let Err(e) = r {
return Err(if strict { refusal(&mut s, e, markup, to_png.then_some(1)) } else { engine_error(e) });
}
eprintln!("wrote {o}");
Ok(())
// A refusal already returned its report. Word, text and other non-rendered copies need no layout.
if rendered {
report_missing_metric_fonts(&s, markup, to_png);
}
// The confirmation is a result, so it goes to stdout with the others (#7070).
write_stdout(|w| writeln!(w, "wrote {o}"))
}
fn load_run_script(rest: &[String], script_path: Option<&Path>) -> Result<Option<script::Script>, Failure> {
@@ -563,6 +662,28 @@ fn run_source_paths(rest: &[String], script: Option<&script::Script>) -> (Option
(from_file, from_template)
}
fn report_missing_metric_fonts(s: &Session, markup: bool, to_png: bool) {
for (word, used) in wordcraft_engine::cmd::font::output_metric_font_notices(s, markup, to_png) {
let used = escape_peer(&used);
use std::io::Write as _;
let _ = writeln!(
std::io::stderr().lock(),
"note: {word} is drawn in {used}, which measures differently, so lines and pages may not match Word's; uncovered characters may use glyph fallback"
);
}
}
/// Show a successful command's result, or its warning when results aren't printed.
fn report_run_result(id: &str, result: &Value, print: bool) -> Result<(), Failure> {
if print {
return write_stdout(|o| writeln!(o, "{id}: {result}"));
}
if let Some(warning) = result.get("warning").and_then(Value::as_str) {
let _ = writeln!(std::io::stderr().lock(), "wordcraft-cli: warning: {}", escape_text(warning, false));
}
Ok(())
}
/// Run the subcommand named by `args` (the command line after the program name). Files named
/// there are opened by their real names, which may not be valid Unicode.
fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
@@ -666,9 +787,7 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
let print = rest.iter().any(|a| a == "--print");
for (n, (id, params)) in script.iter().flat_map(|c| c.commands.iter()).enumerate() {
let r = s.run(id, params).map_err(|e| engine_error(format!("command {} ({id}): {e}", n + 1)))?;
if print {
write_stdout(|o| writeln!(o, "{id}: {r}"))?;
}
report_run_result(id, &r, print)?;
}
let mut i = 0;
while i < rest.len() {
@@ -681,9 +800,7 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
None => (spec.clone(), json!({})),
};
let r = s.run(&id, &params).map_err(|e| engine_error(format!("{id}: {e}")))?;
if print {
write_stdout(|o| writeln!(o, "{id}: {r}"))?;
}
report_run_result(&id, &r, print)?;
i += 2;
} else {
i += 1;
@@ -717,7 +834,11 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
s.run("file.save", &json!({"path": out}))
};
r.map_err(engine_error)?;
eprintln!("wrote {out}");
// A reader that hung up only loses the confirmation; the remaining saves still run.
match write_stdout(|w| writeln!(w, "wrote {out}")) {
Ok(()) | Err(Failure::StdoutClosed) => {}
Err(e) => return Err(e),
}
}
Ok(())
}
@@ -747,28 +868,7 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
}
}
"validate" => run_validate(file.as_deref(), &rest),
"mcp" => {
let (roots, rest) = automation_roots("mcp", &rest)?;
// Refused with or without a value, before the option check, so `--connect=…` gets this refusal rather than
// "unknown option": a bare trailing `--connect` must not slip past either.
if rest.iter().any(|a| a == "--connect" || a.starts_with("--connect=")) {
return Err(MCP_CONNECT_REFUSED.into());
}
validate_options("mcp", &rest, MCP_OPTIONS)?;
// Shared rule 18 (#7124): an agent entry point never runs unconfined.
let Some(roots) = roots.filter(|r| r.read_root().is_some() && r.write_root().is_some()) else {
return Err(MCP_NEEDS_ROOTS.into());
};
// Every thread of this process, not only the server's: nothing reaches past the roots.
wordcraft_engine::file_access::confine_process(roots.clone());
let show = |root: Option<&std::path::Path>| root.map_or_else(|| "none".to_string(), |r| r.display().to_string());
eprintln!("wordcraft-cli: files confined: read root {}, write root {}", show(roots.read_root()), show(roots.write_root()));
let backend: Box<dyn wordcraft_mcp::Backend> = Box::new(headless_mcp(roots, arg_value(&rest, "--author").as_deref())?);
let mut server = wordcraft_mcp::Server::new(backend);
let stdin = std::io::stdin();
// A client that closes our stdout has hung up: `serve` returns BrokenPipe and we end cleanly.
Ok(server.serve(stdin.lock(), std::io::stdout())?)
}
"mcp" => run_mcp(&rest),
"zotero" => {
validate_options("zotero", &rest, ZOTERO_OPTIONS)?;
let paths = positionals(&rest, ZOTERO_OPTIONS);
@@ -808,7 +908,7 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
eprintln!("{} calls, {}", out.calls, if out.completed { "completed" } else { "ended without completing (cancelled?)" });
if let Some(o) = arg_value(&rest, "--save") {
s.run("file.save", &json!({"path": o})).map_err(engine_error)?;
eprintln!("wrote {o}");
write_stdout(|w| writeln!(w, "wrote {o}"))?;
}
Ok(())
}
@@ -818,6 +918,60 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
}
}
/// `wordcraft-cli mcp`: serves MCP on stdin and stdout, headless or through the open window.
fn run_mcp(rest: &[String]) -> Result<(), Failure> {
let (roots, mut rest) = automation_roots("mcp", rest)?;
// Taken out before the option check, with or without a value, so it never reads as unknown.
if take_connect(&mut rest) {
eprintln!("{MCP_CONNECT_DEPRECATED}");
}
validate_options("mcp", &rest, MCP_OPTIONS)?;
let when_closed = match (rest.iter().any(|a| a == "--when-closed"), arg_value(&rest, "--when-closed")) {
(false, _) => None,
(true, value) => {
Some(value.as_deref().and_then(wordcraft_mcp::live::WhenAppClosed::parse).ok_or("mcp: --when-closed takes launch, headless or error")?)
}
};
let author = mcp_author(&rest)?;
let (flag, switch) = agents_state();
let show = |root: Option<&std::path::Path>| root.map_or_else(|| "none".to_string(), |r| r.display().to_string());
let backend: Box<dyn wordcraft_mcp::Backend> = match mcp_plan(roots, rest.iter().any(|a| a == "--headless"), flag, switch)? {
McpPlan::Headless(roots) => {
// Shared rule 18 (#7124): an agent entry point never runs unconfined. Every thread of this process,
// not only the server's: nothing reaches past the roots.
wordcraft_engine::file_access::confine_process(roots.clone());
eprintln!("wordcraft-cli: files confined: read root {}, write root {}", show(roots.read_root()), show(roots.write_root()));
Box::new(headless_mcp(roots, author.as_deref())?)
}
McpPlan::Live(roots) => {
let mut config = wordcraft_mcp::LiveConfig::installed()
.ok_or("mcp: can't find WordCraft's settings folder (no home folder; set WORDCRAFT_PROFILE_DIR)")?;
if let Some(roots) = &roots {
config.read_root = roots.read_root().map(std::path::Path::to_path_buf);
config.write_root = roots.write_root().map(std::path::Path::to_path_buf);
// Both roots given: every headless session works in them, so the whole process is confined to
// them. Calls to the window run in the app, inside its agent folders.
if config.read_root.is_some() && config.write_root.is_some() {
wordcraft_engine::file_access::confine_process(roots.clone());
}
}
config.when_closed = when_closed;
config.author = author;
config.launch = std::env::current_exe().ok().and_then(|exe| wordcraft_mcp::live::launcher(&exe));
eprintln!(
"wordcraft-cli: tool calls go to the open WordCraft window while AI agents are on in ArtCraft Launcher, otherwise to a headless session (read root {}, write root {}; none: WordCraft's agent folder)",
show(config.read_root.as_deref()),
show(config.write_root.as_deref())
);
Box::new(wordcraft_mcp::Live::new(config))
}
};
let mut server = wordcraft_mcp::Server::new(backend);
let stdin = std::io::stdin();
// A client that closes our stdout has hung up: `serve` returns BrokenPipe and we end cleanly.
Ok(server.serve(stdin.lock(), std::io::stdout())?)
}
/// At most 400 characters of `s`, for traces.
fn clip(s: &str) -> String {
match s.char_indices().nth(400) {
@@ -1063,6 +1217,11 @@ fn main() -> ExitCode {
eprintln!("wordcraft-cli: --launch-profile and --profile-root are the desktop app's Nightly bootstrap, not a CLI option");
return ExitCode::from(2);
}
// The engine logs this, but the command line installs no logger, and it is where a
// reproducible build runs.
if let Some(problem) = wordcraft_engine::cmd::source_date_epoch_problem() {
eprintln!("wordcraft-cli: warning: {problem}");
}
// Language packs installed in the suite's font store are used; `proof.installPack` installs
// only while the person has turned downloading on in the app.
wordcraft_engine::packs::use_font_store(false);
+118 -21
View File
@@ -38,7 +38,7 @@ fn validators_accept_only_the_documented_options() {
assert!(validate_options("run", &args(&["--cmd", "text.insert={}", "--cmd", "edit.undo", "--print"]), RUN_OPTIONS).is_ok());
assert!(validate_options("commands", &args(&["--json"]), COMMANDS_OPTIONS).is_ok());
assert!(validate_options("parity", &args(&["--markdown"]), PARITY_OPTIONS).is_ok());
assert!(validate_options("mcp", &args(&["--connect", "127.0.0.1:9000"]), MCP_OPTIONS).is_ok());
assert!(validate_options("mcp", &args(&["--headless", "--when-closed", "launch"]), MCP_OPTIONS).is_ok());
assert!(validate_options("render", &args(&["in.docx", "out.png", "--page"]), RENDER_OPTIONS).is_ok());
assert!(
validate_options(
@@ -326,18 +326,32 @@ fn every_agent_entry_point_refuses_to_start_without_both_roots() {
}
}
/// The desktop app doesn't confine its control channel to roots yet (#3695, #5819), so the bridge
/// to it is refused, with roots or without, before anything connects.
/// `mcp`'s plan never runs anything unconfined (shared rule 18): headless needs both roots, and
/// with the suite's AI-MCP flag the live client runs without them only while the launcher's switch
/// lets agents into the window, which confines them to its agent folder.
#[test]
fn mcp_connect_is_refused_until_the_app_confines_its_control_channel() {
let dir = std::env::temp_dir().to_string_lossy().into_owned();
for line in [
args(&["mcp", "--connect", "127.0.0.1:9"]),
args(&["mcp", "--connect", "127.0.0.1:9", "--author", "Claude"]),
args(&["mcp", "--connect", "127.0.0.1:9", "--automation-read-root", &dir, "--automation-write-root", &dir]),
] {
let e = run(&line).unwrap_err().to_string();
assert!(e.contains("--connect") && e.contains("#3695") && e.contains("#5819"), "{line:?}: {e}");
fn mcp_never_plans_an_unconfined_session() {
let scratch = Scratch::new("mcp-plan");
let root = |read: bool, write: bool| {
let (r, w) = (read.then_some(scratch.0.as_path()), write.then_some(scratch.0.as_path()));
wordcraft_engine::file_access::AutomationRoots::new(r, w).unwrap()
};
let both = || root(true, true);
// --headless, or no flag: both roots or nothing.
for (headless, flag, switch) in [(true, true, true), (true, false, false), (false, false, true), (false, false, false)] {
assert!(matches!(mcp_plan(both(), headless, flag, switch), Ok(McpPlan::Headless(_))));
for partial in [None, root(true, false), root(false, true)] {
assert_eq!(mcp_plan(partial, headless, flag, switch).unwrap_err(), MCP_NEEDS_ROOTS);
}
}
// The flag and the switch: the window, with or without roots.
for roots in [None, root(true, false), both()] {
assert!(matches!(mcp_plan(roots, false, true, true), Ok(McpPlan::Live(_))));
}
// The flag without the switch: only with both roots, which confine its headless sessions.
assert!(matches!(mcp_plan(both(), false, true, false), Ok(McpPlan::Live(Some(_)))));
for partial in [None, root(true, false), root(false, true)] {
assert_eq!(mcp_plan(partial, false, true, false).unwrap_err(), MCP_NEEDS_ROOTS_OR_AGENTS);
}
}
@@ -352,19 +366,38 @@ fn mcp_headless_session_takes_the_author_flag() {
assert_eq!(unnamed.session.author, wordcraft_mcp::Headless::default().session.author, "no flag keeps the default author");
}
/// `--connect` is refused whether or not it has a value, written apart or as `--connect=…`, even with both roots valid.
/// `mcp --author` without a name is refused, also when another option follows it, instead of
/// starting with the default author or that option as the name.
#[test]
fn mcp_connect_is_refused_without_a_value_too() {
let scratch = Scratch::new("connect-bare");
let dir = scratch.0.to_string_lossy().into_owned();
let roots = ["--automation-read-root", &dir, "--automation-write-root", &dir];
for tail in [vec!["--connect"], vec!["--connect", "--author", "Claude"], vec!["--connect=127.0.0.1:9"], vec!["--connect="]] {
let line = args(&[&["mcp"][..], &roots, &tail].concat());
let e = run(&line).unwrap_err().to_string();
assert!(e.contains("--connect") && e.contains("#3695") && e.contains("#5819"), "{line:?}: {e}");
fn mcp_author_needs_a_name() {
assert_eq!(mcp_author(&args(&["--headless", "--author", "Claude"])), Ok(Some("Claude".to_string())));
assert_eq!(mcp_author(&args(&["--headless"])), Ok(None));
for given in [vec!["--author"], vec!["--author", "--headless"], vec!["--author", "A", "--author", "B"]] {
assert!(mcp_author(&args(&given)).is_err(), "{given:?}");
}
}
/// The deprecated `--connect` is taken out with its value, whether it has one, written apart or as
/// `--connect=…`, and leaves the other options as they were.
#[test]
fn mcp_connect_is_taken_out_with_its_value() {
for (given, left) in [
(vec!["--connect", "127.0.0.1:9", "--author", "Claude"], vec!["--author", "Claude"]),
(vec!["--connect"], vec![]),
(vec!["--connect", "--author", "Claude"], vec!["--author", "Claude"]),
(vec!["--headless", "--connect=127.0.0.1:9"], vec!["--headless"]),
(vec!["--connect=", "--connect", "x"], vec![]),
] {
let mut rest = args(&given);
assert!(take_connect(&mut rest), "{given:?}");
assert_eq!(rest, args(&left), "{given:?}");
assert!(validate_options("mcp", &rest, MCP_OPTIONS).is_ok());
}
let mut rest = args(&["--author", "Claude"]);
assert!(!take_connect(&mut rest));
assert_eq!(rest, args(&["--author", "Claude"]));
}
#[test]
fn render_rejects_missing_or_invalid_page_and_scale() {
// Missing operands
@@ -710,6 +743,70 @@ fn script_reads_from_a_stream_and_caps_its_size() {
assert!(script::load_from(&b"{"[..], "-", None).is_err());
}
#[test]
fn run_result_warnings_use_stderr_without_print() {
use std::process::Command;
const CHILD_ARGS: &str = "WORDCRAFT_CLI_WARNING_TEST_ARGS";
const STORE: &str = "WORDCRAFT_CLI_WARNING_TEST_STORE";
const WARNING: &str = "added for this session only: couldn't store it";
if let Ok(argv) = std::env::var(CHILD_ARGS) {
let store = PathBuf::from(std::env::var_os(STORE).unwrap());
wordcraft_fonts::FontDb::global().load_user_fonts(&store);
run(&serde_json::from_str::<Vec<String>>(&argv).unwrap()).unwrap();
// Bypass the test harness summary so the parent sees only the same header and the CLI's
// output. Each child has its own font database and never configures a real user store.
std::process::exit(0);
}
let dir = script_dir("run-warnings");
let store = dir.join("not-a-directory");
std::fs::write(&store, b"blocked font store").unwrap();
// Like the engine's font.add fixture, rename the bundled JetBrains Mono family in memory
// so it is treated as a new face. No additional font asset is used.
let mut font = include_bytes!("../../../assets/fonts/JetBrainsMono-Regular.ttf").to_vec();
let utf16 = |name: &str| name.encode_utf16().flat_map(u16::to_be_bytes).collect::<Vec<u8>>();
for (old, new) in [(b"JetBrains Mono".to_vec(), b"Cli Fixture 42".to_vec()), (utf16("JetBrains Mono"), utf16("Cli Fixture 42"))] {
let mut start = 0;
while let Some(at) = font[start..].windows(old.len()).position(|bytes| bytes == old) {
let range = start + at..start + at + old.len();
start = range.end;
font[range].copy_from_slice(&new);
}
}
let path = dir.join("fixture.ttf");
std::fs::write(&path, font).unwrap();
let params = json!({"path": path.to_string_lossy()});
let spec = format!("font.add={params}");
let script = write_script(&dir, &json!({"commands": [{"command": "font.add", "params": params}]}).to_string());
let child = |argv: &[&str]| {
let out = Command::new(std::env::current_exe().unwrap())
.args(["--exact", "tests::run_result_warnings_use_stderr_without_print", "--nocapture"])
.env(CHILD_ARGS, json!(argv).to_string())
.env(STORE, &store)
.output()
.unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
(String::from_utf8(out.stdout).unwrap(), String::from_utf8(out.stderr).unwrap())
};
let (header, quiet_stderr) = child(&["run", "--cmd", "caret.docEnd"]);
assert!(quiet_stderr.is_empty(), "{quiet_stderr}");
for argv in [["run", "--cmd", &spec], ["run", "--script", &script]] {
let (stdout, stderr) = child(&argv);
assert_eq!(stdout, header);
assert!(stderr.starts_with(&format!("wordcraft-cli: warning: {WARNING}")), "{stderr}");
assert_eq!(stderr.lines().count(), 1, "{stderr}");
let (stdout, stderr) = child(&[argv[0], argv[1], argv[2], "--print"]);
assert!(stderr.is_empty(), "{stderr}");
let result = stdout.strip_prefix(&header).unwrap().strip_prefix("font.add: ").unwrap();
let result: Value = serde_json::from_str(result).unwrap();
let warning = result["warning"].as_str().unwrap();
assert!(warning.starts_with(WARNING), "{result}");
}
}
#[test]
fn script_commands_run_before_cmd_flags() {
let dir = script_dir("order");
+24
View File
@@ -37,3 +37,27 @@ fn run_saves_the_document_opened_last() {
let stdout = String::from_utf8_lossy(&listed.stdout);
assert_eq!(stdout.matches("\"id\"").count(), 1, "{stdout}");
}
struct TempFile(std::path::PathBuf);
impl Drop for TempFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
#[test]
fn failed_run_commands_still_exit_with_an_error() {
let script = TempFile(std::env::temp_dir().join(format!("wordcraft-cli-run-error-{}.json", std::process::id())));
std::fs::write(&script.0, r#"{"commands":["no.such.command"]}"#).unwrap();
let script_path = script.0.to_string_lossy();
let cases = [(["run", "--cmd", "no.such.command"], "no.such.command:"), (["run", "--script", &script_path], "command 1 (no.such.command):")];
for (args, expected) in cases {
let out = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).args(args).output().unwrap();
assert_eq!(out.status.code(), Some(1));
assert!(out.stdout.is_empty(), "{out:?}");
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(stderr.starts_with("wordcraft-cli: ") && stderr.contains(expected), "{stderr}");
assert!(!stderr.contains("wordcraft-cli: warning:"), "{stderr}");
}
}
@@ -0,0 +1,110 @@
//! Conversion notes are scoped to rendered output and to the core fonts it uses.
use std::path::Path;
use std::process::Command;
use wordcraft_doc::{Document, Paragraph, para_block};
const NOTE: &str = "lines and pages may not match Word's";
fn convert(input: &Path, output: &Path, flags: &[&str]) -> String {
let run = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).arg("convert").arg(input).arg(output).args(flags).output().unwrap();
let stderr = String::from_utf8_lossy(&run.stderr);
assert!(run.status.success(), "{output:?}: {stderr}");
assert!(output.is_file(), "{output:?}");
assert_eq!(String::from_utf8_lossy(&run.stdout).trim_end(), format!("wrote {}", output.display()));
stderr.into_owned()
}
#[test]
fn conversion_font_notes_follow_the_output_format_and_pages() {
let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let dir = std::env::temp_dir().join(format!("wc-cli-convert-font-notices-{}-{unique}", std::process::id()));
std::fs::create_dir(&dir).unwrap();
let input = dir.join("input.json");
let mut doc = Document::new();
// Pick a real non-metric core substitution available on this runner, when there is one.
// WordCraft's own bundled Source Sans 3 is the font on the first page.
let (font, expected) = ["Cambria", "Calibri", "Arial", "Times New Roman", "Courier New"]
.into_iter()
.find_map(|font| {
let primary = wordcraft_engine::cmd::font::shown_as(&doc, font)?;
wordcraft_engine::cmd::font::warns(font, &primary).then_some((font, Some(format!("note: {font} is drawn in {primary},"))))
})
.unwrap_or(("Arial", None));
let paragraph =
|text: &str, family: &str| Paragraph::with_text(text, wordcraft_doc::CharProps { font: Some(family.into()), ..Default::default() });
let mut later_page = paragraph("This uses an Office family", font);
later_page.props.page_break_before = Some(true);
doc.body = vec![para_block(paragraph("Bundled font only", "Source Sans 3")), para_block(later_page)];
std::fs::write(&input, serde_json::to_vec(&doc).unwrap()).unwrap();
for (target, flags) in [
("out.docx", &[][..]),
("out.odt", &[][..]),
("out.rtf", &[][..]),
("out.txt", &[][..]),
("out.xml", &["--format", "wordml2003"][..]),
("flat.xml", &["--format", "flatopc"][..]),
("first.PNG", &[][..]),
] {
let stderr = convert(&input, &dir.join(target), flags);
assert!(!stderr.contains(NOTE), "{target}: {stderr}");
}
let xml = std::fs::read_to_string(dir.join("out.xml")).unwrap();
assert!(xml.contains("http://schemas.microsoft.com/office/word/2003/wordml"));
let flat = std::fs::read_to_string(dir.join("flat.xml")).unwrap();
assert!(flat.contains("http://schemas.microsoft.com/office/2006/xmlPackage"));
assert!(std::fs::read(dir.join("first.PNG")).unwrap().starts_with(b"\x89PNG\r\n\x1a\n"));
let whole = dir.join("whole.PDF");
let stderr = convert(&input, &whole, &["--update-fields"]);
assert!(std::fs::read(&whole).unwrap().starts_with(b"%PDF-"));
let notes: Vec<_> = stderr.lines().filter(|line| line.contains(NOTE)).collect();
if let Some(prefix) = expected {
assert_eq!(notes.len(), 1, "{stderr}");
assert!(notes[0].starts_with(&prefix), "{stderr}");
// A one-page image does report a non-metric core font when that page uses it.
doc.body = vec![para_block(paragraph("This uses an Office family", font))];
std::fs::write(&input, serde_json::to_vec(&doc).unwrap()).unwrap();
let stderr = convert(&input, &dir.join("used.png"), &[]);
assert_eq!(stderr.lines().filter(|line| line.starts_with(&prefix)).count(), 1, "{stderr}");
// The two pages can share a single shaped paragraph. Its later font must still
// stay out of a first-page image's notices, but appear in the complete PDF.
let mut split = paragraph(&"Bundled line\n".repeat(16), "Source Sans 3");
split
.insert_text(split.len(), "Office family only on page two", &wordcraft_doc::CharProps { font: Some(font.into()), ..Default::default() })
.unwrap();
split.props.line_spacing = Some(wordcraft_doc::props::LineSpacing::Exactly(17.0));
let section = doc.last_section.clone();
doc.last_section.page_h = 240.0;
doc.last_section.margin_top = 24.0;
doc.last_section.margin_bottom = 24.0;
doc.body = vec![para_block(split)];
std::fs::write(&input, serde_json::to_vec(&doc).unwrap()).unwrap();
let stderr = convert(&input, &dir.join("split.png"), &[]);
assert!(!stderr.contains(NOTE), "{stderr}");
let stderr = convert(&input, &dir.join("split.pdf"), &[]);
assert_eq!(stderr.lines().filter(|line| line.starts_with(&prefix)).count(), 1, "{stderr}");
doc.last_section = section;
} else {
assert!(notes.is_empty(), "{stderr}");
}
doc.body = vec![para_block(paragraph("Bundled font only", "Source Sans 3"))];
std::fs::write(&input, serde_json::to_vec(&doc).unwrap()).unwrap();
let stderr = convert(&input, &dir.join("unused.pdf"), &["--strict"]);
assert!(!stderr.contains(NOTE), "{stderr}");
let invalid = dir.join("invalid.pdf");
let run =
Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).arg("convert").arg(&input).arg(&invalid).args(["--format", "wordml2003"]).output().unwrap();
assert!(!run.status.success());
assert!(!invalid.exists());
let stderr = String::from_utf8_lossy(&run.stderr);
assert!(stderr.contains("only for an .xml file") && !stderr.contains(NOTE), "{stderr}");
assert!(run.stdout.is_empty());
std::fs::remove_dir_all(dir).unwrap();
}
@@ -0,0 +1,84 @@
use std::path::{Path, PathBuf};
use std::process::Command;
use serde_json::{Value, json};
/// Removes the temporary test folder when the test finishes or panics.
struct TempRoot(PathBuf);
impl TempRoot {
fn remove(self) -> std::io::Result<()> {
let res = std::fs::remove_dir_all(&self.0);
std::mem::forget(self);
res
}
}
impl Drop for TempRoot {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
#[test]
fn custom_dictionary_saves_home_relative_paths_and_can_clear_the_override() {
let root = TempRoot(std::env::temp_dir().join(format!("wc-custom-dictionary-{}", std::process::id())));
let home = root.0.join("home");
let profile = root.0.join("profile");
for folder in [&home, &profile] {
std::fs::create_dir_all(folder).unwrap();
std::fs::write(folder.join("custom.dic"), "wordcraftdictionary\n").unwrap();
}
let (preferred, fallback) = if cfg!(windows) { (&profile, &home) } else { (&home, &profile) };
let options = |home: Option<&Path>, profile: Option<&Path>, paths: &[&str]| {
let mut cli = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"));
cli.env_remove("HOME").env_remove("USERPROFILE");
if let Some(home) = home {
cli.env("HOME", home);
}
if let Some(profile) = profile {
cli.env("USERPROFILE", profile);
}
cli.args(["run", "--print"]);
for path in paths {
cli.args(["--cmd", &format!("file.options={}", json!({"customDictionary": path})), "--cmd", "file.options"]);
}
cli.output().unwrap()
};
let assert_saved = |home, profile, paths: &[&str], expected: &[Option<&Path>]| {
let report = options(home, profile, paths);
assert!(report.status.success(), "{}", String::from_utf8_lossy(&report.stderr));
let out = String::from_utf8(report.stdout).unwrap();
let reads: Vec<Value> =
out.lines().filter_map(|line| line.strip_prefix("file.options: ")).map(|line| serde_json::from_str(line).unwrap()).collect();
assert_eq!(reads.len(), expected.len() * 2, "{out}");
for (pair, expected) in reads.as_chunks::<2>().0.iter().zip(expected) {
for read in pair {
assert_eq!(read["customDictionary"].as_str().map(Path::new), *expected, "{out}");
}
}
};
let assert_refused = |home, profile, path, reason: &str| {
let report = options(home, profile, &[path]);
let error = String::from_utf8_lossy(&report.stderr);
assert!(!report.status.success() && error.contains(reason), "{error}");
};
let dic = preferred.join("custom.dic");
let absolute = dic.to_str().unwrap();
assert_saved(Some(&home), Some(&profile), &["~/custom.dic"], &[Some(&dic)]);
assert_saved(None, None, &[absolute, "auto", absolute, ""], &[Some(&dic), None, Some(&dic), None]);
let empty = Path::new("");
let (empty_home, empty_profile) = if cfg!(windows) { (fallback.as_path(), empty) } else { (empty, fallback.as_path()) };
assert_saved(Some(empty_home), Some(empty_profile), &["~/custom.dic"], &[Some(&fallback.join("custom.dic"))]);
assert_refused(None, None, "~/custom.dic", "cannot expand");
if cfg!(windows) {
assert_saved(Some(&home), Some(&profile), &[r"~\custom.dic"], &[Some(&dic)]);
assert_refused(None, None, r"~\custom.dic", "cannot expand");
assert_refused(Some(&home), Some(&profile), r"~\C:\custom.dic", "relative to the home folder");
assert_refused(Some(&home), Some(&profile), r"~\\custom.dic", "relative to the home folder");
} else {
assert_refused(Some(&home), Some(&profile), r"~\custom.dic", "isn't a full path");
}
root.remove().unwrap();
}
@@ -0,0 +1,52 @@
use std::path::Path;
use std::process::Command;
use serde_json::{Value, json};
#[test]
fn folder_options_save_home_relative_paths_and_validate_before_reading() {
let profile = std::env::temp_dir().join(format!("wc-folder-options-profile-{}", std::process::id()));
let templates = profile.join("Templates").join("Personal");
let dictionaries = profile.join("Dictionaries");
std::fs::create_dir_all(&templates).unwrap();
std::fs::create_dir_all(&dictionaries).unwrap();
let options = |profile: Option<&Path>, params: Value| {
let mut cli = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"));
cli.env_remove("HOME").env_remove("USERPROFILE");
if let Some(profile) = profile {
cli.env(if cfg!(windows) { "USERPROFILE" } else { "HOME" }, profile);
}
cli.args(["run", "--print", "--cmd", &format!("file.options={params}"), "--cmd", "file.options"]).output().unwrap()
};
let assert_saved = |profile, params| {
let report = options(profile, params);
assert!(report.status.success(), "{}", String::from_utf8_lossy(&report.stderr));
let out = String::from_utf8(report.stdout).unwrap();
let reads: Vec<Value> =
out.lines().filter_map(|line| line.strip_prefix("file.options: ")).map(|line| serde_json::from_str(line).unwrap()).collect();
assert_eq!(reads.len(), 2, "{out}");
for read in reads {
assert_eq!(Path::new(read["userTemplatesFolder"].as_str().unwrap()), templates);
assert_eq!(Path::new(read["dictionariesFolder"].as_str().unwrap()), dictionaries);
}
};
assert_saved(Some(profile.as_path()), json!({"userTemplatesFolder": "~/Templates/Personal", "dictionariesFolder": "~/Dictionaries"}));
assert_saved(None, json!({"userTemplatesFolder": templates, "dictionariesFolder": dictionaries}));
let win_params = json!({"userTemplatesFolder": r"~\Templates/Personal", "dictionariesFolder": r"~\Dictionaries"});
let assert_refused = |profile, params, reason: &str| {
let report = options(profile, params);
let error = String::from_utf8_lossy(&report.stderr);
assert!(!report.status.success() && error.contains(reason), "{error}");
};
if cfg!(windows) {
assert_saved(Some(profile.as_path()), win_params.clone());
assert_refused(None, win_params, "cannot expand");
assert_refused(Some(profile.as_path()), json!({"userTemplatesFolder": r"~\C:\Templates"}), "relative to the home folder");
} else {
assert_refused(Some(profile.as_path()), win_params, "isn't a full path");
}
assert_refused(None, json!({"dictionariesFolder": "~/Dictionaries"}), "cannot expand");
assert_refused(None, json!({"userTemplatesFolder": r"\\unreachable.invalid\share"}), "can't be a network folder");
std::fs::remove_dir_all(profile).unwrap();
}
+5
View File
@@ -1,7 +1,10 @@
#[cfg(unix)]
mod closed_stdout;
mod convert_fields;
mod convert_font_notices;
mod convert_region;
mod custom_dictionary;
mod folder_options;
mod help;
#[cfg(all(target_os = "linux", target_env = "gnu"))]
mod malloc_tuning;
@@ -9,5 +12,7 @@ mod mcp_roots;
#[cfg(all(unix, not(target_os = "macos")))]
mod non_utf8_args;
mod picture_then_typing;
mod reproducible_pdf;
mod strict;
mod text_tracked;
mod wrote_on_stdout;
+60 -9
View File
@@ -1,7 +1,9 @@
//! Shared rule 18 (#7124): `wordcraft-cli mcp` refuses to start without both
//! `--automation-read-root` and `--automation-write-root`, refuses `--connect` while the desktop
//! app doesn't confine its control channel (#3695, #5819), and with both roots refuses files
//! outside them, through the real binary.
//! `--automation-read-root` and `--automation-write-root` unless the ArtCraft Launcher's switch
//! lets agents into WordCraft's window (which confines them to its agent folder), takes the
//! deprecated `--connect` with a note, and with both roots refuses files outside them, through the
//! real binary. Each run gets its own suite flags, launcher folder and settings folder, so this
//! machine's own never count.
use std::io::Write;
use std::path::{Path, PathBuf};
@@ -48,11 +50,17 @@ fn s(p: &Path) -> String {
p.to_string_lossy().into_owned()
}
/// Run `wordcraft-cli mcp <args>`, send `lines` on stdin, then hang up.
/// Run `wordcraft-cli mcp <args>` without the suite's AI-MCP flag, send `lines` on stdin, then hang up.
fn mcp(args: &[String], lines: &[Value]) -> Output {
mcp_with(args, lines, &[("CRAFT_FLAGS", "-AI-MCP".into())])
}
/// [`mcp`] with these environment variables.
fn mcp_with(args: &[String], lines: &[Value], env: &[(&str, std::ffi::OsString)]) -> Output {
let mut child = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"))
.arg("mcp")
.args(args)
.envs(env.iter().map(|(k, v)| (*k, v)))
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
@@ -99,17 +107,60 @@ fn mcp_refuses_to_start_without_both_roots() {
assert!(reply.get("error").is_none(), "{reply}");
}
/// `--connect` is kept for one release: it says it is deprecated and is otherwise ignored, so a
/// client configuration that still has it keeps working, and it opens no way around the roots.
#[test]
fn mcp_connect_is_refused_until_the_app_confines_its_control_channel() {
fn mcp_connect_is_a_deprecated_alias_of_plain_mcp() {
let folders = Folders::new("connect");
let base = folders.0.clone();
let (read, write) = (s(&base.join("in")), s(&base.join("out")));
let why = ["--connect", "#3695", "#5819"];
refused_at_start(&["--connect".into(), "127.0.0.1:9".into()], &why);
refused_at_start(
let out = mcp(
&["--connect".into(), "127.0.0.1:9".into(), "--automation-read-root".into(), read, "--automation-write-root".into(), write],
&why,
&[serde_json::from_str(PING).unwrap()],
);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(out.status.success(), "stderr: {stderr}");
assert!(stderr.contains("--connect is deprecated"), "{stderr}");
let reply: Value = serde_json::from_slice(out.stdout.split(|b| *b == b'\n').next().unwrap()).unwrap();
assert_eq!(reply["id"], 1, "{reply}");
refused_at_start(&["--connect".into(), "127.0.0.1:9".into()], &["--connect is deprecated", "--automation-read-root"]);
}
/// With the suite's AI-MCP flag: while the launcher's switch keeps agents out, `mcp` still needs
/// both roots and says how to let agents in; once the launcher's list names WordCraft, plain `mcp`
/// starts without roots and follows the closed-app choice (here: ask to open WordCraft).
#[test]
fn with_the_flag_the_launcher_switch_lets_plain_mcp_start() {
let folders = Folders::new("switch");
let base = folders.0.clone();
let launcher = base.join("launcher");
let settings = base.join("settings");
std::fs::create_dir_all(&launcher).unwrap();
std::fs::create_dir_all(&settings).unwrap();
std::fs::write(settings.join("config.toml"), "schema_version = 1\n[integrations]\nwhenAppClosed = \"error\"\n").unwrap();
let env = [
("CRAFT_FLAGS", std::ffi::OsString::from("AI-MCP")),
("CRAFT_MCP_DIR", launcher.clone().into_os_string()),
("WORDCRAFT_PROFILE_DIR", settings.into_os_string()),
];
let ping: Value = serde_json::from_str(PING).unwrap();
let off = mcp_with(&[], std::slice::from_ref(&ping), &env);
let stderr = String::from_utf8_lossy(&off.stderr);
assert!(!off.status.success() && off.stdout.is_empty(), "started with the switch off: {stderr}");
assert!(stderr.contains("ArtCraft Launcher") && stderr.contains("--automation-read-root"), "{stderr}");
let cli = s(Path::new(env!("CARGO_BIN_EXE_wordcraft-cli")));
let list = json!({"version": 1, "apps": [{"id": "wordcraft", "name": "WordCraft", "command": cli, "args": ["mcp"]}]});
std::fs::write(launcher.join("apps.json"), list.to_string()).unwrap();
let on = mcp_with(&[], &[ping, tool(2, "list_documents", json!({}))], &env);
let stderr = String::from_utf8_lossy(&on.stderr);
assert!(on.status.success(), "stderr: {stderr}");
let replies: Vec<Value> =
String::from_utf8_lossy(&on.stdout).lines().filter(|l| !l.trim().is_empty()).map(|l| serde_json::from_str(l).unwrap()).collect();
assert!(replies.iter().any(|r| r["id"] == 1 && r.get("error").is_none()), "{replies:?}");
let call = replies.iter().find(|r| r["id"] == 2).expect("the tool call is answered");
assert_eq!(call["result"]["isError"], true, "{call}");
assert!(call.to_string().contains("isn't running"), "the closed-app choice answers: {call}");
}
/// `tools/call` request `id` for `name` with `arguments`.
@@ -0,0 +1,127 @@
//! Direct PDF exports use the saved timestamp without changing the source document.
use std::process::Command;
#[test]
fn direct_pdf_exports_use_the_pinned_epoch() {
check_creation_date("", "20261005140300");
}
#[test]
fn direct_pdf_exports_preserve_an_existing_creation_date() {
check_creation_date("2000-01-01T00:00:00Z", "20000101000000");
}
/// A .docx records `dcterms:created` as text and the reader takes it as it finds it, so a
/// document can arrive holding something that is not a date at all. The PDF writer cannot put
/// that in a document and fell back to the clock, so two exports of the same file differed even
/// with `SOURCE_DATE_EPOCH` set -- the one thing it is there to stop (noted in review).
#[test]
fn direct_pdf_exports_use_the_pinned_epoch_when_the_existing_date_is_unreadable() {
for created in ["not-a-date", "", " ", "2000-13-01T00:00:00Z", "2000-01-32T00:00:00Z", "99-01-01", "today"] {
check_creation_date(created, "20261005140300");
}
}
fn check_creation_date(created: &str, expected: &str) {
// A sequence number, not the clock alone: `as_nanos` carries microsecond granularity on
// macOS, so two of these tests starting in the same microsecond took the same directory,
// wrote each other's `input.json` and failed the preservation assertion below -- a flake in
// this harness, not in the export. `create_dir` rather than `create_dir_all` so that if a
// name ever does repeat it fails here instead of quietly sharing a directory again.
static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let seq = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let dir = std::env::temp_dir().join(format!("wordcraft-pdf-date-{}-{unique}-{seq}", std::process::id()));
std::fs::create_dir(&dir).unwrap_or_else(|e| panic!("{}: {e}", dir.display()));
let mut doc = wordcraft_doc::Document::from_text("Original reproducible PDF check.");
doc.core.created = created.into();
let input = dir.join("input.json");
let source = serde_json::to_vec(&doc).unwrap();
std::fs::write(&input, &source).unwrap();
for command in ["file.exportPdf", "file.printPdf"] {
let output = dir.join(format!("{command}.pdf"));
let params = serde_json::json!({"path": output});
let run = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"))
.arg("run")
.arg("--file")
.arg(&input)
.arg("--cmd")
.arg(format!("{command}={params}"))
.env("SOURCE_DATE_EPOCH", "1791208980")
.output()
.unwrap();
assert!(run.status.success(), "{command}: {}", String::from_utf8_lossy(&run.stderr));
let bytes = std::fs::read(output).unwrap();
let date = format!("/CreationDate(D:{expected}");
assert!(bytes.windows(date.len()).any(|part| part == date.as_bytes()), "{command} must use {expected}");
assert_eq!(std::fs::read(&input).unwrap(), source, "export must preserve its source file");
}
}
/// A fresh directory for one test's files.
fn scratch(name: &str) -> std::path::PathBuf {
let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let dir = std::env::temp_dir().join(format!("wordcraft-{name}-{}-{unique}", std::process::id()));
std::fs::create_dir(&dir).unwrap_or_else(|e| panic!("{}: {e}", dir.display()));
dir
}
fn cli(env: &str, cmds: &[String]) -> std::process::Output {
let mut run = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"));
run.arg("run").env("SOURCE_DATE_EPOCH", env);
for c in cmds {
run.arg("--cmd").arg(c);
}
run.output().unwrap()
}
/// The pinned date is the file's, not the edits': a comment and a tracked change made in the
/// same run keep the time they were made, so a pinned epoch cannot back-date them (noted in
/// review). Saved as flat XML, which holds both in plain text.
#[test]
fn a_pinned_epoch_dates_the_file_and_not_the_edits_in_it() {
let out = scratch("pinned-edits").join("edits.xml");
let before = wordcraft_engine::cmd::now_iso();
let run = cli(
"1791208980",
&[
r#"review.trackChanges={"value": true}"#.to_string(),
r#"text.insert={"text": "tracked"}"#.to_string(),
r#"review.newComment={"text": "note"}"#.to_string(),
format!("file.saveAs={}", serde_json::json!({"path": out})),
],
);
let after = wordcraft_engine::cmd::now_iso();
assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr));
let xml = std::fs::read_to_string(&out).unwrap();
assert!(xml.contains(r#"<dcterms:modified xsi:type="dcterms:W3CDTF">2026-10-05T14:03:00Z</dcterms:modified>"#), "the file's date is pinned");
let dates: Vec<&str> = xml.split(r#"w:date=""#).skip(1).filter_map(|rest| rest.split('"').next()).collect();
assert!(xml.contains("<w:ins ") && xml.contains("<w:comment "), "a tracked insertion and a comment were saved");
assert!(dates.len() >= 2, "both carry a date: {dates:?}");
for date in dates {
assert!((before.as_str()..=after.as_str()).contains(&date), "{date} is the clock's, between {before} and {after}");
}
}
/// A value that is set and cannot be used is said out loud, and the run still succeeds: the
/// files take the clock's date, as they would with the variable unset (noted in review).
#[test]
fn an_unusable_epoch_is_reported_on_stderr() {
let dir = scratch("epoch-warning");
let save = |name: &str| format!("file.exportPdf={}", serde_json::json!({"path": dir.join(name)}));
let run = cli("later", &[save("later.pdf")]);
assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr));
let stderr = String::from_utf8_lossy(&run.stderr);
assert!(stderr.contains(r#"warning: SOURCE_DATE_EPOCH="later" is not a whole number of seconds"#), "{stderr}");
let pdf = std::fs::read(dir.join("later.pdf")).unwrap();
let pinned = b"/CreationDate(D:20261005140300";
assert!(pdf.windows(b"/CreationDate(D:".len()).any(|w| w == b"/CreationDate(D:"), "the export has a creation date");
assert!(!pdf.windows(pinned.len()).any(|w| w == pinned), "and it is the clock's, not a pinned one");
for quiet in ["1791208980", ""] {
let run = cli(quiet, &[save("quiet.pdf")]);
assert!(run.status.success());
assert!(!String::from_utf8_lossy(&run.stderr).contains("SOURCE_DATE_EPOCH"), "{quiet:?} says nothing");
}
}
+2
View File
@@ -148,6 +148,8 @@ fn an_uncovered_code_point_fails_strict_with_a_report_and_no_file() {
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
let text = stderr(&r);
assert!(text.contains(&format!("wordcraft-cli: strict: 1 character cannot be drawn: {cp} (×3)")), "{text}");
assert!(!text.contains("lines and pages may not match Word's"), "{text}");
assert!(r.stdout.is_empty());
let json = report_json(&r);
assert_eq!(json["schema"], 1);
assert_eq!(json["strict"], "failed");
@@ -0,0 +1,70 @@
//! A write's `wrote <path>` confirmation is a result, so it goes to stdout, where a script that
//! captures the output finds it; stderr keeps errors and diagnostics (#7070).
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
fn dir(name: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("wc-cli-wrote-{name}-{}", std::process::id()));
// A failed run leaves its directory behind (cleanup runs only after the assertions), and a
// later process can reuse the PID: start clean so a stale file cannot pass a check.
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
}
/// The confirmation is on stdout and not on stderr, and the file is there.
fn assert_wrote_on_stdout(run: &Output, out: &Path) {
let (stdout, stderr) = (String::from_utf8_lossy(&run.stdout), String::from_utf8_lossy(&run.stderr));
assert!(run.status.success(), "status {:?}, stderr: {stderr}", run.status);
assert!(out.is_file(), "{} was not written", out.display());
let line = format!("wrote {}", out.display());
assert!(stdout.lines().any(|l| l == line), "stdout lacks `{line}`: {stdout:?}");
assert!(!stderr.contains("wrote "), "the confirmation is on stderr too: {stderr:?}");
}
#[test]
fn convert_confirms_the_write_on_stdout() {
let d = dir("convert");
let (input, out) = (d.join("in.txt"), d.join("out.docx"));
std::fs::write(&input, "Hello").unwrap();
let run = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).arg("convert").arg(&input).arg(&out).output().unwrap();
assert_wrote_on_stdout(&run, &out);
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn run_confirms_each_save_on_stdout() {
let d = dir("run");
let out = d.join("out.docx");
let run = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"))
.args(["run", "--template", "blank", "--cmd", r#"text.insert={"text":"x"}"#, "--save"])
.arg(&out)
.output()
.unwrap();
assert_wrote_on_stdout(&run, &out);
let _ = std::fs::remove_dir_all(&d);
}
/// A reader that has already hung up does not stop the job: every save still runs, though its
/// confirmation has nowhere to go. A PNG is written only in the confirming loop, so it shows a
/// save that was skipped.
#[test]
fn run_keeps_saving_after_stdout_closes() {
let d = dir("closed");
let job = d.join("job.json");
std::fs::write(
&job,
r#"{"template": "blank", "commands": [{"command": "text.insert", "params": {"text": "x"}}], "save": ["first.docx", "second.png"]}"#,
)
.unwrap();
let (reader, writer) = std::io::pipe().unwrap();
drop(reader);
let run = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).args(["run", "--script"]).arg(&job).stdout(writer).output().unwrap();
let stderr = String::from_utf8_lossy(&run.stderr);
assert!(run.status.success(), "status {:?}, stderr: {stderr}", run.status);
for out in ["first.docx", "second.png"] {
assert!(d.join(out).is_file(), "{out} was not written; stderr: {stderr}");
}
let _ = std::fs::remove_dir_all(&d);
}
+1
View File
@@ -27,6 +27,7 @@ const POLL_MS: i32 = 16;
pub fn install(ctx: egui::Context) -> Receiver<ControlRequest> {
let (queue, requests) = channel::<ControlRequest>();
let request: Request = Rc::new(move |method, params| {
let params = super::page_params::control_params(&method, params);
let (control, reply) = ControlRequest::new(method, params);
if queue.send(control).is_err() {
return Box::pin(async { json!({"ok": false, "error": "the app is not running"}) });
+2
View File
@@ -23,6 +23,8 @@ mod prefs;
mod api;
#[cfg(target_arch = "wasm32")]
mod host;
#[cfg(any(target_arch = "wasm32", test))]
mod page_params;
#[cfg(target_arch = "wasm32")]
mod web;
+55
View File
@@ -0,0 +1,55 @@
use serde_json::Value;
pub(super) fn control_params(method: &str, mut params: Value) -> Value {
// The page helper asks for inline data. A screenshot without a path already returns it.
if method == "ui.screenshot"
&& let Some(fields) = params.as_object_mut()
&& !fields.contains_key("path")
&& fields.get("data") == Some(&Value::Bool(true))
{
fields.remove("data");
}
params
}
#[cfg(test)]
mod tests {
use craft::automation::screenshot::ScreenshotParams;
use serde_json::json;
use super::control_params;
#[test]
fn page_helper_requests_the_same_capture_as_a_direct_request() {
for (helper, direct) in
[(json!({"data": true}), json!({})), (json!({"data": true, "region": [10, 20, 100, 200]}), json!({"region": [10, 20, 100, 200]}))]
{
let params = control_params("ui.screenshot", helper);
assert_eq!(params, direct);
assert!(ScreenshotParams::from_params(&params).is_ok());
}
}
#[test]
fn page_helper_keeps_screenshot_validation() {
for (input, expected) in [
(json!({"data": true, "region": [100, 200, 10, 20]}), json!({"region": [100, 200, 10, 20]})),
(json!({"data": true, "viewport": "other"}), json!({"viewport": "other"})),
(json!({"data": true, "path": "capture.png"}), json!({"data": true, "path": "capture.png"})),
(json!({"data": true, "path": null}), json!({"data": true, "path": null})),
(json!({"data": false}), json!({"data": false})),
(json!({"data": "true"}), json!({"data": "true"})),
] {
let params = control_params("ui.screenshot", input);
assert_eq!(params, expected);
assert!(ScreenshotParams::from_params(&params).is_err());
}
}
#[test]
fn direct_requests_keep_their_parameters() {
for (method, params) in [("ui.screenshot", json!({"path": "capture.png"})), ("file.new", json!({"data": true}))] {
assert_eq!(control_params(method, params.clone()), params);
}
}
}
+1
View File
@@ -36,6 +36,7 @@ craft = { workspace = true, features = [
"ui-app",
"dialogs",
"automation",
"automation-agents",
"gpu-startup",
"print",
"settings",
+89 -8
View File
@@ -4,7 +4,8 @@
//! A connection authenticates once with the token (`docs/control-protocol.md`, Token). When no
//! token or token file is supplied, the app generates a token and writes it to
//! `<settings>/control-key.<instance>` (mode 0600) after the port is bound, and removes the file
//! when the window closes.
//! when the window closes. The server itself goes to the agent link for the run
//! (`AgentLink::from_launch`), so File › Options › Agents says the launch options manage it.
use std::net::TcpListener;
use std::path::{Path, PathBuf};
@@ -25,17 +26,37 @@ pub struct Control {
}
impl Control {
/// The server, for the agent link to keep for the whole run (`AgentLink::from_launch`), and the
/// token file this run wrote, which the app removes when the window closes.
pub fn split(self) -> (Listening, TokenFile) {
(self.listening, TokenFile(self.created))
}
/// Stop accepting connections and remove the token file this run wrote, if any.
#[cfg(test)]
pub fn shut_down(self) {
let Self { listening, created } = self;
let (listening, file) = self.split();
drop(listening);
remove(created.as_deref());
file.remove();
}
}
/// The default token file a run wrote, if any; a token file the user supplied is never removed.
pub struct TokenFile(Option<PathBuf>);
impl TokenFile {
/// Removes the file this run wrote.
pub fn remove(self) {
remove(self.0.as_deref());
}
}
fn remove(path: Option<&Path>) {
if let Some(path) = path {
let _ = std::fs::remove_file(path);
if let Some(path) = path
&& let Err(e) = std::fs::remove_file(path)
&& e.kind() != std::io::ErrorKind::NotFound
{
log::warn!("couldn't remove {}: {e}", path.display());
}
}
@@ -62,7 +83,7 @@ impl StartError {
/// `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)> {
match start_with(options, port, host, settings, ControlOptions::server_token) {
match start_with(options, port, host, settings, ControlOptions::server_token, serve) {
Ok(started) => Some(started),
Err(err) => {
log::error!("{}", err.message());
@@ -77,6 +98,7 @@ fn start_with(
host: WindowHost,
settings: Option<&Path>,
token_for: impl FnOnce(&ControlOptions) -> Result<String, AutomationError>,
serve: impl FnOnce(TcpListener, String, WindowHost) -> std::io::Result<(Receiver<ControlRequest>, Listening)>,
) -> 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}")))?;
@@ -122,16 +144,17 @@ mod tests {
/// 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(
fn try_start_retrying_token_timeout_with(
options: &ControlOptions,
port: u16,
host: WindowHost,
settings: Option<&Path>,
mut token_for: impl FnMut(&ControlOptions) -> Result<String, AutomationError>,
mut serve: impl FnMut(TcpListener, String, WindowHost) -> std::io::Result<(Receiver<ControlRequest>, Listening)>,
) -> Result<(Receiver<ControlRequest>, Control), (usize, StartError)> {
let mut attempt = 1;
loop {
match start_with(options, port, host.clone(), settings, &mut token_for) {
match start_with(options, port, host.clone(), settings, &mut token_for, &mut serve) {
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}");
@@ -142,6 +165,16 @@ mod tests {
}
}
fn try_start_retrying_token_timeout(
options: &ControlOptions,
port: u16,
host: WindowHost,
settings: Option<&Path>,
token_for: impl FnMut(&ControlOptions) -> Result<String, AutomationError>,
) -> Result<(Receiver<ControlRequest>, Control), (usize, StartError)> {
try_start_retrying_token_timeout_with(options, port, host, settings, token_for, serve)
}
fn start_retrying_token_timeout(
options: &ControlOptions,
port: u16,
@@ -400,4 +433,52 @@ mod tests {
assert!(rx.try_recv().is_err(), "refused auth attempts must not reach the UI");
control.shut_down();
}
struct TempDir(std::path::PathBuf);
impl TempDir {
fn new(name: &str) -> Self {
let dir = std::env::temp_dir().join(format!("{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
Self(dir)
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
#[test]
fn a_stale_key_file_is_replaced() {
let dir = TempDir::new("wordcraft-control-stale");
std::fs::create_dir_all(&dir.0).unwrap();
let p = wordcraft_control_key::key_path(&dir.0, 0);
std::fs::write(&p, "old").unwrap();
let options = ControlOptions::default();
let (_rx, control) = start_retrying_token_timeout(&options, 0, host(), Some(&dir.0), ControlOptions::server_token);
let token = std::fs::read_to_string(&p).unwrap();
assert_ne!(token.trim(), "old");
assert!(ControlClient::connect(control.listening.addr, token.trim()).is_ok());
control.shut_down();
}
#[test]
fn an_accept_thread_spawn_failure_aborts_start_and_removes_the_key() {
let dir = TempDir::new("wordcraft-control-spawn-fail");
let path = wordcraft_control_key::key_path(&dir.0, 0);
let options = ControlOptions::default();
let result =
try_start_retrying_token_timeout_with(&options, 0, host(), Some(&dir.0), ControlOptions::server_token, |_listener, _token, _host| {
assert!(path.exists(), "startup wrote the token file before spawning");
Err(std::io::Error::other("injected accept thread spawn failure"))
});
assert!(
matches!(result, Err((_, StartError::Other(ref msg))) if msg.contains("cannot start the accept thread")),
"a server without its accept thread must not report success"
);
assert!(!path.exists(), "failed startup must remove its published key");
}
}
+88 -12
View File
@@ -67,8 +67,8 @@ struct App {
settings: SharedSettings<Prefs>,
/// The print spool, a handle on the one in the app's services: jobs being sent finish first.
spool: Spool,
/// The control server, when `--control` started one; it removes the token file it made.
control: Option<control_server::Control>,
/// The token file `--control` wrote, removed at exit; its server runs in the agent link.
control: Option<control_server::TokenFile>,
/// The app binary's last step as the app leaves, run once at the end of `finish` (a Nightly
/// quit ends the process inside AppKit's terminate, after eframe's `on_exit`).
exit: Option<Box<dyn FnOnce()>>,
@@ -118,8 +118,8 @@ impl App {
if let Err(e) = self.settings.lock().flush() {
log::warn!("preferences: {e}");
}
if let Some(control) = self.control.take() {
control.shut_down();
if let Some(file) = self.control.take() {
file.remove();
}
if !launch_profile::current().is_nightly() {
self.app.start_pending_update();
@@ -858,13 +858,41 @@ fn main() -> eframe::Result {
log::warn!("local recovery unavailable: {e}");
}
}
// Agents in the open window: while the ArtCraft Launcher's switch (Settings › AI agents)
// names WordCraft, the agent link serves them and publishes where, so `wordcraft-cli mcp`
// finds the window. `--control` runs its own server for the whole run instead. Allow
// Agent Control off (File › Options › Agents) refuses both. A Nightly window serves none.
let mut control_server = None;
if !nightly
&& let Some(port) = control.port
&& let Some((rx, started)) = control_server::start(&control, port, WindowHost::of(&ctx), wordcraft_control_key::settings_dir().as_deref())
{
app = app.with_control(ControlChannel::new(rx));
control_server = Some(started);
if !nightly {
let settings_dir = wordcraft_control_key::settings_dir();
// A file a crashed launch left behind names a port nothing serves; before this
// launch's own listener, so it doesn't keep it.
if let Some(dir) = &settings_dir {
craft::automation::agents::remove_stale_connection(dir);
}
let allow = settings.lock().get().integrations.allow_agent_control;
let launched = match control.port {
Some(port) if !allow => {
complain(format_args!("File › Options › Agents › Allow Agent Control is off: not listening on port {port}"));
None
}
Some(port) => control_server::start(&control, port, WindowHost::of(&ctx), settings_dir.as_deref()),
None => None,
};
let link = match launched {
Some((rx, started)) => {
app = app.with_control(ControlChannel::new(rx));
let (listening, token_file) = started.split();
control_server = Some(token_file);
craft::automation::agents::AgentLink::from_launch(listening)
}
None => craft::automation::agents::AgentLink::new(settings_dir, format!("WordCraft {}", env!("CARGO_PKG_VERSION"))),
};
let switch = craft::automation::agents::AgentSwitch::watch(wordcraft_ui_egui::agents::LAUNCHER_APP_ID, {
let ctx = ctx.clone();
move || ctx.request_repaint()
});
app = app.with_agents(wordcraft_ui_egui::agents::Agents::new(link, switch));
}
// Nothing to open (no files, no sample, no control channel driving the editor): start
// on File › Home, as Word does (#766), unless the Start screen option is off. Files
@@ -1202,8 +1230,8 @@ mod smoke {
assert!(run.app.app.dialog_host_mut().shows_modal(), "the Save Changes prompt shows");
let tree = run.frames.tree();
// The framework words the answer as the platform does: "Don't Save" on macOS, "No" elsewhere.
let dont_save = if cfg!(target_os = "macos") { "Don't Save" } else { "No" };
// The framework words the answer "Don't Save" on every OS (craft-libs 92ed66b43).
let dont_save = "Don't Save";
// A button is named by the label inside it (`labelled_by`) as often as by its own name, and the label's own
// node is no button: the testing module's `name` and `is_interactive` read it as the fixture's `by_label` does.
let button = tree
@@ -1271,6 +1299,54 @@ mod smoke {
assert!(run.app.app.dialog_host_mut().is_empty(), "Escape dismisses About");
assert_eq!(run.app.app.session.doc.plain_text(wordcraft_doc::StoryRef::Body), before);
}
/// With a modal dialog open, Quit stays enabled and ⌘Q / menu Quit still run `ui.quit`:
/// a clean document quits and a modified one opens Save Changes (#8792).
#[cfg(target_os = "macos")]
#[test]
fn native_quit_works_while_a_modal_dialog_is_open() {
use craft::menu::{ItemRole, NativeMenu};
let mut clean = Run::new();
let fake = native_menu::FakeBackend::default();
let synced = fake.synced.clone();
let events = fake.events.clone();
let dispatch_cell = fake.dispatch.clone();
clean.app.native_menu = Some(NativeMenu::new(Box::new(fake)));
clean.app.app.run("ui.dialog", json!({"name": "about"})).unwrap();
clean.settle();
assert!(clean.app.app.dialog_host_mut().shows_modal());
let quit = {
let bars = synced.borrow();
let bar = bars.last().unwrap();
let about = bar.items().into_iter().find(|item| item.role == Some(ItemRole::About)).unwrap();
let quit = bar.items().into_iter().find(|item| item.role == Some(ItemRole::Quit)).unwrap();
assert!(!about.enabled, "About is greyed while About is open");
assert!(quit.enabled, "Quit stays enabled while About is open");
quit.clone()
};
let dispatch = dispatch_cell.borrow().as_ref().unwrap().clone();
let cmd_q = quit.shortcut.unwrap();
events.borrow_mut().push(dispatch.chosen(&quit.command, Some(&cmd_q), quit.layout_shortcut, true, cmd_q.mods, None));
clean.settle();
assert!(clean.app.app.quit_requested, "Cmd+Q quits a clean document while About is open");
let mut dirty = Run::new();
let fake = native_menu::FakeBackend::default();
let events = fake.events.clone();
let dispatch_cell = fake.dispatch.clone();
dirty.app.native_menu = Some(NativeMenu::new(Box::new(fake)));
dirty.app.app.run("text.insert", json!({"text": "unsaved"})).unwrap();
dirty.app.app.run("ui.dialog", json!({"name": "paragraph"})).unwrap();
dirty.settle();
assert!(dirty.app.app.dialog_host_mut().shows_modal());
let dispatch = dispatch_cell.borrow().as_ref().unwrap().clone();
events.borrow_mut().push(dispatch.chosen(&quit.command, Some(&cmd_q), quit.layout_shortcut, false, Default::default(), None));
dirty.settle();
assert!(!dirty.app.app.quit_requested, "Quit asks Save Changes first for a modified document");
dirty.app.app.run("ui.saveChanges", json!({"answer": "dontSave"})).unwrap();
assert!(dirty.app.app.quit_requested, "Don't Save completes the quit");
}
}
#[cfg(test)]
+68 -3
View File
@@ -1,6 +1,6 @@
//! The macOS application menu uses the same About dialog as File › About.
use craft::menu::{CommandRef, Gate, Item, ItemRole, Layout, LayoutOptions, Menu, MenuBar, MenuRole, NativeMenu, mac_layout};
use craft::menu::{CommandRef, Gate, Item, ItemRole, Layout, LayoutOptions, Menu, MenuBar, MenuRole, ModalRules, NativeMenu, mac_layout};
use serde_json::json;
use wordcraft_ui_egui::{WordApp, i18n};
@@ -36,15 +36,24 @@ fn layout_in(lang: i18n::Lang) -> Layout {
layout(&|s| i18n::tr(lang, s).to_owned())
}
/// Commands that still run from the application menu while a modal dialog is open: `ui.quit` asks
/// about unsaved documents through `WordApp::quit`, matching the built-in Quit item and the Dock.
fn modal_rules() -> ModalRules {
ModalRules::default().in_dialogs(["ui.quit"])
}
pub(super) fn install(ctx: &egui::Context, app: &WordApp) -> Option<NativeMenu> {
let menu = craft::menu::mac::install(ctx, &layout_in(lang(app)).bar);
if menu.is_none() {
let mut menu = craft::menu::mac::install(ctx, &layout_in(lang(app)).bar);
if let Some(menu) = &mut menu {
menu.set_modal_rules(modal_rules());
} else {
log::warn!("the WordCraft application menu could not be installed");
}
menu
}
pub(super) fn update(menu: &mut NativeMenu, app: &mut WordApp, ctx: &egui::Context) {
menu.set_modal_rules(modal_rules());
menu.set_gate(Gate::default().modal(app.dialog_host_mut().shows_modal()));
for command in menu.take_clicks(ctx) {
if let Err(error) = app.run(&command.id, command.params) {
@@ -58,6 +67,29 @@ pub(super) fn update(menu: &mut NativeMenu, app: &mut WordApp, ctx: &egui::Conte
}
}
#[cfg(test)]
#[derive(Default)]
pub(super) struct FakeBackend {
pub(super) synced: std::rc::Rc<std::cell::RefCell<Vec<MenuBar>>>,
pub(super) events: std::rc::Rc<std::cell::RefCell<Vec<craft::menu::Event>>>,
pub(super) dispatch: std::rc::Rc<std::cell::RefCell<Option<craft::menu::Dispatch>>>,
}
#[cfg(test)]
impl craft::menu::Backend for FakeBackend {
fn sync(&mut self, bar: &MenuBar) {
self.synced.borrow_mut().push(bar.clone());
}
fn attach(&mut self, dispatch: craft::menu::Dispatch) {
*self.dispatch.borrow_mut() = Some(dispatch);
}
fn drain(&mut self) -> Vec<craft::menu::Event> {
std::mem::take(&mut *self.events.borrow_mut())
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -78,4 +110,37 @@ mod tests {
let quit = layout.bar.items().into_iter().find(|item| item.role == Some(ItemRole::Quit)).unwrap();
assert_eq!(quit.command.id, "ui.quit");
}
/// Quit stays enabled while a modal dialog is open, and both a menu click and ⌘Q pass the gate (#8792).
#[test]
fn quit_stays_enabled_and_runs_under_modal_rules() {
let fake = FakeBackend::default();
let synced = fake.synced.clone();
let events = fake.events.clone();
let dispatch_cell = fake.dispatch.clone();
let mut menu = NativeMenu::new(Box::new(fake));
menu.set_modal_rules(modal_rules());
menu.set_gate(Gate::default().modal(true));
let ctx = egui::Context::default();
menu.sync_with("en", || layout(&|s| s.to_owned()));
let bar = synced.borrow();
let last = bar.last().unwrap();
let about = last.items().into_iter().find(|item| item.role == Some(ItemRole::About)).unwrap().clone();
let quit = last.items().into_iter().find(|item| item.role == Some(ItemRole::Quit)).unwrap().clone();
drop(bar);
assert!(!about.enabled, "About is greyed while a modal dialog is open");
assert!(quit.enabled, "Quit stays enabled while a modal dialog is open");
let dispatch = dispatch_cell.borrow().as_ref().unwrap().clone();
let cmd_q = quit.shortcut.unwrap();
events.borrow_mut().extend([
dispatch.chosen(&about.command, about.shortcut.as_ref(), about.layout_shortcut, false, Default::default(), None),
dispatch.chosen(&quit.command, Some(&cmd_q), quit.layout_shortcut, false, Default::default(), None),
dispatch.chosen(&quit.command, Some(&cmd_q), quit.layout_shortcut, true, cmd_q.mods, None),
]);
menu.poll(&ctx);
assert_eq!(menu.take_clicks(&ctx), vec![quit.command.clone(), quit.command]);
}
}
+20 -4
View File
@@ -39,15 +39,31 @@ fn write_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> {
let written = std::io::Write::write_all(&mut file, bytes).and_then(|()| file.sync_all());
drop(file);
if let Err(error) = written {
let _ = std::fs::remove_file(&temporary);
if let Err(e) = std::fs::remove_file(&temporary) {
log::warn!("couldn't remove {}: {e}", temporary.display());
}
return Err(error);
}
if let Err(error) = std::fs::rename(&temporary, path) {
let _ = std::fs::remove_file(&temporary);
if let Err(e) = std::fs::remove_file(&temporary) {
log::warn!("couldn't remove {}: {e}", temporary.display());
}
return Err(error);
}
if let Ok(directory) = File::open(directory) {
let _ = directory.sync_all();
match File::open(directory) {
Ok(dir) => {
if let Err(e) = dir.sync_all() {
log::warn!("couldn't sync {}: {e}", directory.display());
}
}
#[cfg(unix)]
Err(e) => {
log::warn!("couldn't open {} to sync: {e}", directory.display());
}
#[cfg(not(unix))]
Err(_) => {
// Opening a directory handle with File::open is not supported on Windows, so skipping the sync there is expected.
}
}
Ok(())
}
+4
View File
@@ -206,6 +206,10 @@ display_name = "entropybeater"
[people.helenkwok]
real_name = "Helen Kwok"
[people.adikshan11]
real_name = "Adithya Shankaran"
sync_github_name = true
[people.ashokram-si]
real_name = "Ashok Ram"
+1 -1
View File
@@ -452,7 +452,7 @@ pub fn reroute_group(group: &mut InlineObject) -> bool {
// Rendering scales the rectangle before spinning it. Undo only the group scale
// so route can rebuild an unrotated child frame without moving fallback ends.
let (x, y) = (fin(c.x) * sx, fin(c.y) * sy);
let (cw, ch) = ((fin(*w) * sx).clamp(0.0, 4000.0), (fin(*h) * sy).clamp(0.0, 4000.0));
let (cw, ch) = ((fin(*w) * sx).clamp(0.0, crate::para::MAX_SHARE_LEN), (fin(*h) * sy).clamp(0.0, crate::para::MAX_SHARE_LEN));
let (cx, cy) = (x + cw / 2.0, y + ch / 2.0);
let spin = float.spin();
let s0 = spin.apply(cx, cy, x, y);
+45 -3
View File
@@ -49,6 +49,35 @@ impl std::fmt::Debug for MediaIndex {
}
}
/// Failed text-box part allocations recorded while adopting notes/comments, waiting to be merged
/// into the body adoption summary of the same paste (#9918).
#[derive(Clone, Default)]
pub(crate) struct PendingBoxAlloc {
pub(crate) failed: usize,
pub(crate) error: Option<String>,
}
impl PendingBoxAlloc {
pub(crate) fn merge(&mut self, other: PendingBoxAlloc) {
self.failed = self.failed.saturating_add(other.failed);
if self.error.is_none() {
self.error = other.error;
}
}
}
impl PartialEq for PendingBoxAlloc {
fn eq(&self, _: &Self) -> bool {
true
}
}
impl std::fmt::Debug for PendingBoxAlloc {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("PendingBoxAlloc")
}
}
impl Default for Document {
fn default() -> Self {
Document::new()
@@ -76,6 +105,7 @@ impl Document {
passthrough: BTreeMap::new(),
glossary: Vec::new(),
media_index: MediaIndex::default(),
pending_box_alloc: PendingBoxAlloc::default(),
kept: Default::default(),
missing_pictures: Default::default(),
fit_state: None,
@@ -155,6 +185,7 @@ impl Document {
passthrough,
glossary,
media_index: _,
pending_box_alloc: _,
kept: _,
missing_pictures: _,
fit_state: _,
@@ -177,6 +208,7 @@ impl Document {
passthrough: other_passthrough,
glossary: other_glossary,
media_index: _,
pending_box_alloc: _,
kept: _,
missing_pictures: _,
fit_state: _,
@@ -432,6 +464,7 @@ impl Document {
}
let Some(Block::Para(p)) = self.body.get_mut(block).map(Arc::make_mut) else { return false };
let Some(before) = p.section.take() else { return false };
p.touch();
self.section_mut(block).absorb(&before);
true
}
@@ -439,7 +472,10 @@ impl Document {
/// Allocate a new part id and insert the part. Part ids run out only past `u32::MAX` parts, more
/// than memory holds; then nothing is added and the id is 0, which [`free_id`] never gives a part.
pub fn add_part(&mut self, kind: PartKind, blocks: Blocks) -> u32 {
self.try_add_part(kind, blocks).unwrap_or(0)
self.try_add_part(kind, blocks).unwrap_or_else(|e| {
log::error!("add_part: {e}");
0
})
}
/// [`Document::add_part`], or an error, adding nothing, when every part id is taken.
@@ -813,8 +849,14 @@ impl Document {
/// Repair every paragraph's runs (see [`Paragraph::normalize`]); for models from untrusted
/// JSON, whose run lengths may overflow, fall short or split a character.
pub fn normalize_runs(&mut self) {
let mut stories: Vec<&mut Blocks> = vec![&mut self.body];
stories.extend(self.parts.values_mut().map(|p| &mut p.blocks));
let separators = [&mut self.footnote_separators, &mut self.endnote_separators]
.into_iter()
.flat_map(|s| [&mut s.separator, &mut s.continuation_separator, &mut s.continuation_notice])
.flatten();
let stories = std::iter::once(&mut self.body)
.chain(self.parts.values_mut().map(|part| &mut part.blocks))
.chain(separators)
.chain(self.glossary.iter_mut().map(|entry| &mut entry.blocks));
for blocks in stories {
for b in blocks.iter_mut() {
edit::each_para_mut(Arc::make_mut(b), 0, &mut |p: &mut Paragraph| {
+112 -13
View File
@@ -254,6 +254,10 @@ struct BoxBudget {
costs: BTreeMap<u32, usize>,
/// Boxes left without a story because the paste's budget couldn't hold theirs.
skipped: usize,
/// Boxes left without a story because allocating a new part id failed.
alloc_failed: usize,
/// First part-allocation error seen while adopting text boxes, logged once at the end.
alloc_error: Option<String>,
/// A box the fragment has no story for may show this document's story of that id (a
/// fragment copied from this document without its parts). Off for another document's
/// fragment, whose ids mean nothing here.
@@ -262,7 +266,36 @@ struct BoxBudget {
impl BoxBudget {
fn new() -> BoxBudget {
BoxBudget { stories: MAX_PASTED_BOXES, bytes: MAX_PASTED_BOX_BYTES, active: Vec::new(), costs: BTreeMap::new(), skipped: 0, local: true }
BoxBudget {
stories: MAX_PASTED_BOXES,
bytes: MAX_PASTED_BOX_BYTES,
active: Vec::new(),
costs: BTreeMap::new(),
skipped: 0,
alloc_failed: 0,
alloc_error: None,
local: true,
}
}
fn merge_pending(&mut self, pending: crate::document::PendingBoxAlloc) {
self.alloc_failed = self.alloc_failed.saturating_add(pending.failed);
if self.alloc_error.is_none() {
self.alloc_error = pending.error;
}
}
fn into_pending(self) -> crate::document::PendingBoxAlloc {
crate::document::PendingBoxAlloc { failed: self.alloc_failed, error: self.alloc_error }
}
fn warn_alloc_failed(&self) {
if self.alloc_failed > 0 {
let reason = self.alloc_error.as_deref().unwrap_or("no free part id");
let noun = if self.alloc_failed == 1 { "text box is" } else { "text boxes are" };
// Once per paste, not once per box (follow-up to #9854).
log::warn!("adopt_text_box: {} {noun} left empty; cannot add a part: {reason}", self.alloc_failed);
}
}
}
@@ -478,6 +511,8 @@ impl Relink<'_> {
self.shift_change(&mut row.props.fmt_change);
for cell in row.cells.iter_mut() {
self.shift_change(&mut cell.props.fmt_change);
let merge = cell.props.merge_change.take();
cell.props.merge_change = merge.and_then(|m| Some(crate::props::CellMergeChange { rev: self.rev_id(m.rev)?, ..m }));
todo.extend(cell.blocks.iter_mut().map(Arc::make_mut));
}
}
@@ -1205,12 +1240,27 @@ impl Document {
/// `w:matchSrc`): a style whose id we already have comes along under a new id, and its
/// document defaults go into its base styles, which its unstyled paragraphs then use.
pub fn adopt_with(&mut self, src: Document, keep_styles: bool) -> Fragment {
self.adopt_in(src, keep_styles, &mut 0)
self.adopt_with_allocator(src, keep_styles, &mut |doc, blocks| doc.try_add_part(PartKind::TextBox, blocks))
}
fn adopt_with_allocator<F>(&mut self, src: Document, keep_styles: bool, add_part: &mut F) -> Fragment
where
F: FnMut(&mut Self, Blocks) -> Result<u32>,
{
let mut budget = BoxBudget::new();
let frag = self.adopt_in_with(src, keep_styles, &mut 0, &mut budget, add_part);
// Carry note/comment allocation failures into the matching insert_fragment / adopt_fragment
// so one cross-document paste emits a single summary warning (#9918).
self.pending_box_alloc.merge(budget.into_pending());
frag
}
/// [`Self::adopt_with`], its permission range ids from at least `perms` on (and past ours);
/// `perms` moves past them.
fn adopt_in(&mut self, mut src: Document, keep_styles: bool, perms: &mut u32) -> Fragment {
fn adopt_in_with<F>(&mut self, mut src: Document, keep_styles: bool, perms: &mut u32, budget: &mut BoxBudget, add_part: &mut F) -> Fragment
where
F: FnMut(&mut Self, Blocks) -> Result<u32>,
{
let mut renamed = BTreeMap::new();
let mut default_style = None;
if keep_styles {
@@ -1340,12 +1390,11 @@ impl Document {
part.blocks.iter_mut().for_each(|b| link.block(Arc::make_mut(b)));
}
// A note's or comment's text boxes get stories here now; the body's go with the fragment.
let mut budget = BoxBudget::new();
for (old, new) in &notes {
let Some(part) = src.parts.get(old) else { continue };
let mut blocks: Vec<Block> = part.blocks.iter().map(|b| (**b).clone()).collect();
blocks.iter_mut().for_each(|b| link.block(b));
self.adopt_text_boxes(&mut blocks, &parts, 0, &mut budget);
self.adopt_text_boxes_with(&mut blocks, &parts, 0, budget, add_part);
if let Some(p) = self.parts.get_mut(new) {
p.blocks = blocks.into_iter().map(Arc::new).collect();
}
@@ -1367,9 +1416,18 @@ impl Document {
/// id the reader hasn't given out (ranges it holds aren't in this document yet); it moves past
/// the adopted ones.
pub fn adopt_blocks(&mut self, src: Document, keep_styles: bool, perms: &mut u32) -> Vec<Block> {
let Fragment { mut blocks, parts, .. } = self.adopt_in(src, keep_styles, perms);
self.adopt_blocks_with(src, keep_styles, perms, &mut |doc, blocks| doc.try_add_part(PartKind::TextBox, blocks))
}
fn adopt_blocks_with<F>(&mut self, src: Document, keep_styles: bool, perms: &mut u32, add_part: &mut F) -> Vec<Block>
where
F: FnMut(&mut Self, Blocks) -> Result<u32>,
{
let mut budget = BoxBudget::new();
self.adopt_text_boxes(&mut blocks, &parts, 0, &mut budget);
budget.merge_pending(std::mem::take(&mut self.pending_box_alloc));
let Fragment { mut blocks, parts, .. } = self.adopt_in_with(src, keep_styles, perms, &mut budget, add_part);
self.adopt_text_boxes_with(&mut blocks, &parts, 0, &mut budget, add_part);
budget.warn_alloc_failed();
blocks
}
@@ -1577,7 +1635,15 @@ impl Document {
/// Give every text box in `blocks` a new story of its own, copied from `parts` (or, for a
/// fragment without them, from this document's text box of that id). A box whose story can't
/// be found keeps no story rather than showing an unrelated one.
#[cfg(test)]
fn adopt_text_boxes(&mut self, blocks: &mut [Block], parts: &BTreeMap<u32, Part>, depth: usize, budget: &mut BoxBudget) {
self.adopt_text_boxes_with(blocks, parts, depth, budget, &mut |doc, blocks| doc.try_add_part(PartKind::TextBox, blocks));
}
fn adopt_text_boxes_with<F>(&mut self, blocks: &mut [Block], parts: &BTreeMap<u32, Part>, depth: usize, budget: &mut BoxBudget, add_part: &mut F)
where
F: FnMut(&mut Self, Blocks) -> Result<u32>,
{
let mut any = false;
for b in blocks.iter() {
each_para(b, 0, &mut |p| any |= box_ids(p).next().is_some());
@@ -1591,7 +1657,7 @@ impl Document {
for o in p.objects.iter_mut() {
for story in o.text_box_slots() {
if let Some(old) = *story {
*story = self.adopt_text_box(old, parts, depth, budget);
*story = self.adopt_text_box(old, parts, depth, budget, add_part);
changed = true;
}
}
@@ -1607,7 +1673,10 @@ impl Document {
/// text boxes are shared with the source (copy-on-write), the others copied. A box showing a
/// story it is inside, or whose story the paste's budget can't hold, gets none (CWE-400);
/// only that box: a later box with a smaller story is still copied while the budget lasts.
fn adopt_text_box(&mut self, old: u32, parts: &BTreeMap<u32, Part>, depth: usize, budget: &mut BoxBudget) -> Option<u32> {
fn adopt_text_box<F>(&mut self, old: u32, parts: &BTreeMap<u32, Part>, depth: usize, budget: &mut BoxBudget, add_part: &mut F) -> Option<u32>
where
F: FnMut(&mut Self, Blocks) -> Result<u32>,
{
if depth >= MAX_BOX_DEPTH || budget.active.contains(&old) {
return None;
}
@@ -1642,14 +1711,23 @@ impl Document {
each_para(&b, 0, &mut |p| boxes |= box_ids(p).next().is_some());
if boxes {
let mut copy = (*b).clone();
self.adopt_text_boxes(std::slice::from_mut(&mut copy), parts, depth + 1, budget);
self.adopt_text_boxes_with(std::slice::from_mut(&mut copy), parts, depth + 1, budget, add_part);
blocks.push(Arc::new(copy));
} else {
blocks.push(b);
}
}
budget.active.pop();
let id = self.try_add_part(PartKind::TextBox, blocks).ok()?;
let id = match add_part(self, blocks) {
Ok(id) => id,
Err(e) => {
budget.alloc_failed = budget.alloc_failed.saturating_add(1);
if budget.alloc_error.is_none() {
budget.alloc_error = Some(e.to_string());
}
return None;
}
};
if let Some(p) = self.parts.get_mut(&id) {
p.body = body;
}
@@ -1679,6 +1757,13 @@ impl Document {
/// fragment's parts (as a paste does), to place them in this document; a box the fragment
/// has no story for keeps none.
pub fn adopt_fragment(&mut self, frag: &Fragment) -> Vec<Block> {
self.adopt_fragment_with(frag, &mut |doc, blocks| doc.try_add_part(PartKind::TextBox, blocks))
}
fn adopt_fragment_with<F>(&mut self, frag: &Fragment, add_part: &mut F) -> Vec<Block>
where
F: FnMut(&mut Self, Blocks) -> Result<u32>,
{
let media_remap = self.adopt_media(&frag.media);
let mut blocks = frag.blocks.clone();
let mut remapped_parts;
@@ -1690,18 +1775,27 @@ impl Document {
&remapped_parts
};
let mut budget = BoxBudget { local: false, ..BoxBudget::new() };
self.adopt_text_boxes(&mut blocks, parts, 0, &mut budget);
budget.merge_pending(std::mem::take(&mut self.pending_box_alloc));
self.adopt_text_boxes_with(&mut blocks, parts, 0, &mut budget, add_part);
if budget.skipped > 0 {
log::warn!(
"{} text boxes are left empty; their stories are past what one copy brings ({MAX_PASTED_BOXES} stories, {MAX_PASTED_BOX_BYTES} bytes)",
budget.skipped
);
}
budget.warn_alloc_failed();
blocks
}
/// Insert a fragment at `pos`; returns the position after the pasted content.
pub fn insert_fragment(&mut self, pos: &Pos, frag: &Fragment) -> Result<Pos> {
self.insert_fragment_with(pos, frag, &mut |doc, blocks| doc.try_add_part(PartKind::TextBox, blocks))
}
fn insert_fragment_with<F>(&mut self, pos: &Pos, frag: &Fragment, add_part: &mut F) -> Result<Pos>
where
F: FnMut(&mut Self, Blocks) -> Result<u32>,
{
let media_remap = self.adopt_media(&frag.media);
// Tables that would nest deeper than the limit here become their paragraphs (#1596).
let room = MAX_TABLE_DEPTH.saturating_sub(pos.path.depth());
@@ -1710,6 +1804,9 @@ impl Document {
fit_tables(b, room, &mut blocks);
}
if blocks.is_empty() {
let mut budget = BoxBudget::new();
budget.merge_pending(std::mem::take(&mut self.pending_box_alloc));
budget.warn_alloc_failed();
return Ok(pos.clone());
}
let Some(dest_para) = self.para_at(pos) else {
@@ -1722,7 +1819,8 @@ impl Document {
remap_media_in(&mut blocks, &mut parts, &media_remap);
// Pasted text boxes get stories of their own (never shared with the copy's source).
let mut budget = BoxBudget::new();
self.adopt_text_boxes(&mut blocks, &parts, 0, &mut budget);
budget.merge_pending(std::mem::take(&mut self.pending_box_alloc));
self.adopt_text_boxes_with(&mut blocks, &parts, 0, &mut budget, add_part);
if budget.skipped > 0 {
// Once per paste, not once per box (review of #3874).
log::warn!(
@@ -1730,6 +1828,7 @@ impl Document {
budget.skipped
);
}
budget.warn_alloc_failed();
// Single paragraph: inline insert keeping runs.
if blocks.len() == 1
&& let Some(Block::Para(src)) = blocks.first()
+93
View File
@@ -576,6 +576,99 @@ fn a_box_over_the_budget_leaves_later_smaller_boxes_their_stories() {
assert_eq!(budget.costs.len(), 2, "each story costed once");
}
#[test]
fn part_allocation_failure_warns_once_per_paste_with_adopt_text_box_label() {
let small = para_block(Paragraph::with_text("small", CharProps::default()));
let mut p = Paragraph::new();
for _ in 0..3 {
p.insert_object(0, box_shape(Some(1)), &CharProps::default()).unwrap();
}
let mut parts = BTreeMap::new();
parts.insert(1, crate::Part { kind: PartKind::TextBox, blocks: vec![small], body: Default::default() });
let mut blocks = vec![Block::Para(p)];
let mut d = doc(&["x"]);
let mut budget = BoxBudget::new();
let mut remaining = 1usize;
let (_, during) = crate::test_log::warnings(|| {
d.adopt_text_boxes_with(&mut blocks, &parts, 0, &mut budget, &mut |doc, bl| {
if remaining > 0 {
remaining -= 1;
doc.try_add_part(PartKind::TextBox, bl)
} else {
Err(DocError::Invalid("no free part id".into()))
}
});
});
assert!(during.is_empty(), "must not log once per failing box: {during:?}");
let Some(Block::Para(p)) = blocks.first() else { panic!() };
let got: Vec<bool> = p.objects.iter().map(|o| matches!(o, InlineObject::Shape { story: Some(_), .. })).collect();
assert_eq!(got, [true, false, false], "first box allocates, remaining two stay empty");
assert_eq!(budget.alloc_failed, 2);
let (_, summary) = crate::test_log::warnings(|| budget.warn_alloc_failed());
assert_eq!(summary.len(), 1, "must log one summary warning: {summary:?}");
assert!(summary[0].starts_with("adopt_text_box:"), "{summary:?}");
assert!(summary[0].contains("2 text boxes are left empty"), "{summary:?}");
assert!(summary[0].contains("no free part id"), "{summary:?}");
}
#[test]
fn cross_document_paste_combines_note_and_body_alloc_warnings_into_one() {
let make_src = || {
let mut src = Document::new();
let tb1 = src.add_part(PartKind::TextBox, vec![para_block(Paragraph::with_text("note box", CharProps::default()))]);
let tb2 = src.add_part(PartKind::TextBox, vec![para_block(Paragraph::with_text("body box 1", CharProps::default()))]);
let tb3 = src.add_part(PartKind::TextBox, vec![para_block(Paragraph::with_text("body box 2", CharProps::default()))]);
let mut note_para = Paragraph::with_text("fn", CharProps::default());
note_para.insert_object(2, box_shape(Some(tb1)), &CharProps::default()).unwrap();
let fn_id = src.add_part(PartKind::Footnote, vec![para_block(note_para)]);
let mut body_para = Paragraph::with_text("hi", CharProps::default());
body_para
.insert_object(
2,
InlineObject::NoteRef { kind: crate::para::NoteKind::Footnote, id: fn_id, custom: String::new() },
&CharProps::default(),
)
.unwrap();
body_para.insert_object(0, box_shape(Some(tb2)), &CharProps::default()).unwrap();
body_para.insert_object(0, box_shape(Some(tb3)), &CharProps::default()).unwrap();
src.body = vec![para_block(body_para)];
src
};
// adopt_blocks: note + body failures combine into one summary warning.
let mut d = doc(&["x"]);
let mut perms = 1;
let (_, warned) = crate::test_log::warnings(|| {
d.adopt_blocks_with(make_src(), false, &mut perms, &mut |_, _| Err(DocError::Invalid("no free part id".into())))
});
assert_eq!(warned.len(), 1, "adopt_blocks must log once across notes and body: {warned:?}");
assert!(warned[0].starts_with("adopt_text_box: 3 text boxes are left empty"), "{warned:?}");
// adopt_with + insert_fragment: zero warnings during adopt_with, one combined warning on insert_fragment.
let mut d = doc(&["x"]);
let (frag, during_adopt) =
crate::test_log::warnings(|| d.adopt_with_allocator(make_src(), false, &mut |_, _| Err(DocError::Invalid("no free part id".into()))));
assert!(during_adopt.is_empty(), "adopt_with must defer note alloc warnings to paste: {during_adopt:?}");
let (_, during_insert) = crate::test_log::warnings(|| {
d.insert_fragment_with(&Pos::body(0, 1), &frag, &mut |_, _| Err(DocError::Invalid("no free part id".into()))).unwrap()
});
assert_eq!(during_insert.len(), 1, "insert_fragment must log one combined warning: {during_insert:?}");
assert!(during_insert[0].starts_with("adopt_text_box: 3 text boxes are left empty"), "{during_insert:?}");
// adopt_with + adopt_fragment: one combined warning, and pending count is drained.
let mut d = doc(&["x"]);
let (frag, during_adopt) =
crate::test_log::warnings(|| d.adopt_with_allocator(make_src(), false, &mut |_, _| Err(DocError::Invalid("no free part id".into()))));
assert!(during_adopt.is_empty(), "{during_adopt:?}");
let (_, during_frag) = crate::test_log::warnings(|| d.adopt_fragment_with(&frag, &mut |_, _| Err(DocError::Invalid("no free part id".into()))));
assert_eq!(during_frag.len(), 1, "adopt_fragment must log one combined warning: {during_frag:?}");
assert!(during_frag[0].starts_with("adopt_text_box: 3 text boxes are left empty"), "{during_frag:?}");
// A subsequent paste with no failures must not re-log the drained note failures.
let (_, after) = crate::test_log::warnings(|| d.adopt_fragment(&Fragment::from_text("ok")));
assert!(after.is_empty(), "{after:?}");
}
#[test]
fn many_boxes_sharing_one_story_paste_with_their_text() {
// Review of #3874: a document converted from PDF has thousands of boxes showing story
+4
View File
@@ -138,6 +138,10 @@ pub struct Document {
/// by `==`).
#[serde(skip)]
media_index: MediaIndex,
/// Text-box part allocation failures from note/comment adoption carried into the matching
/// fragment paste so one cross-document paste logs once (#9918); never saved, ignored by `==`.
#[serde(skip)]
pub(crate) pending_box_alloc: document::PendingBoxAlloc,
/// Markup kept from the file it was opened from, for writing back what isn't edited (see
/// [`kept`]); never saved, ignored by `==`.
#[serde(skip)]
+184 -10
View File
@@ -87,6 +87,10 @@ pub struct AbstractNum {
/// `None`: derived from the levels.
#[serde(skip_serializing_if = "Option::is_none")]
pub multi_level_type: Option<String>,
/// The list starts over after each section break, continuous or not (Word 2013's
/// `w15:restartNumberingAfterBreak`; measured in Word for Windows, #7382).
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub restart_after_section_break: bool,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
@@ -288,7 +292,10 @@ impl Numbering {
/// Create a new list of `kind`; returns the `num` id. List ids run out only past `u32::MAX`
/// lists, more than memory holds; then nothing is added and the id is 0, "no list".
pub fn add_list(&mut self, kind: ListKind) -> u32 {
self.try_add_list(kind).unwrap_or(0)
self.try_add_list(kind).unwrap_or_else(|e| {
log::error!("add_list: {e}");
0
})
}
/// [`Numbering::add_list`], or an error, adding nothing, when list ids are all taken.
pub fn try_add_list(&mut self, kind: ListKind) -> crate::Result<u32> {
@@ -337,8 +344,8 @@ impl Numbering {
pub struct Counters {
/// Per abstract list: current value per level.
state: HashMap<u32, [u32; 9]>,
/// Which levels of which nums have started: a num's start override for a level applies
/// once, when that level of that num is first used (ECMA-376 Part 1, 17.9.27 startOverride).
/// Which levels of which nums have started: a num's start override for a level applies on
/// first use and again at each restart by that list (ECMA-376 Part 1, 17.9.27 startOverride).
seen: HashMap<(u32, u8), bool>,
/// Per abstract list: whether each level has counted yet (a value of 0 can be a real count when a
/// level starts at 0).
@@ -381,12 +388,33 @@ impl Counters {
self.next_label_from(n, abs, level)
}
/// A section ends: the lists that start over after a section break
/// ([`AbstractNum::restart_after_section_break`]) do, every level, as if not used yet. A
/// list's start overrides aren't applied again: after the break it counts from its levels'
/// starts (measured in Word for Windows, #7382). Walks that count labels in document order
/// call it after each paragraph that ends a section.
pub fn section_break(&mut self, numbering: &Numbering) {
for a in numbering.abstracts.iter().filter(|a| a.restart_after_section_break) {
self.state.remove(&a.id);
self.flags.remove(&a.id);
self.labels.retain(|(id, _), _| *id != a.id);
}
}
/// Like [`Self::values`], using one walk's borrowed definition index.
pub fn values_indexed(&self, numbering: &NumberingIndex<'_>, num: u32) -> Option<[u32; 9]> {
let abs = numbering.abstract_of(num)?;
Some(self.state.get(&abs.id).copied().unwrap_or([0; 9]))
}
/// The values counted so far for `num`, including implicitly counted ancestors and zero starts.
/// An unstarted level has no value even when its definition has a default start.
pub fn counted_values_indexed(&self, numbering: &NumberingIndex<'_>, num: u32) -> [Option<u32>; 9] {
let Some(abs) = numbering.abstract_of(num) else { return [None; 9] };
let (Some(values), Some(flags)) = (self.state.get(&abs.id), self.flags.get(&abs.id)) else { return [None; 9] };
std::array::from_fn(|level| flags[level].started.then_some(values[level]))
}
fn next_label_from(&mut self, n: &Num, abs: &AbstractNum, level: u8) -> Option<(String, Level)> {
let num = n.id;
let lv = (level as usize).min(8);
@@ -395,6 +423,13 @@ impl Counters {
// A "none" level (Word's numFmt none) still counts and restarts the levels below it; only
// its number reads as nothing, so its literal text ("RESPONSE:") shows (#4985).
let def = level_def(lv)?.clone();
// A level not restarted yet counts from its abstract list's start: one this list defines
// itself counts on with the abstract list. A level a paragraph of this list restarts, by
// counting above it, starts again at this list's start override for it, every time, or
// else at the start of this list's definition of it (measured in Word for Windows, #7381).
let start_of = |k: usize| abs.levels.get(k).or_else(|| level_def(k)).map_or(1, |l| l.start);
let restart_at =
|k: usize| n.start_overrides.iter().find(|(l, _)| *l as usize == k).map(|(_, s)| *s).or_else(|| level_def(k).map(|l| l.start));
let st = self.state.entry(abs.id).or_insert([0; 9]);
let fl = self.flags.entry(abs.id).or_default();
// Only this level's override, not the num's others: the counters are shared by every
@@ -425,11 +460,11 @@ impl Counters {
}
std::collections::hash_map::Entry::Occupied(_) => None,
};
*v = start.or(f.first).unwrap_or_else(|| level_def(k).map_or(1, |l| l.start));
*v = start.or(f.first).unwrap_or_else(|| start_of(k));
*f = LevelFlags { started: true, first: None };
}
if let (Some(v), Some(f)) = (st.get_mut(lv), fl.get_mut(lv)) {
*v = if f.started { v.saturating_add(1) } else { f.first.unwrap_or(def.start) };
*v = if f.started { v.saturating_add(1) } else { f.first.unwrap_or_else(|| start_of(lv)) };
*f = LevelFlags { started: true, first: None };
}
// Deeper levels restart, unless they never restart or only restart after a level above
@@ -438,7 +473,7 @@ impl Counters {
let restarts = level_def(d).is_none_or(|l| l.restart && l.restart_after.is_none_or(|k| lv < k as usize));
if restarts {
*deeper = 0;
*f = LevelFlags::default();
*f = LevelFlags { started: false, first: restart_at(d) };
self.labels.remove(&(abs.id, d as u8));
}
}
@@ -493,16 +528,19 @@ impl Counters {
}
}
fn placeholder_level(digit: char) -> Option<usize> {
digit.to_digit(10).filter(|d| (1..=9).contains(d)).map(|d| (d - 1) as usize)
}
/// The zero-based levels a label template shows (`"%1.%2"` → `[0, 1]`, `"(%3)"` → `[2]`).
pub fn template_levels(text: &str) -> Vec<usize> {
let mut out = Vec::new();
let mut chars = text.chars().take(MAX_LEVEL_TEXT).peekable();
while let Some(c) = chars.next() {
if c == '%'
&& let Some(d) = chars.peek().and_then(|d| d.to_digit(10))
&& let Some(k) = chars.peek().copied().and_then(placeholder_level)
{
chars.next();
let k = (d as usize).saturating_sub(1).min(8);
if !out.contains(&k) {
out.push(k);
}
@@ -518,10 +556,9 @@ fn render_label<'a>(level_def: impl Fn(usize) -> Option<&'a Level>, def: &Level,
let mut chars = def.text.chars().take(MAX_LEVEL_TEXT).peekable();
while let Some(c) = chars.next() {
if c == '%'
&& let Some(d) = chars.peek().and_then(|d| d.to_digit(10))
&& let Some(k) = chars.peek().copied().and_then(placeholder_level)
{
chars.next();
let k = (d as usize).saturating_sub(1).min(8);
let val = vals.get(k).copied().unwrap_or(0);
let counted = started.get(k).is_some_and(|f| f.started);
let level = level_def(k);
@@ -592,13 +629,66 @@ mod tests {
assert_eq!(counters.started(&numbering, second_id).unwrap()[..2], [true, true]);
}
/// #7381: a level a list defines itself (Word's lvlOverride/lvl) counts on with its abstract
/// list, from the abstract list's start; its own start counts with a start override, which
/// restarts the level there (measured in Word for Windows: 5. F. G. 8. I. and 5. C. D. 5. F.).
#[test]
fn a_level_a_list_defines_itself_counts_on_with_its_abstract_list() {
for (overrides, want) in [(vec![], ["5.", "F.", "G.", "8.", "I."]), (vec![(0, 3)], ["5.", "C.", "D.", "5.", "F."])] {
let mut n = Numbering::default();
let first = n.add_list(ListKind::Numbered);
let abs = n.num(first).unwrap().abstract_id;
n.abstracts.iter_mut().find(|a| a.id == abs).unwrap().levels[0].start = 5;
let letters = Level { format: NumFormat::UpperLetter, text: "%1.".into(), start: 3, ..Level::default() };
let second = n.free_num_id().unwrap();
n.nums.push(Num { id: second, abstract_id: abs, start_overrides: overrides.clone(), level_overrides: vec![(0, letters)] });
let labels = |order: &[u32]| {
let mut c = Counters::default();
order.iter().map(|id| c.next_label(&n, *id, 0).unwrap().0).collect::<Vec<String>>()
};
assert_eq!(labels(&[first, second, second, first, second]), want, "{overrides:?}");
if overrides.is_empty() {
// Used first, it starts at the abstract list's 5, not its own 3: E. F. 7. H.
assert_eq!(labels(&[second, second, first, second]), ["E.", "F.", "7.", "H."]);
}
}
}
/// A level 2 that list 2 defines itself (upper letters from 3, the abstract list's from 5)
/// starts at the abstract list's start until a level 1 restarts it, and then at the start the
/// restarting paragraph's list gives it: its start override, every time, or its own
/// definition's start (measured in Word for Windows, #7381).
#[test]
fn a_restarted_level_starts_where_the_restarting_list_says() {
let lvl = |format, text: &str, start| Level { format, text: text.into(), start, ..Level::default() };
let case = |overrides: Vec<(u8, u32)>, own: Option<Level>, items: &[(u32, u8)]| {
let mut n = Numbering::default();
let plain = n.try_add_levels(None, vec![lvl(NumFormat::Decimal, "%1.", 1), lvl(NumFormat::UpperLetter, "%2)", 5)]).unwrap();
let abs = n.num(plain).unwrap().abstract_id;
let id = n.free_num_id().unwrap();
n.nums.push(Num { id, abstract_id: abs, start_overrides: overrides, level_overrides: own.into_iter().map(|l| (1, l)).collect() });
let mut c = Counters::default();
items.iter().map(|&(list, level)| c.next_label(&n, if list == 1 { plain } else { id }, level).unwrap().0).collect::<Vec<String>>()
};
let own = || Some(lvl(NumFormat::UpperLetter, "%2)", 3));
let nested = [(2, 0), (2, 1), (2, 1), (2, 0), (2, 1)];
assert_eq!(case(vec![], own(), &nested), ["1.", "C)", "D)", "2.", "C)"]);
assert_eq!(case(vec![(1, 3)], own(), &nested), ["1.", "C)", "D)", "2.", "C)"]);
assert_eq!(case(vec![(1, 7)], None, &nested), ["1.", "G)", "H)", "2.", "G)"], "the override again at each restart");
assert_eq!(case(vec![], own(), &[(2, 1), (2, 1), (2, 0), (2, 1)]), ["E)", "F)", "2.", "C)"], "not restarted yet");
assert_eq!(case(vec![], own(), &[(1, 0), (2, 1), (2, 1), (1, 0), (2, 1)]), ["1.", "E)", "F)", "2.", "E)"], "restarted by the plain list");
assert_eq!(case(vec![], own(), &[(2, 0), (1, 1), (2, 1), (2, 0), (1, 1)]), ["1.", "C)", "D)", "2.", "C)"], "restarted by list 2");
}
#[test]
fn a_huge_level_text_gives_a_bounded_label() {
let mut n = Numbering::default();
let id = n.add_list(ListKind::Numbered);
let huge = Level { format: NumFormat::UpperRoman, text: "%1".repeat(30_000), start: u32::MAX, ..Level::default() };
if let Some(num) = n.nums.iter_mut().find(|x| x.id == id) {
// The level's own start counts with a start override (as Word's lvlOverride reads).
num.level_overrides = vec![(0, huge)];
num.start_overrides = vec![(0, u32::MAX)];
}
let mut c = Counters::default();
let label = c.next_label(&n, id, 0).unwrap().0;
@@ -827,6 +917,35 @@ mod tests {
assert_eq!(n.find_kind(ListKind::Bullet), Some(b));
}
#[test]
fn a_list_flagged_to_restart_after_a_section_break_starts_over_there() {
let mut n = Numbering::default();
let flagged = n.add_list(ListKind::Numbered);
let abs = n.num(flagged).unwrap().abstract_id;
n.abstracts.iter_mut().find(|a| a.id == abs).unwrap().restart_after_section_break = true;
let mut other_levels = n.abstract_of(flagged).unwrap().levels.clone();
other_levels[0].text = "(%1)".into();
let other = n.try_add_levels(None, other_levels).unwrap();
// The same list's other instance, with a start override it applies once.
let overridden = n.free_num_id().unwrap();
n.nums.push(Num { id: overridden, abstract_id: abs, start_overrides: vec![(0, 5)], ..Default::default() });
let mut c = Counters::default();
let next = |c: &mut Counters, num, level| c.next_label(&n, num, level).unwrap().0;
assert_eq!([next(&mut c, flagged, 0), next(&mut c, flagged, 0), next(&mut c, other, 0)], ["1.", "2.", "(1)"]);
next(&mut c, flagged, 1);
c.section_break(&n);
// Every level of the flagged list starts over; the other list goes on.
assert_eq!(c.values(&n, flagged), Some([0; 9]));
assert_eq!(next(&mut c, other, 0), "(2)");
next(&mut c, flagged, 1);
assert_eq!(c.values(&n, flagged).unwrap()[..2], [1, 1], "the level above counts its first number");
assert_eq!(next(&mut c, flagged, 0), "2.");
// An override already used isn't applied again after a break.
assert_eq!(next(&mut c, overridden, 0), "5.");
c.section_break(&n);
assert_eq!(next(&mut c, overridden, 0), "1.");
}
#[test]
fn restart_keeps_the_list_s_own_level_definitions() {
let mut n = Numbering::default();
@@ -842,6 +961,61 @@ mod tests {
assert_eq!(c.next_label(&n, r, 0).unwrap().0, "Part V");
}
#[test]
fn start_zero_counters_increment_properly() {
let mut n = Numbering::default();
let id = n.add_list(ListKind::Numbered);
if let Some(a) = n.abstracts.first_mut() {
a.levels[0].start = 0;
a.levels[0].text = "Item %1.".into();
}
let mut c = Counters::default();
assert_eq!(c.next_label(&n, id, 0).unwrap().0, "Item 0.");
assert_eq!(c.next_label(&n, id, 0).unwrap().0, "Item 1.");
assert_eq!(c.next_label(&n, id, 0).unwrap().0, "Item 2.");
}
#[test]
fn start_override_of_zero_starts_at_zero() {
let mut n = Numbering::default();
let id = n.add_list(ListKind::Numbered);
if let Some(num) = n.nums.iter_mut().find(|x| x.id == id) {
num.start_overrides = vec![(0, 0)];
}
let mut c = Counters::default();
let labels: Vec<String> = (0..3).map(|_| c.next_label(&n, id, 0).unwrap().0).collect();
assert_eq!(labels, ["0.", "1.", "2."]);
}
#[test]
fn a_counted_zero_ancestor_replaces_the_unstarted_fallback() {
let mut numbering = Numbering::default();
let num = numbering.add_list(ListKind::Numbered);
numbering.abstracts[0].levels[0].start = 7;
numbering.abstracts[0].levels[1] = Level { text: "%1.%2.".into(), ..Default::default() };
numbering.nums[0].start_overrides = vec![(0, 0)];
let index = NumberingIndex::new(&numbering);
let mut counters = Counters::default();
assert_eq!(counters.counted_values_indexed(&index, num)[0], None);
assert_eq!(counters.current_label(&numbering, num, 1).as_deref(), Some("7.1."));
let (label, _) = counters.next_label_indexed(&index, num, 1).unwrap();
assert_eq!(label, "0.1.");
assert_eq!(counters.counted_values_indexed(&index, num)[0], Some(0));
}
#[test]
fn placeholder_percent_zero_is_preserved_as_literal() {
let mut n = Numbering::default();
let id = n.add_list(ListKind::Numbered);
if let Some(a) = n.abstracts.first_mut() {
a.levels[0].text = "%0 %1.".into();
}
let mut c = Counters::default();
assert_eq!(c.next_label(&n, id, 0).unwrap().0, "%0 1.");
assert_eq!(template_levels("%0 %2. %9 %2"), [1, 8]);
}
#[test]
fn definition_index_keeps_first_ids_overrides_and_missing_definitions() {
let override_level = Level { start: 0, text: "own %1".into(), ..Default::default() };
+1 -1
View File
@@ -18,7 +18,7 @@ mod inline_kinds;
mod inline_object;
mod run;
pub use float::{AltText, Anchor, Float, FloatAlign, MAX_ALT_TEXT, Wrap, WrapText, cap_alt};
pub use float::{AltText, Anchor, Float, FloatAlign, MAX_ALT_TEXT, MAX_SHARE_LEN, RelSize, SizeFrom, Wrap, WrapText, cap_alt};
pub use inline_kinds::{NoteKind, PTabAlign, PTabBase, RubyAlign, ShapeKind, ruby_offset, ruby_raise};
pub use inline_object::{CanvasStyle, GroupChild, InlineObject, MAX_GROUP_CHILDREN};
pub use run::{COLUMN_BREAK, LINE_BREAK, NB_HYPHEN, NBSP, OBJ, PAGE_BREAK, Run, SOFT_HYPHEN, next_rev};
+47
View File
@@ -103,6 +103,46 @@ pub enum FloatAlign {
Outside,
}
/// What an anchored object's relative width or height is a share of (`relativeFrom` of
/// `wp14:sizeRelH` and `wp14:sizeRelV`, [MS-ODRAWXML]). As craft-wordmodel's, which the DOCX
/// bridge carries it from.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum SizeFrom {
/// The page's text area (the page less its margins).
Margin,
Page,
LeftMargin,
RightMargin,
TopMargin,
BottomMargin,
InsideMargin,
OutsideMargin,
}
/// An anchored object's width or height as a share of the page or a margin (`wp14:sizeRelH` with
/// `wp14:pctWidth`, `wp14:sizeRelV` with `wp14:pctHeight`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RelSize {
pub from: SizeFrom,
/// Thousandths of a percent: 100000 is the whole length. 0 leaves the object its own size, as
/// Word does.
pub pct: u32,
}
/// Longest side a share of the page or a margin gives an object, points: ten times the largest
/// page Word makes (22 inches), the most a share reaches (1000 %, as Word reads it). It bounds a
/// group's members as the group scales them too, not the 4000 pt an object's own size stops at.
pub const MAX_SHARE_LEN: f32 = 15_840.0;
impl RelSize {
/// The length this share gives of `base` (points), `None` for a share of 0.
pub fn of(self, base: f32) -> Option<f32> {
(self.pct > 0).then(|| base.max(0.0) * self.pct as f32 / 100_000.0)
}
}
impl FloatAlign {
/// From an OOXML alignment (`wp:align`, `w:tblpXSpec`, `w:tblpYSpec`).
pub fn from_ooxml(v: &str) -> Option<FloatAlign> {
@@ -191,6 +231,13 @@ pub struct Float {
/// drawing on its anchor paragraph's page.
#[serde(skip_serializing_if = "is_zero_u32")]
pub page: u32,
/// The width and the height as a share of the page or a margin (`wp14:sizeRelH`,
/// `wp14:sizeRelV`), which Word sizes the object by instead of its own size: a cover page's
/// sidebar is as tall as any page (#6770). See [`RelSize`].
#[serde(skip_serializing_if = "Option::is_none")]
pub rel_w: Option<RelSize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub rel_h: Option<RelSize>,
/// Turned, but the file keeps no room for the turn (`wp:effectExtent` missing or zero, as
/// files from other tools have): Word then keeps an inline one's line to its frame and lets
/// the turned object overhang it (see [`Float::line_pad`]). Cleared by [`Float::set_spin`].
+18 -2
View File
@@ -258,8 +258,19 @@ impl InlineObject {
_ => None,
}
}
/// Resize a drawing (a group's members scale with it; a canvas's keep their size and place).
/// Resize a drawing (a group's members scale with it; a canvas's keep their size and place). A
/// side whose size changes loses a share of the page or a margin it had (`Float::rel_w`,
/// `Float::rel_h`), which would otherwise size it instead.
pub fn set_size(&mut self, nw: f32, nh: f32) {
let old = self.frame().map(|(w, h, _)| (w, h));
if let (Some((ow, oh)), Some(f)) = (old, self.float_mut()) {
if ow != nw {
f.rel_w = None;
}
if oh != nh {
f.rel_h = None;
}
}
if let InlineObject::Image { w, h, .. }
| InlineObject::Graphic { w, h, .. }
| InlineObject::Shape { w, h, .. }
@@ -352,7 +363,12 @@ impl InlineObject {
.enumerate()
.filter_map(|(i, c)| {
let (cw, chh, _) = c.obj.frame()?;
let r = [x + fin(c.x) * sx, y + fin(c.y) * sy, (fin(cw) * sx).clamp(0.0, 4000.0), (fin(chh) * sy).clamp(0.0, 4000.0)];
let r = [
x + fin(c.x) * sx,
y + fin(c.y) * sy,
(fin(cw) * sx).clamp(0.0, super::MAX_SHARE_LEN),
(fin(chh) * sy).clamp(0.0, super::MAX_SHARE_LEN),
];
(!matches!(c.obj, InlineObject::Group { .. })).then_some((i, r))
})
.collect()
+2 -2
View File
@@ -32,8 +32,8 @@ pub use para_props::{
TextAlignment, TextFrame,
};
pub use table_props::{
CellPicture, CellProps, HeightRule, PictureRepeat, RowProps, TableFloat, TableLook, TableProps, TextDirection, TextVert, VAlign, VMerge,
anchor_ooxml, valign_from_anchor,
CellMergeChange, CellPicture, CellProps, HeightRule, MergeMark, PictureRepeat, RowProps, TableFloat, TableLook, TableProps, TextDirection,
TextVert, VAlign, VMerge, anchor_ooxml, valign_from_anchor,
};
#[cfg(test)]
+46
View File
@@ -300,12 +300,58 @@ pub struct CellProps {
/// Tracked formatting change (`w:tcPrChange`).
#[serde(skip_serializing_if = "Option::is_none")]
pub fmt_change: Option<Box<PropChange<CellProps>>>,
/// Tracked vertical merge or split of the cell (`w:cellMerge`).
#[serde(skip_serializing_if = "Option::is_none")]
pub merge_change: Option<CellMergeChange>,
/// A picture behind the cell's content (an ODF cell's `style:background-image`; Word has
/// none).
#[serde(skip_serializing_if = "Option::is_none")]
pub picture: Option<Box<CellPicture>>,
}
/// A tracked vertical merge or split of a table cell (ECMA-376 §17.13.5.3, `w:cellMerge`): the
/// revision that made it, and the cell's vertical merge after it (`w:vMerge`) and before it
/// (`w:vMergeOrig`). The table already shows the change. Word for Windows lists one with
/// `w:vMerge` as merged cells and one without as split cells. Accepting or rejecting it drops
/// only the record: the cells stay as they are.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct CellMergeChange {
/// Index into `Document::revisions`.
pub rev: u32,
#[serde(skip_serializing_if = "Option::is_none")]
pub v_merge: Option<MergeMark>,
#[serde(skip_serializing_if = "Option::is_none")]
pub v_merge_orig: Option<MergeMark>,
}
/// A cell's vertical merge in a tracked merge or split (`ST_AnnotationVMerge`): it continues the
/// merge from the cell above (`cont`) or starts one (`rest`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum MergeMark {
Continue,
Restart,
}
impl MergeMark {
pub fn ooxml(self) -> &'static str {
match self {
MergeMark::Continue => "cont",
MergeMark::Restart => "rest",
}
}
/// The value for `s`, `None` for one the schema doesn't have.
pub fn from_ooxml(s: &str) -> Option<MergeMark> {
match s {
"cont" => Some(MergeMark::Continue),
"rest" => Some(MergeMark::Restart),
_ => None,
}
}
}
/// A cell's background picture: drawn at its own size where `align` puts it, tiled, or stretched
/// over the cell, and cut off at the cell's edges.
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
+10 -2
View File
@@ -773,6 +773,10 @@ pub struct SectionProps {
pub page_w: f32,
pub page_h: f32,
pub landscape: bool,
/// Top and bottom margins, points. Negative is Word's exact margin (`w:pgMar` `w:top` /
/// `w:bottom` below zero, ECMA-376 §17.6.11; DOC `dyaTop` / `dyaBottom`): the text starts
/// (ends) at the absolute value from the page edge even when the header (footer) is taller,
/// and overlaps it.
pub margin_top: f32,
pub margin_bottom: f32,
pub margin_left: f32,
@@ -912,17 +916,21 @@ impl SectionProps {
pub fn text_width(&self) -> f32 {
(self.page_w - self.margin_left - self.margin_right - self.gutter).max(18.0)
}
/// Height of the text area between the margins, points (a negative, exact margin counts at
/// its size).
pub fn text_height(&self) -> f32 {
(self.page_h - self.margin_top - self.margin_bottom).max(18.0)
(self.page_h - self.margin_top.abs() - self.margin_bottom.abs()).max(18.0)
}
/// Swap to landscape/portrait (keeps margins relative to the paper as Word does: rotates them).
/// An exact (negative) top or bottom turns into a side at its size, as in Word: only the top
/// and bottom can be exact.
pub fn set_landscape(&mut self, on: bool) {
if on == self.landscape {
return;
}
self.landscape = on;
std::mem::swap(&mut self.page_w, &mut self.page_h);
let (t, b, l, r) = (self.margin_top, self.margin_bottom, self.margin_left, self.margin_right);
let (t, b, l, r) = (self.margin_top.abs(), self.margin_bottom.abs(), self.margin_left, self.margin_right);
if on {
self.margin_top = l;
self.margin_bottom = r;
+24
View File
@@ -216,6 +216,8 @@ impl Table {
for c in &src.cells {
let mut nc = Cell::empty();
nc.props = c.props.clone();
// A tracked merge or split is the source cell's own: the new one has none.
nc.props.merge_change = None;
if nc.props.vmerge == VMerge::Restart {
nc.props.vmerge = VMerge::None;
}
@@ -596,6 +598,7 @@ impl Table {
for (i, cell) in src.cells.iter_mut().enumerate() {
let mut nc = Cell::empty();
nc.props = cell.props.clone();
nc.props.merge_change = None;
if i == ci {
cell.props.vmerge = VMerge::None;
nc.props.vmerge = VMerge::None;
@@ -830,4 +833,25 @@ mod tests {
assert_eq!(v.rows[0].cells[0].props.vmerge, VMerge::Restart);
assert_eq!(v.rows[2].cells[0].props.vmerge, VMerge::Continue);
}
/// A tracked merge or split of a cell stays with that cell: a row inserted beside it, or the rows
/// a cell is split into, are new cells the revision never touched.
#[test]
fn new_cells_take_no_tracked_cell_merge() {
use crate::props::{CellMergeChange, MergeMark};
let merged = Some(CellMergeChange { rev: 0, v_merge: None, v_merge_orig: Some(MergeMark::Continue) });
let mut t = Table::new(2, 2, 144.0);
for row in &mut t.rows {
for c in &mut row.cells {
c.props.merge_change = merged;
}
}
t.insert_row(1, 0);
assert_eq!(t.rows.len(), 3);
assert!(t.rows[1].cells.iter().all(|c| c.props.merge_change.is_none()), "the inserted row");
assert!(t.rows[0].cells.iter().all(|c| c.props.merge_change == merged), "the row it was copied from keeps its record");
assert!(t.split_cell_grid(0, 0, 1, 2));
let records = t.rows.iter().map(|r| r.cells.iter().filter(|c| c.props.merge_change.is_some()).count()).collect::<Vec<_>>();
assert_eq!(records, [2, 0, 0, 2], "the row the split adds takes none");
}
}
+19
View File
@@ -959,6 +959,25 @@ fn normalize_runs_reconciles_objects_with_markers() {
// Deleting the first marker keeps B on the second.
p.delete(1, 4).unwrap();
assert_eq!(p.objects, vec![fs("B")]);
let mut d = build();
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
p.objects.push(fs("Surplus"));
p.runs[0].len = 1;
d.footnote_separators.continuation_notice = Some(d.body.clone());
d.endnote_separators.separator = Some(d.body.clone());
d.glossary.push(BuildingBlock { name: "Quick Parts example".into(), blocks: d.body.clone(), ..Default::default() });
d.normalize_runs();
for (name, blocks) in [
("footnote continuation notice", d.footnote_separators.continuation_notice.as_ref().unwrap()),
("endnote separator", d.endnote_separators.separator.as_ref().unwrap()),
("Quick Parts entry", &d.glossary[0].blocks),
] {
edit::each_para(&blocks[0], 0, &mut |p| {
assert_eq!(p.objects, vec![fs("A"), fs("B")], "{name} drops the surplus object");
assert_eq!(p.runs.iter().map(|r| r.len).sum::<usize>(), p.text.len(), "{name} repairs its runs");
});
}
// The cost is linear: the markers and runs `reconcile_objects` walks (`crate::work`), not a
// timing. 8x the unmatched markers cost about 8x the steps, far more if each removal rescans.
let reconcile = |extra: usize| {
+3
View File
@@ -189,6 +189,9 @@ pub(crate) fn story_word_count_of(
total = total.saturating_add(count_label_words(&label));
}
total = total.saturating_add(count_words(&p.plain_text()));
if p.section.is_some() {
counters.section_break(numbering);
}
}
Block::Table(t) => {
for row in &t.rows {
+1 -1
View File
@@ -15,13 +15,13 @@ wordcraft-doc = { workspace = true }
craft-xml = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
[dev-dependencies]
wordcraft-doc = { workspace = true, features = ["test-support"] }
wordcraft-geom = { workspace = true, features = ["image"] }
base64 = { workspace = true }
cfb = { workspace = true }
log = { workspace = true }
proptest = { workspace = true }
image = { workspace = true }
craft-zip = { workspace = true }
+15 -3
View File
@@ -57,7 +57,13 @@ pub fn read_with(bytes: &[u8], opts: &ReadOptions) -> Result<wordcraft_doc::Docu
let importer = opts.chunks?;
let chunk = AltChunk { content_type: shared_chunk.content_type, part: shared_chunk.part, bytes: shared_chunk.bytes };
let doc = importer(&chunk)?;
to_shared_model(&doc).ok()
match to_shared_model(&doc) {
Ok(shared) => Some(shared),
Err(e) => {
log::warn!("docx: dropping alt chunk {}: {e}", chunk.part);
None
}
}
};
let shared_opts =
@@ -106,7 +112,10 @@ pub fn chart_items(spec: &wordcraft_doc::chart::ChartSpec, theme: &[wordcraft_do
return Vec::new();
};
let shared_items = craft_docx::chart_items(&shared_spec, &shared_theme, w, h);
model_bridge::convert(shared_items).unwrap_or_default()
model_bridge::convert(shared_items).unwrap_or_else(|e| {
log::warn!("docx: chart items could not be converted: {e}");
Vec::new()
})
}
/// Write a chart part.
@@ -131,7 +140,10 @@ pub fn smart_art_items(
return Vec::new();
};
let shared_items = craft_docx::smart_art_items(&shared_spec, &shared_theme, w, h);
model_bridge::convert(shared_items).unwrap_or_default()
model_bridge::convert(shared_items).unwrap_or_else(|e| {
log::warn!("docx: smart art items could not be converted: {e}");
Vec::new()
})
}
/// Read bibliography sources from a `b:Sources` file.
+78
View File
@@ -93,6 +93,84 @@ fn run_and_style_snap_to_grid_and_web_hidden_survive_two_saves() {
}
}
/// Keeps run and style emphasis values intact across repeated DOCX saves.
#[test]
fn run_and_style_emphasis_marks_survive_two_saves() {
use wordcraft_doc::props::EmphasisMark;
let styles = r#"
<w:style w:type="character" w:styleId="Dot"><w:rPr><w:em w:val="dot"/></w:rPr></w:style>
<w:style w:type="character" w:styleId="Comma"><w:rPr><w:em w:val="comma"/></w:rPr></w:style>
<w:style w:type="character" w:styleId="Circle"><w:rPr><w:em w:val="circle"/></w:rPr></w:style>
<w:style w:type="character" w:styleId="UnderDot"><w:rPr><w:em w:val="underDot"/></w:rPr></w:style>
<w:style w:type="character" w:styleId="NoMark"><w:rPr><w:em w:val="none"/></w:rPr></w:style>
"#;
let body = r#"
<w:p>
<w:r><w:rPr><w:rStyle w:val="Dot"/></w:rPr><w:t>default dot</w:t></w:r>
<w:r><w:rPr><w:rStyle w:val="Comma"/></w:rPr><w:t>comma</w:t></w:r>
<w:r><w:rPr><w:rStyle w:val="Circle"/></w:rPr><w:t>circle</w:t></w:r>
<w:r><w:rPr><w:rStyle w:val="UnderDot"/></w:rPr><w:t>under dot</w:t></w:r>
<w:r><w:rPr><w:rStyle w:val="Dot"/><w:em w:val="none"/></w:rPr><w:t>explicit none</w:t></w:r>
<w:r><w:rPr><w:rStyle w:val="NoMark"/></w:rPr><w:t>style none</w:t></w:r>
<w:r><w:rPr><w:em w:val="dot"/></w:rPr><w:t>run dot</w:t></w:r>
<w:r><w:rPr><w:em w:val="comma"/></w:rPr><w:t>run comma</w:t></w:r>
<w:r><w:rPr><w:em w:val="circle"/></w:rPr><w:t>run circle</w:t></w:r>
<w:r><w:rPr><w:em w:val="underDot"/></w:rPr><w:t>run under dot</w:t></w:r>
<w:r><w:rPr><w:em w:val="none"/></w:rPr><w:t>run none</w:t></w:r>
<w:r><w:t>inherit absent</w:t></w:r>
</w:p>
"#;
let mut doc = wordcraft_docx::read(&docx(body, styles)).unwrap();
let expected_styles = [
("Dot", Some(EmphasisMark::Dot)),
("Comma", Some(EmphasisMark::Comma)),
("Circle", Some(EmphasisMark::Circle)),
("UnderDot", Some(EmphasisMark::UnderDot)),
("NoMark", Some(EmphasisMark::None)),
];
let expected_runs = [
(Some("Dot"), None, EmphasisMark::Dot),
(Some("Comma"), None, EmphasisMark::Comma),
(Some("Circle"), None, EmphasisMark::Circle),
(Some("UnderDot"), None, EmphasisMark::UnderDot),
(Some("Dot"), Some(EmphasisMark::None), EmphasisMark::None),
(Some("NoMark"), None, EmphasisMark::None),
(None, Some(EmphasisMark::Dot), EmphasisMark::Dot),
(None, Some(EmphasisMark::Comma), EmphasisMark::Comma),
(None, Some(EmphasisMark::Circle), EmphasisMark::Circle),
(None, Some(EmphasisMark::UnderDot), EmphasisMark::UnderDot),
(None, Some(EmphasisMark::None), EmphasisMark::None),
(None, None, EmphasisMark::None),
];
let assert_state = |doc: &wordcraft_doc::Document, stage: &str| {
for (id, mark) in expected_styles {
assert_eq!(doc.styles.get(id).and_then(|style| style.chr.emphasis), mark, "{stage}: style {id}");
}
let p = doc.body.iter().find_map(|b| b.as_para()).unwrap();
let actual: Vec<_> = p
.runs
.iter()
.map(|r| (r.props.style.as_deref(), r.props.emphasis, doc.styles.resolve_char(p.props.style.as_deref(), &r.props).emphasis))
.collect();
assert_eq!(actual, expected_runs, "{stage}");
};
assert_state(&doc, "initial read");
for pass in 0..2 {
let out = wordcraft_docx::write(&doc).unwrap();
let style_xml = part(&out, "word/styles.xml");
for value in ["dot", "comma", "circle", "underDot", "none"] {
assert!(style_xml.contains(&format!(r#"<w:em w:val="{value}"/>"#)), "pass {pass}: {style_xml}");
}
let document_xml = part(&out, "word/document.xml");
assert!(document_xml.contains(r#"<w:em w:val="none"/>"#), "pass {pass}: {document_xml}");
assert!(document_xml.contains("default dot"));
doc = wordcraft_docx::read(&out).unwrap();
assert_state(&doc, &format!("pass {pass}"));
}
}
#[test]
fn style_paragraph_and_run_changes_keep_independent_authors() {
let styles = r#"
+109 -1
View File
@@ -513,6 +513,7 @@ fn split_para_as(s: &mut Session, at: &Pos, enter: bool) -> Result<Pos, CmdError
let para = s.doc.para_mut(at.story, &at.path)?;
if n.level > 0 {
para.props.numbering = Some(wordcraft_doc::props::NumRef { num: n.num, level: n.level - 1 });
para::drop_direct_indents(&mut para.props);
para.touch();
} else {
leave_list(para);
@@ -580,11 +581,65 @@ pub fn now_unix() -> u64 {
}
}
/// ISO-8601 timestamp (UTC, seconds).
/// ISO-8601 timestamp (UTC, seconds): the clock, for an event that happened now -- a comment, a
/// tracked change, a version. Not for what a saved or exported file records: see [`saved_iso`].
pub fn now_iso() -> String {
iso_from_unix_secs(now_unix())
}
/// The timestamp a saved or exported file records (its created and modified properties):
/// `SOURCE_DATE_EPOCH` when it holds a non-negative whole number of seconds, else the clock. With
/// it set, separate conversions of unchanged input can produce the same bytes. Repeated saves
/// of one session still advance the document revision
/// (<https://reproducible-builds.org/specs/source-date-epoch/>).
///
/// The clock stays in [`now_iso`]: an editing event's time is not the file's, and pinning it would
/// misdate comments and tracked changes.
///
/// A value that is set but not one of those is ignored with a warning, so a build that meant to
/// pin its dates hears that it did not.
pub fn saved_iso() -> String {
let raw = std::env::var("SOURCE_DATE_EPOCH").ok();
if let Some(problem) = epoch_problem(raw.as_deref()) {
log::warn!("{problem}");
}
iso_from_unix_secs(pinned_or(|_| raw.clone(), now_unix))
}
/// Why `SOURCE_DATE_EPOCH` is set and still not used, for a caller with no logger to say so (the
/// command line). `None` when it is unset, empty, or a value [`saved_iso`] takes.
pub fn source_date_epoch_problem() -> Option<String> {
epoch_problem(std::env::var("SOURCE_DATE_EPOCH").ok().as_deref())
}
/// An empty value counts as unset, as a CI file's `SOURCE_DATE_EPOCH=` with nothing after it
/// means; anything else that does not pin a date is worth a warning.
fn epoch_problem(value: Option<&str>) -> Option<String> {
let v = value?;
if v.trim().is_empty() || pinned(v).is_some() {
return None;
}
Some(format!(
"SOURCE_DATE_EPOCH={v:?} is not a whole number of seconds from 1970 to 9999-12-31, so saved and exported files take the clock's date"
))
}
/// The seconds a `SOURCE_DATE_EPOCH` value pins, if it pins any.
fn pinned(v: &str) -> Option<u64> {
v.trim().parse::<u64>().ok().filter(|secs| *secs <= LAST_DATE)
}
/// [`saved_iso`]'s choice, with the environment and the clock given so a test can show which wins.
pub(crate) fn pinned_or(get: impl Fn(&str) -> Option<String>, clock: impl Fn() -> u64) -> u64 {
get("SOURCE_DATE_EPOCH").as_deref().and_then(pinned).unwrap_or_else(clock)
}
/// The last date a document can record, as Unix seconds: 9999-12-31T23:59:59Z. A year runs to
/// four digits in `xsd:dateTime`, which is what a .docx core property holds, so a value past this
/// would be written as something no reader accepts -- `292277026596-12-04T15:30:07Z` for
/// `i64::MAX`. Such a value is left to the clock, as a malformed one is.
const LAST_DATE: u64 = 253_402_300_799;
/// The local time zone's offset from UTC in seconds (east positive) at `unix`, daylight saving
/// included: the system's zone, or the browser's on the web. 0 (UTC) when it can't be found.
pub fn local_offset_secs(unix: u64) -> i64 {
@@ -735,3 +790,56 @@ mod iso_tests {
let _ = (civil_from_days(i64::MAX), civil_from_days(i64::MIN));
}
}
#[cfg(test)]
mod saved_time_tests {
use super::{epoch_problem, iso_from_unix_secs, pinned_or};
/// What a saved or exported file records: `SOURCE_DATE_EPOCH` when it holds a non-negative
/// whole number of seconds, the clock whenever it does not. The environment and the clock are
/// given here rather than set, so no test changes this process's environment -- that is
/// `unsafe` under edition 2024 and would reach every test beside it.
#[test]
fn a_pinned_epoch_is_preferred_and_the_clock_answers_otherwise() {
let env = |v: Option<&'static str>| move |_: &str| v.map(str::to_owned);
let clock = || 1_000_000;
assert_eq!(pinned_or(env(Some("1791208980")), clock), 1_791_208_980, "the variable wins");
assert_eq!(pinned_or(env(Some("0")), clock), 0, "the epoch itself counts");
assert_eq!(pinned_or(env(Some(" 1791208980 ")), clock), 1_791_208_980, "spaces around it are allowed");
// The last date a document can write is honoured; past it the year would not fit
// `xsd:dateTime` and the clock answers instead.
assert_eq!(pinned_or(env(Some("253402300799")), clock), 253_402_300_799);
assert_eq!(iso_from_unix_secs(253_402_300_799), "9999-12-31T23:59:59Z");
for ignored in [
None,
Some(""),
Some(" "),
Some("-1"),
Some("later"),
Some("1791208980.5"),
Some("99999999999999999999"),
Some("253402300800"),
Some("9223372036854775807"),
] {
assert_eq!(pinned_or(env(ignored), clock), 1_000_000, "{ignored:?} leaves it to the clock");
}
// Only that variable is read.
assert_eq!(pinned_or(|name: &str| (name == "TZ").then(|| "1791208980".to_owned()), clock), 1_000_000);
// And it reaches the stamp as that instant, not as something near it.
assert_eq!(iso_from_unix_secs(pinned_or(env(Some("1791208980")), clock)), "2026-10-05T14:03:00Z");
}
/// A value that is set and still ignored is reported, so a build that meant to pin its dates
/// hears that it did not (noted in review). Unset and empty say nothing: an empty value is
/// how a CI file leaves the variable off.
#[test]
fn a_set_but_unusable_epoch_is_reported_and_nothing_else_is() {
for quiet in [None, Some(""), Some(" "), Some("0"), Some("1791208980"), Some(" 1791208980 "), Some("253402300799")] {
assert_eq!(epoch_problem(quiet), None, "{quiet:?}");
}
for loud in ["later", "-1", "1791208980.5", "1e9", "253402300800", "99999999999999999999"] {
let problem = epoch_problem(Some(loud)).unwrap_or_else(|| panic!("{loud:?} should be reported"));
assert!(problem.contains(&format!("{loud:?}")) && problem.contains("clock"), "{problem}");
}
}
}
+4 -2
View File
@@ -363,8 +363,10 @@ fn copy_member(s: &mut Session, pos: &Pos, index: usize) -> CmdResult {
return Err(CmdError::Failed("the member vanished".into()));
}
let text = f.clipboard_text();
let r = super::edit::copy_result(s, &f, &text)?;
s.clip_history.push(&f, &text);
let r = super::edit::copy_result(s, f, text)?;
if let Some(f) = &s.clipboard {
s.clip_history.push(f, &s.clipboard_text);
}
Ok(r)
}
+195 -43
View File
@@ -2,8 +2,9 @@
use serde_json::Value;
use wordcraft_doc::math_edit::MathPos;
use wordcraft_doc::para::OBJ;
use wordcraft_doc::{InlineObject, Paragraph, Pos, StoryRef};
use wordcraft_doc::para::{NBSP, OBJ};
use wordcraft_doc::props::TextDirection;
use wordcraft_doc::{InlineObject, Paragraph, Path, Pos, StoryRef};
use wordcraft_layout::ViewMode;
use super::{parse_pos, sel_result};
@@ -53,7 +54,10 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("caret.set", "Set Caret", "Navigation", set)
.params(r#"{"pos": Pos, "extend"?: bool} | {"page": n, "x": pt, "y": pt}"#)
.pure(),
CommandSpec::new("select.all", "Select All", "Home › Editing › Select", select_all).key("Mod+A").pure(),
CommandSpec::new("select.all", "Select All", "Home › Editing › Select", select_all)
.key("Mod+A")
.params(r#"{"whole"?: bool (default true: select the whole story; false: grow through the cell, row and table first)}"#)
.pure(),
CommandSpec::new("select.range", "Select Range", "Navigation", select_range).params(r#"{"anchor": Pos, "focus": Pos}"#).pure(),
CommandSpec::new("select.word", "Select Word", "Navigation", select_word).pure(),
CommandSpec::new("select.sentence", "Select Sentence", "Navigation", select_sentence).pure(),
@@ -110,6 +114,47 @@ fn bidi_para(s: &Session) -> bool {
/// Left/Right: with a selection and no Shift, collapse to its edge.
fn lr(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
if let Some(t) = turn(s) {
// Vertical text (#8986): Left/Right change line; top-to-bottom lines stack leftwards.
return line_step(s, v, (t == TextDirection::Down) == is_left, is_left);
}
lr_along(s, v, is_left)
}
/// The text direction at the caret when it is in turned (vertical) text.
fn turn(s: &mut Session) -> Option<TextDirection> {
let l = s.layout();
l.turn_at(&s.sel.focus, s.page_hint)
}
/// Vertical text: to the next (`next`) or previous line, at the same distance along it. With no
/// such line in the caret's flow (a table cell's only line, the last column), Left/Right step along
/// the text as they did before (`is_left`: backwards).
fn line_step(s: &mut Session, v: &Value, next: bool, is_left: bool) -> CmdResult {
let ext = extend(v);
if !ext && !s.sel.is_collapsed() {
let (a, b) = s.sel.ordered();
s.sel = Selection::caret(if next { b } else { a });
s.goal_x = None;
return sel_result(s);
}
let l = s.layout();
let from = s.sel.focus.clone();
let to = match l.turned_line(&from, s.goal_x, next, s.page_hint) {
Some((p, g)) => {
s.goal_x = Some(g);
p
}
None => return lr_along(s, v, is_left),
};
let gx = s.goal_x;
apply(s, to, ext);
s.goal_x = gx;
sel_result(s)
}
/// Left/Right as a step along the text (`is_left`: backwards).
fn lr_along(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
let ext = extend(v);
if !ext && !s.sel.is_collapsed() {
let (a, b) = s.sel.ordered();
@@ -124,10 +169,11 @@ fn lr(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
}
let from = s.sel.focus.clone();
// Equation entry and the grapheme step start at the same visible edge.
let edge = logical_edge(s, &from, is_left);
let hidden = s.layout_hides_deleted(from.story);
let edge = logical_edge(s, &from, is_left, hidden);
if !ext
&& !s.math_left
&& let Some(r) = into_equation(s, &from, edge, is_left)
&& let Some(r) = into_equation(s, &from, edge, is_left, hidden)
{
return r;
}
@@ -141,10 +187,10 @@ fn lr(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
/// left, as in Word (#4138). Leaving it puts the caret on the far side, so the same arrow then
/// moves on instead of going back in. A caret.left/right that itself left an equation (sent
/// while editing one) moves on too.
fn into_equation(s: &mut Session, from: &Pos, edge: usize, is_left: bool) -> Option<CmdResult> {
fn into_equation(s: &mut Session, from: &Pos, edge: usize, is_left: bool, hidden: wordcraft_layout::HideDeleted) -> Option<CmdResult> {
let off = if is_left { edge.checked_sub(OBJ.len_utf8())? } else { edge };
let para = s.doc.para_at(from)?;
if !matches!(para.object_at(off), Some(InlineObject::Equation { .. })) || (!s.view.show_markup && para.props_of_char(off).del.is_some()) {
if !matches!(para.object_at(off), Some(InlineObject::Equation { .. })) || (hidden.any() && hidden.hides(&s.doc, para.props_of_char(off).del)) {
return None;
}
s.sel = Selection::caret(Pos { off, ..from.clone() });
@@ -180,44 +226,52 @@ fn visual_lr(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
sel_result(s)
}
/// 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 {
/// Find the run containing `byte` from the nearer end of `para`.
fn run_at_byte(para: &Paragraph, byte: usize) -> Option<(usize, std::ops::Range<usize>)> {
if byte >= para.len() {
return None;
}
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;
let start = end.saturating_sub(run.len);
let range = start..end;
end = 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;
}
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 logical_edge(s: &Session, from: &Pos, is_left: bool) -> usize {
if !s.view.show_markup
/// The two ends of a hidden deletion share a caret position. Cross the hidden
/// span before taking the normal grapheme step, including adjacent deletions.
fn hidden_deletion_edge(para: &Paragraph, off: usize, is_left: bool, hides: impl Fn(Option<u32>) -> bool) -> usize {
// At a run boundary, inspect the byte on the side the caret is moving toward.
let Some(byte) = off.checked_sub(usize::from(is_left)) else { return off };
let Some((i, range)) = run_at_byte(para, byte) else { return off };
if !hides(para.runs[i].props.del) {
return off;
}
if is_left {
range.start - para.runs[..i].iter().rev().take_while(|run| hides(run.props.del)).map(|run| run.len).sum::<usize>()
} else {
range.end + para.runs[i + 1..].iter().take_while(|run| hides(run.props.del)).map(|run| run.len).sum::<usize>()
}
}
fn logical_edge(s: &Session, from: &Pos, is_left: bool, hidden: wordcraft_layout::HideDeleted) -> usize {
if hidden.any()
&& let Some(para) = s.doc.para_at(from)
{
return hidden_deletion_edge(para, from.off, is_left);
return hidden_deletion_edge(para, from.off, is_left, |del| hidden.hides(&s.doc, del));
}
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)
let edge = logical_edge(s, from, is_left, s.layout_hides_deleted(from.story));
step_from_edge(s, from, edge, is_left)
}
fn step_from_edge(s: &Session, from: &Pos, edge: usize, is_left: bool) -> Pos {
@@ -229,24 +283,118 @@ fn step_from_edge(s: &Session, from: &Pos, edge: usize, is_left: bool) -> Pos {
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 }
step_to_neighbor(s, from, is_left, !s.view.show_markup)
}
fn step_to_neighbor(s: &Session, from: &Pos, is_left: bool, skip_deleted: bool) -> Pos {
let story = from.story;
let neighbor = if is_left { s.doc.prev_para(story, &from.path) } else { s.doc.next_para(story, &from.path) };
let Some(mut path) = neighbor else { return from.clone() };
// Layout collapses a wholly deleted paragraph in No Markup. A surviving mark still gives
// even a paragraph without visible text a caret stop.
let deleted = |path: &Path| s.doc.para(story, path).is_some_and(|p| p.mark.del.is_some() && p.runs.iter().all(|r| r.props.del.is_some()));
if skip_deleted && deleted(&path) {
// Get the story's paths once for the rest of the walk, even across many deleted paragraphs.
let paths = s.doc.para_paths(story);
let Ok(i) = paths.binary_search(&path) else { return from.clone() };
let stop = if is_left { paths[..i].iter().rev().find(|p| !deleted(p)) } else { paths[i + 1..].iter().find(|p| !deleted(p)) };
let Some(stop) = stop else { return from.clone() };
path = stop.clone();
}
let off = if is_left { s.doc.para(story, &path).map_or(0, Paragraph::len) } else { 0 };
Pos { story, path, off }
}
fn visible_word_start(para: &Paragraph, off: usize, hides: impl Fn(Option<u32>) -> bool) -> Option<usize> {
let off = para.clamp(off);
let byte = off.checked_sub(1)?;
let (i, range) = run_at_byte(para, byte)?;
let mut idx = off;
let mut seen_word = false;
let mut seen_visible = false;
let mut end = range.end;
for run in para.runs[..=i].iter().rev() {
let start = end.saturating_sub(run.len);
let range_end = end.min(off);
end = start;
if hides(run.props.del) {
continue;
}
let Some(slice) = para.text.get(start..range_end) else { continue };
for (rel, c) in slice.char_indices().rev() {
seen_visible = true;
if wordcraft_doc::bidi::is_word_char(c) {
seen_word = true;
idx = start + rel;
} else if seen_word {
return Some(idx);
} else {
idx = start + rel;
}
}
}
seen_visible.then_some(idx)
}
fn visible_word_end(para: &Paragraph, off: usize, hides: impl Fn(Option<u32>) -> bool) -> Option<usize> {
let off = para.clamp(off);
let (i, range) = run_at_byte(para, off)?;
let mut first_word = None;
let mut in_space = false;
let mut last_end = None;
let mut run_start = range.start;
for run in &para.runs[i..] {
let run_end = run_start.saturating_add(run.len);
let start = run_start.max(off);
run_start = run_end;
if hides(run.props.del) {
continue;
}
let Some(slice) = para.text.get(start..run_end) else { continue };
for (rel, c) in slice.char_indices() {
let abs = start + rel;
last_end = Some(abs + c.len_utf8());
let is_first = first_word.is_none();
let fw = *first_word.get_or_insert_with(|| wordcraft_doc::bidi::is_word_char(c) && c != '\'');
let w = wordcraft_doc::bidi::is_word_char(c);
if c == ' ' || c == NBSP {
in_space = true;
continue;
}
if in_space || (fw && !w) || (!fw && !is_first) {
return Some(abs);
}
}
}
last_end
}
fn word_left(s: &mut Session, p: &Pos) -> Pos {
match s.doc.para_at(p) {
Some(para) if p.off > 0 => Pos { off: para.word_start(p.off), ..p.clone() },
_ => logical_step(s, p, true),
let hidden = s.layout_hides_deleted(p.story);
if let Some(para) = s.doc.para_at(p) {
if hidden.any() {
if let Some(off) = visible_word_start(para, p.off, |del| hidden.hides(&s.doc, del)) {
return Pos { off, ..p.clone() };
}
} else if p.off > 0 {
return Pos { off: para.word_start(p.off), ..p.clone() };
}
}
step_to_neighbor(s, p, true, false)
}
fn word_right(s: &mut Session, p: &Pos) -> Pos {
match s.doc.para_at(p) {
Some(para) if p.off < para.len() => Pos { off: para.word_end(p.off), ..p.clone() },
_ => logical_step(s, p, false),
let hidden = s.layout_hides_deleted(p.story);
if let Some(para) = s.doc.para_at(p) {
if hidden.any() {
if let Some(off) = visible_word_end(para, p.off, |del| hidden.hides(&s.doc, del)) {
return Pos { off, ..p.clone() };
}
} else if p.off < para.len() {
return Pos { off: para.word_end(p.off), ..p.clone() };
}
}
step_to_neighbor(s, p, false, false)
}
fn para_up(s: &mut Session, p: &Pos) -> Pos {
@@ -270,6 +418,10 @@ fn para_down(s: &mut Session, p: &Pos) -> Pos {
}
fn vert(s: &mut Session, v: &Value, dir: i32) -> CmdResult {
if let Some(t) = turn(s) {
// Vertical text (#8986): Up/Down step along the line (top-to-bottom text runs down).
return lr_along(s, v, (dir < 0) == (t == TextDirection::Down));
}
let ext = extend(v);
let l = s.layout();
let from = s.sel.focus.clone();
@@ -284,7 +436,7 @@ fn vert(s: &mut Session, v: &Value, dir: i32) -> CmdResult {
}
};
if let Some(c) = l.caret_on(&to, s.page_hint) {
s.page_hint = c.page;
s.set_page_hint(c.page);
}
let gx = s.goal_x;
apply(s, to, ext);
@@ -336,7 +488,7 @@ fn page(s: &mut Session, v: &Value, dir: i32) -> CmdResult {
} else {
l.hit(np, c.x, c.top + 1.0, from.story).unwrap_or(from)
};
s.page_hint = np;
s.set_page_hint(np);
apply(s, to, ext);
sel_result(s)
}
@@ -359,7 +511,7 @@ fn set(s: &mut Session, v: &Value) -> CmdResult {
let story = super::story_param(s, v);
let l = s.layout();
let page = usize::try_from(pg).unwrap_or(usize::MAX);
s.page_hint = page;
s.set_page_hint(page);
l.hit(page, x, y, story).ok_or_else(|| CmdError::Params("no text on that page".into()))?
} else {
return Err(CmdError::Params("`pos` or `page`/`x`/`y` required".into()));
@@ -376,7 +528,7 @@ fn select_all(s: &mut Session, v: &Value) -> CmdResult {
s.column_mode = false;
return sel_result(s);
}
if !p::bool(v, "whole").unwrap_or(false)
if !p::bool(v, "whole").unwrap_or(true)
&& let Some(r) = super::table::grow_select_all(s)
{
return r;
+1
View File
@@ -26,6 +26,7 @@ use generated::ENTRY_STYLE;
pub(crate) use generated::generated_list;
use generated::table_of_figures;
pub use generated::{figures_instr, update_generated};
pub(super) use generated::{is_list_entry, wrapped_list};
pub use render::{cite, entry};
pub use sources::update_citations;
use sources::{citation, sources};
+77 -4
View File
@@ -65,6 +65,7 @@ fn generated_list_with(s: &mut Session, instr: &str, title: &str, leader: Option
seed.props.tabs = Some(vec![TabStop { pos: 0.0, align: TabAlign::Right, leader }]);
s.doc.insert_block(StoryRef::Body, &Path::top(i.saturating_add(1)), Block::Para(seed))?;
}
s.touch();
update_generated(s)
}
@@ -74,7 +75,7 @@ const MAX_WRAPPED: usize = 10_000;
/// A generated list (index, bibliography, table of figures or authorities) held as a complex
/// field that starts at body block `i` and runs over its entries: its field code and the block
/// it ends in. `None` for anything else (a TOC has its own update).
fn wrapped_list(s: &Session, i: usize) -> Option<(String, usize, usize, usize)> {
pub(in crate::cmd) fn wrapped_list(s: &Session, i: usize) -> Option<(String, usize, usize, usize)> {
let p = s.doc.body.get(i)?.as_para()?;
let (k, off, instr) = p.objects_with_offsets().enumerate().find_map(|(k, (off, o))| match o {
InlineObject::FieldStart { instr, .. } => {
@@ -197,9 +198,15 @@ fn caption_body(p: &Paragraph, label: &str) -> String {
pub(super) const ENTRY_STYLE: &str = "ListEntry";
/// A result paragraph can share its style with a field header split out of an imported list.
pub(in crate::cmd) fn is_list_entry(p: &Paragraph) -> bool {
p.props.style.as_deref() == Some(ENTRY_STYLE) && list_kind(p).is_none()
}
/// Rebuild every generated list.
pub fn update_generated(s: &mut Session) -> Result<(), CmdError> {
let mut i = 0;
let mut relocated_index_leader = None;
while i < s.doc.body.len() {
// A list held as a field around its entries (as Word and ODT files hold them): made the
// field's own paragraph, as WordCraft inserts one, its old entries rebuilt below.
@@ -207,7 +214,11 @@ pub fn update_generated(s: &mut Session) -> Result<(), CmdError> {
// break, are the document's and stay.
// (The field it is made: what comes before it in its paragraph may hold other fields.)
let mut converted = None;
let mut index_leader = None;
if let Some((instr, start, last, end)) = wrapped_list(s, i) {
if instr.starts_with("INDEX") {
index_leader = crate::cmd::index::wrapped_entry_leader(s, i, start, last, end);
}
// The entries between its first and last paragraphs go.
for _ in i.saturating_add(1)..last {
s.doc.remove_block(StoryRef::Body, &Path::top(i + 1))?;
@@ -247,9 +258,14 @@ pub fn update_generated(s: &mut Session) -> Result<(), CmdError> {
let p = s.doc.para_mut(StoryRef::Body, &Path::top(i))?;
if p.objects_with_offsets().any(|(off, o)| off < start && list_field(o).is_some()) {
let list = p.split_off(start)?;
// Rebuilding the preceding list can shift the new paragraph's block index.
if let Some(leader) = index_leader.take() {
relocated_index_leader = Some((list.rev, leader));
}
s.doc.insert_block(StoryRef::Body, &Path::top(i + 1), Block::Para(list))?;
converted = None;
}
s.touch();
}
let kind = converted.or_else(|| s.doc.body.get(i).and_then(|b| b.as_para()).and_then(list_kind));
let Some(kind) = kind else {
@@ -258,7 +274,11 @@ pub fn update_generated(s: &mut Session) -> Result<(), CmdError> {
};
add_entry_style(s);
if kind.starts_with("INDEX") {
crate::cmd::index::rebuild_from(s, i, None, kind)?;
let index_leader = index_leader.or_else(|| {
let rev = s.doc.body.get(i)?.as_para()?.rev;
relocated_index_leader.take_if(|(relocated, _)| *relocated == rev).map(|(_, leader)| leader)
});
crate::cmd::index::rebuild_from(s, i, index_leader, kind)?;
i += 1;
continue;
}
@@ -290,11 +310,11 @@ pub fn update_generated(s: &mut Session) -> Result<(), CmdError> {
.body
.get(i + 1)
.and_then(|b| b.as_para())
.filter(|p| p.props.style.as_deref() == Some(ENTRY_STYLE))
.filter(|p| is_list_entry(p))
.and_then(|p| p.props.tabs.as_ref()?.last().map(|t| t.leader))
.or(saved_leader)
.unwrap_or(TabLeader::Dot);
while s.doc.body.get(i + 1).and_then(|b| b.as_para()).is_some_and(|p| p.props.style.as_deref() == Some(ENTRY_STYLE)) {
while s.doc.body.get(i + 1).and_then(|b| b.as_para()).is_some_and(is_list_entry) {
s.doc.remove_block(StoryRef::Body, &Path::top(i + 1))?;
}
let lines = entries_for(s, &kind);
@@ -310,6 +330,7 @@ pub fn update_generated(s: &mut Session) -> Result<(), CmdError> {
}
s.doc.insert_block(StoryRef::Body, &Path::top(i + 1 + k), Block::Para(para))?;
}
s.touch();
i += 1;
}
s.touch();
@@ -563,4 +584,56 @@ mod tests {
assert_eq!(lists, [Some("INDEX".to_string()), Some("BIBLIOGRAPHY".to_string())]);
}
}
#[test]
fn a_wrapped_index_keeps_its_leader_when_split_from_a_bibliography() {
let old_entry = "Old entry\t1";
let mut s = wrapped("Old entry\t1\n\nKilns are hot.", 0, 0, old_entry.len());
s.run("select.text", &serde_json::json!({"text": "Kilns"})).unwrap();
s.run("references.markEntry", &serde_json::json!({})).unwrap();
s.doc.sources.push(wordcraft_doc::Source { tag: "a".into(), kind: "book".into(), title: "Listed Source".into(), ..Default::default() });
let props = CharProps::default();
let instr = "INDEX \\e \"\t\"";
let p = s.doc.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
p.objects[0] = InlineObject::FieldStart { instr: instr.into(), locked: false, dirty: false };
p.insert_object(
0,
InlineObject::Field {
instr: "BIBLIOGRAPHY".into(),
result: String::new(),
locked: false,
dirty: false,
code: false,
form: String::new(),
},
&props,
)
.unwrap();
p.props.style = Some(ENTRY_STYLE.into());
p.props.tabs = Some(vec![TabStop { pos: 120.0, align: TabAlign::Right, leader: TabLeader::Hyphen }]);
let p = s.doc.para_mut(StoryRef::Body, &Path::top(1)).unwrap();
// A separate INDEX with the same instruction has no prior result and must get the default.
p.insert_object(
0,
InlineObject::Field { instr: instr.into(), result: String::new(), locked: false, dirty: false, code: false, form: String::new() },
&props,
)
.unwrap();
s.touch();
let (_, start, last, end) = wrapped_list(&s, 0).unwrap();
assert_eq!(crate::cmd::index::wrapped_entry_leader(&mut s, 0, start, last, end), Some(TabLeader::Hyphen));
for _ in 0..2 {
update_generated(&mut s).unwrap();
let paras: Vec<_> = s.doc.body.iter().filter_map(|b| b.as_para()).collect();
assert_eq!(list_kind(paras[0]).as_deref(), Some("BIBLIOGRAPHY"));
assert!(paras[1].plain_text().contains("Listed Source"), "the bibliography inserts an entry before the relocated index");
for (header, leader) in [(2, TabLeader::Hyphen), (4, TabLeader::Dot)] {
assert_eq!(list_kind(paras[header]).as_deref(), Some(instr));
assert_eq!(paras[header + 1].plain_text(), "Kilns\t1");
assert_eq!(paras[header + 1].props.tabs.as_ref().unwrap()[0].leader, leader);
}
}
}
}
+1 -1
View File
@@ -247,7 +247,7 @@ fn copy(s: &mut Session, segs: &[(Pos, Pos)]) -> CmdResult {
let text = rows.join("\n");
let media = s.doc.media_of_blocks(&blocks);
let f = Fragment { blocks, parts, media };
super::edit::copy_result(s, &f, &text)
super::edit::copy_result(s, f, text)
}
/// Delete each row's piece (bottom up, so earlier positions stay valid) and leave the caret at
+57 -36
View File
@@ -332,46 +332,67 @@ mod tests {
/// Drawing commands must not search every page again for each glued connector.
#[test]
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")]
fn rerouting_many_pages_does_not_rescan_all_objects_per_connector() {
use wordcraft_doc::{Document, Paragraph, para_block};
let mut doc = Document::new();
doc.body = (0..8000u32)
.map(|i| {
let mut p = Paragraph::default();
p.props.page_break_before = Some(i > 0);
let id = i * 2 + 1;
for (kind, x, extra) in [
(ShapeKind::Rectangle, 100.0, ShapeExtra { id, ..Default::default() }),
(ShapeKind::Ellipse, 300.0, ShapeExtra { id: id + 1, ..Default::default() }),
(
ShapeKind::ElbowConnector,
0.0,
ShapeExtra { start: Some(ConnEnd { id, site: 3 }), end: Some(ConnEnd { id: id + 1, site: 2 }), ..Default::default() },
),
] {
let float = Float { wrap: Wrap::InFrontOfText, h_rel: Anchor::Page, v_rel: Anchor::Page, x, y: 200.0, ..Default::default() };
p.insert_object(p.len(), shape(kind, extra, float), &Default::default()).unwrap();
}
para_block(p)
})
.collect();
let mut s = Session::new(doc);
s.view.proofing = false;
s.page_hint = 0;
assert_eq!(s.layout().pages.len(), 8000);
let started = std::time::Instant::now();
assert!(reroute(&mut s));
let elapsed = started.elapsed();
eprintln!("8000-page reroute: {elapsed:?}");
assert!(elapsed < std::time::Duration::from_secs(5), "reroute took {elapsed:?}");
for path in s.doc.para_paths(StoryRef::Body) {
let para = s.doc.para(StoryRef::Body, &path).unwrap();
let InlineObject::Shape { w, h, float, .. } = para.object_at(6).unwrap() else { panic!("connector") };
fn glued_pages(n: u32) -> Session {
let mut doc = Document::new();
doc.body = (0..n)
.map(|i| {
let mut p = Paragraph::default();
p.props.page_break_before = Some(i > 0);
let id = i * 2 + 1;
for (kind, x, extra) in [
(ShapeKind::Rectangle, 100.0, ShapeExtra { id, ..Default::default() }),
(ShapeKind::Ellipse, 300.0, ShapeExtra { id: id + 1, ..Default::default() }),
(
ShapeKind::ElbowConnector,
0.0,
ShapeExtra { start: Some(ConnEnd { id, site: 3 }), end: Some(ConnEnd { id: id + 1, site: 2 }), ..Default::default() },
),
] {
let float = Float { wrap: Wrap::InFrontOfText, h_rel: Anchor::Page, v_rel: Anchor::Page, x, y: 200.0, ..Default::default() };
p.insert_object(p.len(), shape(kind, extra, float), &Default::default()).unwrap();
}
para_block(p)
})
.collect();
let mut s = Session::new(doc);
s.view.proofing = false;
s.page_hint = 0;
assert_eq!(s.layout().pages.len(), n as usize);
s
}
const SMALL: u32 = 32;
const SCALE: u32 = 8;
let mut small = glued_pages(SMALL);
let mut big = glued_pages(SMALL * SCALE);
let layout = big.layout();
let small_steps = wordcraft_doc::work::count(|| assert!(reroute(&mut small)));
let big_steps = wordcraft_doc::work::count(|| assert!(reroute(&mut big)));
// One layout walk to build the index plus bounded work per connector: roughly 8x the
// steps for 8x the pages. Allow room for fixed differences in the first and last pages.
let budget = small_steps * 12;
assert!(small_steps > 0 && big_steps > small_steps, "reroute steps: {small_steps} -> {big_steps}");
assert!(big_steps <= budget, "reroute repeated lookup work: {small_steps} -> {big_steps} steps for {SCALE}x pages");
// The previous lookup starts at the caret's page for every connector. Run just that
// part of the old route to verify it would exceed the same budget on this fixture.
let connector_off = 2 * wordcraft_doc::para::OBJ.len_utf8();
let scan_steps = wordcraft_doc::work::count(|| {
for page in 0..layout.pages.len() {
let hit = layout.object(&Pos::body(page, connector_off), 0).unwrap();
assert_eq!(hit.page, page);
}
});
assert!(scan_steps > budget, "per-connector scans took only {scan_steps} steps for a budget of {budget}");
for path in big.doc.para_paths(StoryRef::Body) {
let para = big.doc.para(StoryRef::Body, &path).unwrap();
let InlineObject::Shape { w, h, float, .. } = para.object_at(connector_off).unwrap() else { panic!("connector") };
assert_eq!((*w, *h, float.x, float.y), (160.0, 0.0, 140.0, 210.0));
}
s.touch();
assert!(!reroute(&mut s), "rerouting must settle after refreshing the layout");
big.touch();
assert!(!reroute(&mut big), "rerouting must settle after refreshing the layout");
}
/// The per-case shape/geometry of one scaled-group reroute case.
+7
View File
@@ -521,6 +521,13 @@ fn place(s: &mut Session, layout: &DocLayout, obj: InlineObject, page: usize, (x
float.y = y - origin.y;
}
para.touch();
if !on_page && let Some(offset) = super::objects::shifted_float_offset(s, &at, page, y, origin.y) {
super::objects::edit_obj(s, &at, |o| {
if let Some(float) = o.float_mut() {
float.y = offset;
}
})?;
}
Ok(at)
}
+66 -21
View File
@@ -7,6 +7,9 @@ use wordcraft_doc::{Path, Pos, StoryRef};
use super::{delete_selection, find_pattern, pos_json, sel_result};
use crate::{CmdError, CmdResult, CommandSpec, Selection, Session, p};
/// Ribbon location of the linked Cut, Copy and Paste commands.
pub const LINKED_CLIPBOARD_LOCATION: &str = "Home › Clipboard";
/// Browsers reserve Mod+Shift+C for their inspector. Keep the desktop binding, but
/// advertise a web alternative through the same registry/keymap as every other command.
/// Mod+Alt+C already inserts copyright, and Mod+Alt+Shift+V is Keep Text Only.
@@ -72,8 +75,8 @@ pub fn specs() -> Vec<CommandSpec> {
})
.key("Mod+Y / Mod+Shift+Z")
.pure(),
CommandSpec::new("edit.cut", "Cut", "Home › Clipboard", cut).key("Mod+X").when(has_sel),
CommandSpec::new("edit.copy", "Copy", "Home › Clipboard", copy).key("Mod+C / Mod+Insert").pure().when(has_sel),
CommandSpec::new("edit.cut", "Cut", LINKED_CLIPBOARD_LOCATION, cut).key("Mod+X").when(has_sel),
CommandSpec::new("edit.copy", "Copy", LINKED_CLIPBOARD_LOCATION, copy).key("Mod+C / Mod+Insert").pure().when(has_sel),
// Word's Spike (Ctrl+F3, Ctrl+Shift+F3; ⌘ on the Mac): the AutoText entry "Spike", so Quick
// Parts and AutoText insert it without emptying it, as in Word.
CommandSpec::new("edit.spike", "Spike", "Editing", spike).key("Mod+F3").when(has_text_sel),
@@ -86,7 +89,7 @@ pub fn specs() -> Vec<CommandSpec> {
Some("the Spike is empty")
}
}),
CommandSpec::new("edit.paste", "Paste", "Home › Clipboard", paste)
CommandSpec::new("edit.paste", "Paste", LINKED_CLIPBOARD_LOCATION, paste)
.key("Mod+V / Shift+Insert")
.params(r#"{"text"?: string, "html"?: string, "rtf"?: string, "privateClipboard"?: bool}"#),
CommandSpec::new("edit.pasteNestedTable", "Paste as Nested Table", "Home › Clipboard › Paste", paste_nested)
@@ -161,7 +164,7 @@ pub fn specs() -> Vec<CommandSpec> {
.params(r#"{"tab"?: "find|replace|goto" (default replace)}"#)
.pure(),
CommandSpec::new("edit.replaceAll", "Replace All", "Home › Editing › Replace", replace_all)
.params(r#"{"text": string, "with": string (^p ^t ^& ^c …; \\1 with wildcards; with regex also $1 ${n} ${name} $0 $$ \\1 \\n (paragraph mark) \\t), …options of edit.find} (with AutoFormat's smart quotes on, a " or ' typed in `with` goes in curly by the character before it, as typing does, except with regex or special: false (taken as written); ^034 and ^039 stay straight; a match that already reads so, curled the same kind, is left and not counted)"#),
.params(r#"{"text": string, "with": string (^p ^t ^& ^c …; \\1 with wildcards; with regex also $1 ${n} ${name} $0 $$ \\1 \\n (paragraph mark) \\t), …options of edit.find} (with AutoFormat's smart quotes on, a " or ' typed in `with` goes in curly by the character before it, as typing does, except with regex or special: false (taken as written); ^034 and ^039 stay straight; a match that already reads so, curled the same kind, is left and not counted); replaces in the main text, headers, footers, footnotes, endnotes and text boxes, wherever the caret is"#),
CommandSpec::new("edit.goto", "Go To", "Home › Editing › Find", goto)
.key("Mod+Alt+G / F5")
.params(r#"{"page"?: n, "pageBy"?: int (pages forward, negative back, from the caret's page), "bookmark"?: string (selects its text), "paragraph"?: n}; none opens Find and Replace on its Go To tab"#)
@@ -209,8 +212,10 @@ fn copy_with(s: &mut Session, whole: Option<&Path>) -> CmdResult {
None => s.doc.copy_range(&a, &b),
};
let text = f.clipboard_text();
let r = copy_result(s, &f, &text)?;
s.clip_history.push(&f, &text);
let r = copy_result(s, f, text)?;
if let Some(f) = &s.clipboard {
s.clip_history.push(f, &s.clipboard_text);
}
Ok(r)
}
@@ -220,7 +225,7 @@ fn copy_with(s: &mut Session, whole: Option<&Path>) -> CmdResult {
///
/// The copy goes on the clipboard whole or not at all: a copy whose HTML or RTF cannot be made
/// is refused, and the clipboard keeps what it held.
pub(crate) fn copy_result(s: &mut Session, f: &Fragment, text: &str) -> CmdResult {
pub(crate) fn copy_result(s: &mut Session, f: Fragment, text: String) -> CmdResult {
let mut d = f.to_document();
d.styles = s.doc.styles.clone();
if d.media.is_empty() {
@@ -243,8 +248,8 @@ pub(crate) fn copy_result(s: &mut Session, f: &Fragment, text: &str) -> CmdResul
}
// The copy is on the clipboard now: its text, its fragment and its HTML and RTF flavours,
// all at once.
s.clipboard_text = text.to_string();
s.clipboard = Some(f.clone());
s.clipboard_text = text;
s.clipboard = Some(f);
s.clipboard_html = html;
s.clipboard_rtf = rtf;
Ok(r)
@@ -731,7 +736,7 @@ fn find(s: &mut Session, v: &Value) -> CmdResult {
return Ok(json!({"count": s.find.results.len()}));
}
let story = s.sel.focus.story;
s.find.results = search(s, story)?;
s.find.set_results(search(s, story)?);
// Select the first match after the caret.
let caret = s.sel.focus.clone();
let idx = s.find.results.iter().position(|(a, _)| *a >= caret).unwrap_or(0);
@@ -770,13 +775,13 @@ fn advanced_find(s: &mut Session, v: &Value) -> CmdResult {
let n = found.len();
let matches: Vec<Value> = found.iter().take(200).map(|(a, b)| json!({"start": pos_json(a), "end": pos_json(b)})).collect();
s.find.current = 0;
s.find.results = found;
s.find.set_results(found);
Ok(json!({"count": n, "matches": matches, "highlight": s.find.highlight}))
}
fn step(s: &mut Session, dir: i64) -> CmdResult {
let story = s.sel.focus.story;
s.find.results = search(s, story)?;
s.find.set_results(search(s, story)?);
let n = s.find.results.len();
if n == 0 {
return Err(CmdError::Failed("no matches".into()));
@@ -827,16 +832,57 @@ fn replace(s: &mut Session, v: &Value) -> CmdResult {
Ok(json!({"replaced": replaced, "remaining": search(s, story)?.len(), "selected": selected}))
}
/// Every match replaced, last first so earlier positions stay valid (one undo step). A `\r` in
/// the replacement (`^p`) splits the paragraph.
/// The stories Replace All covers, as in Word: the main text, then the headers, footers,
/// footnotes, endnotes and text boxes the document shows. Hidden stories (a removed header, a
/// deleted note's text) and comments keep their words.
fn replace_stories(s: &Session) -> Vec<StoryRef> {
s.doc.shown_stories()
}
/// Every match in every story replaced (wherever the caret is), last first so earlier positions
/// stay valid (one undo step). A `\r` in the replacement (`^p`) splits the paragraph. Locked
/// content in any story stops it before anything changes.
fn replace_all(s: &mut Session, v: &Value) -> CmdResult {
need_query(s, v)?;
read_opts(s, v);
let story = s.sel.focus.story;
// Matches already curled as the replacement would curl them are left and not counted (#7307).
let results: Vec<Found> = search_matches(s, story, true, true)?.into_iter().filter(|f| !f.keep).collect();
let n = results.len();
super::controls::check_deletions(s, story, results.iter().map(|f| (&f.a, &f.b)))?;
let mut found = Vec::new();
// A protected document only lets the editable regions change: matches elsewhere (in a header,
// say) stay as they are, so they don't make the whole command fail.
let editable = super::protect::editable_ranges(s);
for story in replace_stories(s) {
// Matches already curled as the replacement would curl them are left and not counted (#7307).
let mut results: Vec<Found> = search_matches(s, story, true, true)?.into_iter().filter(|f| !f.keep).collect();
if let Some(ranges) = &editable {
results.retain(|f| ranges.iter().any(|(from, to)| f.a.story == from.story && f.a >= *from && f.b <= *to));
}
if results.is_empty() {
continue;
}
super::controls::check_deletions(s, story, results.iter().map(|f| (&f.a, &f.b)))?;
found.push(results);
}
let n: usize = found.iter().map(Vec::len).sum();
let saved_sel = s.sel.clone();
let orig_story = saved_sel.focus.story;
let mut orig_story_sel = None;
// The main text comes last, so under Track Changes keep the selection from the caret's own
// story (or restore the saved selection if that story had no match, #9063 / #9186).
for results in found.into_iter().rev() {
let is_orig = results[0].a.story == orig_story;
replace_found(s, results)?;
if s.doc.settings.track_changes && is_orig {
orig_story_sel = Some(s.sel.clone());
}
}
if s.doc.settings.track_changes {
s.sel = orig_story_sel.unwrap_or(saved_sel);
}
s.status = format!("All done. We made {n} replacements.");
Ok(json!({"replaced": n}))
}
/// Replace the matches of one story, last first.
fn replace_found(s: &mut Session, results: Vec<Found>) -> Result<(), CmdError> {
for Found { a, b, rep, .. } in results.into_iter().rev() {
let with = rep.unwrap_or_default();
if s.doc.settings.track_changes {
@@ -857,8 +903,7 @@ fn replace_all(s: &mut Session, v: &Value) -> CmdResult {
}
}
}
s.status = format!("All done. We made {n} replacements.");
Ok(json!({"replaced": n}))
Ok(())
}
fn goto(s: &mut Session, v: &Value) -> CmdResult {
+34 -4
View File
@@ -70,6 +70,8 @@ fn rename(s: &mut Session, v: &Value) -> CmdResult {
{
crate::io::rename_file(path, &destination).map_err(CmdError::Failed)?;
}
// Renamed, the file is the same one, with the same size and modified time: the stamp
// taken when it was read or saved still says whether another program changed it.
s.path = Some(destination);
s.relayout();
}
@@ -94,7 +96,7 @@ 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 (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`)}"#)
.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`), "ifUnchanged"?: bool (AutoSave: refuse, writing nothing, if the document's own file was changed or removed by another program since it was opened or saved here)}"#)
.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
@@ -256,6 +258,9 @@ fn open(s: &mut Session, v: &Value) -> CmdResult {
);
}
let password = p::str(v, "password");
// How the file looks before it is read (none for bytes passed in): one another program
// replaces while it is being read then no longer matches, and AutoSave leaves it (#7069).
let disk_stamp = if p::str(v, "data").is_none() { crate::io::file_stamp(std::path::Path::new(path)) } else { None };
// An empty file opens as a new blank document that saves back to it (#1384).
let (doc, encrypted) = read_document(s, path, v)?;
match s.used_because() {
@@ -269,6 +274,7 @@ fn open(s: &mut Session, v: &Value) -> CmdResult {
super::view::restore_zoom(s, z);
}
s.path = Some(path.into());
s.disk_stamp = disk_stamp;
// A Markdown file's own text, for the view to show and Save to write back as it is.
if super::md_source::is_markdown_file(std::path::Path::new(path)) {
s.md_file = markdown_file_text(path, v);
@@ -411,6 +417,24 @@ fn save(s: &mut Session, v: &Value) -> CmdResult {
}
};
check_strict_output(p::bool(v, "strict").unwrap_or(false), &path.to_string_lossy())?;
// AutoSave (`ifUnchanged`) never writes over the document's own file once another program has
// changed it since the document was read from it or last saved to it: that program's changes
// would be lost without a word (#7069). Checked again just before the new bytes replace the
// file (`unchanged`); first here, so a changed file costs no serializing. A save the user asks
// for writes as before.
let own_conditional = p::bool(v, "ifUnchanged") == Some(true) && s.path.as_deref() == Some(path.as_path());
let unchanged = if own_conditional { s.disk_stamp } else { None };
let name = || path.file_name().map_or_else(|| path.to_string_lossy(), |n| n.to_string_lossy()).to_string();
// Without a record of how the file looked (it was missing a moment when it was read, say),
// nothing says another program left it alone: no conditional write over it.
if own_conditional && unchanged.is_none() {
return Err(CmdError::Failed(format!("{} could not be checked against the file as it was opened or saved here", name())));
}
if let Some(stamp) = unchanged
&& crate::io::file_stamp(&path) != Some(stamp)
{
return Err(CmdError::Failed(format!("{} was changed or removed by another program after it was opened or saved here", name())));
}
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()));
}
@@ -453,15 +477,19 @@ fn save(s: &mut Session, v: &Value) -> CmdResult {
let exact = super::md_source::text_to_save(s, &path, opts.markup);
let rewritten = exact.is_none() && !s.md_file.is_empty() && super::md_source::is_markdown_file(&path);
let written = match &exact {
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),
Some(text) => crate::io::save_text_path_checked(&path, text, unchanged),
None => crate::io::save_path_checked(&path, copy.as_ref().unwrap_or(&s.doc), password, &opts, unchanged),
};
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)?;
let stamp = written.map_err(CmdError::Failed)?;
if as_copy {
// A copy over the document's own file is the file now: what AutoSave checks against.
if s.path.as_deref() == Some(path.as_path()) {
s.disk_stamp = Some(stamp);
}
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
@@ -471,6 +499,8 @@ fn save(s: &mut Session, v: &Value) -> CmdResult {
let markdown_to_markdown = super::md_source::is_markdown_file(&path) && s.path.as_deref().is_some_and(super::md_source::is_markdown_file);
if own_file || markdown_to_markdown || ["docx", "docm", "dotx", "dotm", "odt", "ott", "fodt", "rtf", "json", "xml"].contains(&ext.as_str()) {
s.path = Some(path.clone());
// The file this save wrote, not whatever is there by the time it is looked at again.
s.disk_stamp = Some(stamp);
s.dirty = false;
s.relayout();
// What the file holds now.
+12 -4
View File
@@ -221,7 +221,7 @@ fn strip_row(r: &RowProps) -> RowProps {
RowProps { fmt_change: None, ..r.clone() }
}
fn strip_cell(c: &CellProps) -> CellProps {
CellProps { fmt_change: None, span: 0, vmerge: VMerge::None, ..c.clone() }
CellProps { fmt_change: None, merge_change: None, span: 0, vmerge: VMerge::None, ..c.clone() }
}
fn strip_section(s: &SectionProps) -> SectionProps {
SectionProps { fmt_change: None, headers: Default::default(), footers: Default::default(), ..s.clone() }
@@ -457,10 +457,13 @@ pub fn resolve_row(r: &mut Row, accept: bool) {
}
}
/// Accept or reject a cell's change. Merges are the table's structure, not formatting: they stay.
/// Accept or reject a cell's changes. Merges are the table's structure, not formatting: they stay.
/// A tracked merge or split of the cell is dropped either way, its cells left as they are (Word
/// for Windows).
pub fn resolve_cell(c: &mut Cell, accept: bool) {
c.props.merge_change = None;
if let Some(ch) = c.props.fmt_change.take().filter(|_| !accept) {
c.props = CellProps { fmt_change: None, span: c.props.span, vmerge: c.props.vmerge, ..ch.old };
c.props = CellProps { fmt_change: None, merge_change: None, span: c.props.span, vmerge: c.props.vmerge, ..ch.old };
}
}
@@ -510,6 +513,11 @@ pub fn row_diff(r: &RowProps) -> Vec<Value> {
pub fn cell_diff(c: &CellProps) -> Vec<Value> {
c.fmt_change
.as_ref()
.map(|ch| diff(&CellProps { fmt_change: None, ..ch.old.clone() }, &CellProps { fmt_change: None, ..c.clone() }))
.map(|ch| {
diff(
&CellProps { fmt_change: None, merge_change: None, ..ch.old.clone() },
&CellProps { fmt_change: None, merge_change: None, ..c.clone() },
)
})
.unwrap_or_default()
}
+17
View File
@@ -186,6 +186,23 @@ pub fn missing_fonts(doc: &Document, layout: &DocLayout) -> Vec<MissingFont> {
out.into_values().collect()
}
/// Core Word fonts that actually need a non-metric substitute in a PDF or first-page PNG.
pub fn output_metric_font_notices(s: &Session, markup: bool, first_page_png: bool) -> Vec<(&'static str, String)> {
if first_page_png {
let layout = s.export_layout_with(markup);
return metric_font_notices(layout.pages.get(..1).unwrap_or(&[]));
}
let opts = super::file::export_options(s, &json!({"markup": markup}));
let out = super::references::output_fields(&s.doc);
let doc = out.as_ref().unwrap_or(&s.doc);
let layout = crate::strict::pdf_layout(doc, &crate::strict::pdf_options(&opts));
metric_font_notices(&layout.pages)
}
fn metric_font_notices(pages: &[wordcraft_layout::Page]) -> Vec<(&'static str, String)> {
DocLayout::metric_font_notices_on(pages).into_iter().map(|(core, face)| (core, face.family.clone())).collect()
}
/// A font name as [`missing_fonts`] lists it: as layout records it (at most 256 characters),
/// trimmed.
fn shown_name(font: &str) -> &str {
+29 -2
View File
@@ -1,12 +1,13 @@
//! Character formatting (Home › Font).
use std::collections::HashMap;
use std::sync::{Arc, PoisonError};
use serde_json::{Value, json};
use wordcraft_doc::eq::{EncloseShape, EncloseStyle, Enclosure};
use wordcraft_doc::props::{Border, CharProps, Highlight, Rgb, TextColor, Underline, VertAlign};
use wordcraft_doc::resolve::ResolvedChar;
use wordcraft_doc::{InlineObject, PartKind, Pos, RevisionKind, StoryRef};
use wordcraft_doc::{Document, InlineObject, PartKind, Pos, RevisionKind, StoryRef};
use super::sel_result;
use super::tools::{is_turkic, lower_char, upper_char};
@@ -955,6 +956,30 @@ pub fn state(s: &Session) -> Value {
(*cached_state(s)).clone()
}
/// The common East Asian family shown by the font controls. A theme slot without a face uses
/// the run's ordinary font, as layout does. Resolve each theme slot once per selection.
fn selection_east_asian_font<'a>(doc: &'a Document, runs: &'a [ResolvedChar]) -> (Option<&'a str>, bool) {
let mut themes = HashMap::new();
let mut fonts = runs.iter().map(|run| match run.font_ea_theme {
Some(slot) => {
let face = *themes.entry(slot).or_insert_with(|| wordcraft_layout::para::east_asian_font(doc, run));
(Some(face.unwrap_or(&run.font)), face.is_some())
}
None => {
let face = run.font_ea.as_deref();
(face, face.is_some_and(|name| !name.trim().is_empty()))
}
});
let Some((Some(first), mut named)) = fonts.next() else { return (None, false) };
for (font, from_named_face) in fonts {
if font != Some(first) {
return (None, false);
}
named |= from_named_face;
}
(Some(first), named)
}
fn compute_state(s: &Session) -> Value {
let all = resolved(s);
let first = all.first().cloned();
@@ -972,10 +997,12 @@ fn compute_state(s: &Session) -> Value {
// characters the substitute lacks. `font.missing` lists every face the shown text is drawn
// in, fallback faces too, and which fonts change the layout.
let shown_as = font.as_str().and_then(|f| crate::cmd::font::shown_as(&s.doc, f));
let (font_ea, named_east_asian) = selection_east_asian_font(&s.doc, &all);
json!({
"font": font,
"fontShownAs": shown_as,
"fontEastAsia": same(&|r| json!(r.font_ea)),
"fontEastAsia": font_ea,
"namedEastAsianFont": named_east_asian,
"size": same(&|r| json!(r.size)),
"bold": all.iter().all(shown_bold),
"italic": all.iter().all(shown_italic),
+182 -5
View File
@@ -9,6 +9,8 @@ use wordcraft_doc::para::InlineObject;
use wordcraft_doc::props::{CharProps, TabAlign, TabLeader, TabStop};
use wordcraft_doc::section::SectionStart;
use wordcraft_doc::{Block, Paragraph, Path, Pos, StoryRef};
use wordcraft_layout::para::ClKind;
use wordcraft_layout::{DocLayout, Placed, ViewMode};
use super::references::{FieldCode, field_arg, leader, page_at, page_formats, page_text};
use super::sel_result;
@@ -136,6 +138,98 @@ fn index_field(s: &Session) -> Option<(usize, String)> {
})
}
fn laid_out_leader(layout: &DocLayout, path: Path, offset: usize) -> Option<TabLeader> {
layout.index.get(&(StoryRef::Body, path))?.iter().find_map(|&(page, item)| {
let Placed::Lines { para, l0, l1, .. } = layout.pages.get(page)?.items.get(item)? else { return None };
para.lines.get(*l0..*l1)?.iter().find_map(|line| {
let tab = (line.c0..line.c1).find(|&i| para.clusters.get(i).is_some_and(|c| c.start == offset && c.kind == ClKind::Tab))?;
Some(line.leaders.iter().find(|&&(i, _)| i == tab).map_or(TabLeader::None, |&(_, leader)| leader))
})
})
}
/// Read the leader of the first page-number tab that is laid out. Layout chooses the next
/// stop after the text, including inherited and non-right stops.
fn entry_leader(s: &mut Session, tabs: &[(usize, usize)]) -> Option<TabLeader> {
if tabs.is_empty() {
return None;
}
let from_layout = |layout: &DocLayout| tabs.iter().find_map(|&(block, offset)| laid_out_leader(layout, Path::top(block), offset));
// A screen view can reflow the index to a different width or hide its result.
if !s.view.read_mode
&& s.view.mode == ViewMode::Print
&& !s.view.field_codes
&& let Some(leader) = from_layout(&s.layout())
{
return Some(leader);
}
if let Some(leader) = from_layout(&s.output_layout_of(&s.doc, false, false)) {
return Some(leader);
}
// Measure hidden separators without revealing other hidden text, which could move the tab
// past a different stop. The measurement leaves the document and view unchanged.
let mut measurement = s.doc.clone();
for &(block, offset) in tabs {
if let Ok(p) = measurement.para_mut(StoryRef::Body, &Path::top(block)) {
let _ = p.format(offset, offset + 1, &|props| props.hidden = Some(false));
}
}
if let Some(leader) = from_layout(&s.output_layout_of(&measurement, false, false)) {
return Some(leader);
}
// If the tab is still absent, retain an unambiguous saved leader.
let mut saved = tabs
.iter()
.filter_map(|&(block, _)| s.doc.body.get(block)?.as_para())
.flat_map(|p| s.doc.styles.resolve_para(&p.props).tabs)
.map(|tab| tab.leader);
let leader = saved.next()?;
saved.all(|other| other == leader).then_some(leader)
}
fn inline_entry_leader(s: &mut Session, i: usize) -> Option<TabLeader> {
let tabs: Vec<_> = s
.doc
.body
.iter()
.enumerate()
.skip(i + 1)
.map_while(|(j, b)| Some((j, b.as_para().filter(|p| super::citations::is_list_entry(p))?)))
.filter_map(|(j, p)| p.text.rfind('\t').map(|offset| (j, offset)))
.collect();
entry_leader(s, &tabs)
}
/// Read the leader before replacing a wrapped INDEX result, within the field's bounds.
pub(in crate::cmd) fn wrapped_entry_leader(s: &mut Session, i: usize, start: usize, last: usize, end: usize) -> Option<TabLeader> {
let tabs: Vec<_> = (i..=last)
.filter_map(|j| {
let p = s.doc.body.get(j)?.as_para()?;
let from = if j == i { start } else { 0 };
let to = if j == last { end } else { p.len() };
p.text.get(from..to)?.rfind('\t').map(|offset| (j, from + offset))
})
.collect();
entry_leader(s, &tabs)
}
/// The index Insert Index will update and the leader its current result shows.
pub fn index_settings(s: &mut Session) -> Option<(FieldCode, Option<TabLeader>)> {
if let Some((i, instr)) = index_field(s) {
let leader = inline_entry_leader(s, i);
return Some((FieldCode::parse(&instr), leader));
}
(0..s.doc.body.len()).find_map(|i| {
let (instr, start, last, end) = super::citations::wrapped_list(s, i)?;
let field = FieldCode::parse(&instr);
if field.name != "INDEX" {
return None;
}
Some((field, wrapped_entry_leader(s, i, start, last, end)))
})
}
/// Whether an INDEX field (a plain one or a range field, as Word files hold it) sits in the main
/// text's own paragraphs (`main`), or anywhere else a reader sees: a table cell, a text box, a
/// header or a footer in use. Stored headers and footers no page shows (a first-page header
@@ -188,6 +282,7 @@ fn range_index_after_text(s: &Session) -> bool {
fn insert_index(s: &mut Session, v: &Value) -> CmdResult {
let instr = index_instr(v);
check_index_reachable(s)?;
let leader = p::str(v, "tabLeader").map(leader).or_else(|| index_settings(s).and_then(|(_, leader)| leader)).unwrap_or(TabLeader::Dot);
// An index Word wrote as a range field is first made a plain field in its own paragraph, as
// Update Index makes it, so it takes the new settings rather than a second index being added
// beside it (#8034).
@@ -213,7 +308,7 @@ fn insert_index(s: &mut Session, v: &Value) -> CmdResult {
None => super::citations::generated_list(s, &instr, "Index")?,
}
if let Some((i, _)) = index_field(s) {
rebuild(s, i, p::str(v, "tabLeader").map(leader))?;
rebuild(s, i, Some(leader))?;
}
s.clamp_selection();
sel_result(s)
@@ -339,16 +434,18 @@ pub fn rebuild(s: &mut Session, i: usize, leader: Option<TabLeader>) -> Result<(
pub fn rebuild_from(s: &mut Session, i: usize, leader: Option<TabLeader>, instr: String) -> Result<(), CmdError> {
let f = FieldCode::parse(&instr);
// Old entries go; keep their leader and the section their columns had.
let mut old_leader = None;
let leader = leader.or_else(|| inline_entry_leader(s, i)).unwrap_or(TabLeader::Dot);
let old_len = s.doc.body.len();
let mut old_sect = None;
while let Some(p) = s.doc.body.get(i + 1).and_then(|b| b.as_para()).filter(|p| p.props.style.as_deref() == Some(ENTRY_STYLE)) {
old_leader = old_leader.or_else(|| p.props.tabs.as_ref().and_then(|t| t.last()).map(|t| t.leader));
while let Some(p) = s.doc.body.get(i + 1).and_then(|b| b.as_para()).filter(|p| super::citations::is_list_entry(p)) {
if p.section.is_some() {
old_sect = p.section.clone();
}
s.doc.remove_block(StoryRef::Body, &Path::top(i + 1))?;
}
let leader = leader.or(old_leader).unwrap_or(TabLeader::Dot);
if s.doc.body.len() != old_len {
s.touch();
}
let cols = f.arg('c').and_then(|c| c.trim().parse::<u32>().ok()).unwrap_or(1).clamp(1, 4);
let sep = f.arg('e').map(str::to_string).unwrap_or_else(|| ", ".into());
let run_in = f.has('r');
@@ -545,6 +642,86 @@ mod tests {
assert_eq!(s.doc.body[i + 2].as_para().unwrap().props.tabs.as_ref().unwrap()[0].leader, TabLeader::Hyphen);
}
#[test]
fn index_keeps_the_leader_used_by_the_page_number_tab() {
use std::sync::Arc;
let mut s = Session::new(wordcraft_doc::Document::from_text("Kilns are hot."));
s.run("references.markEntry", &json!({"entry": "Kilns"})).unwrap();
s.run("caret.docEnd", &json!({})).unwrap();
s.run("references.index", &json!({"rightAlign": true, "headings": false, "tabLeader": "hyphen"})).unwrap();
let (i, _) = index_field(&s).unwrap();
let path = Path::top(i + 1);
assert_eq!(s.doc.para(StoryRef::Body, &path).unwrap().plain_text(), "Kilns\t1");
for (align, leader, inherit_later_stop) in
[(TabAlign::Left, TabLeader::Underscore, false), (TabAlign::Right, TabLeader::Hyphen, true), (TabAlign::Left, TabLeader::None, true)]
{
let generated_pos = s.doc.para(StoryRef::Body, &path).unwrap().props.tabs.as_ref().unwrap()[0].pos;
Arc::make_mut(&mut s.doc.styles).get_mut(ENTRY_STYLE).unwrap().para.tabs =
inherit_later_stop.then(|| vec![TabStop { pos: generated_pos + 0.75, align: TabAlign::Right, leader: TabLeader::Dot }]);
let entry = s.doc.para_mut(StoryRef::Body, &path).unwrap();
// The text already runs past the first stop. The next one wins over the later style stop.
entry.props.tabs = Some(vec![TabStop { pos: 5.0, align: TabAlign::Right, leader: TabLeader::Dot }, TabStop { pos: 90.0, align, leader }]);
entry.touch();
s.touch();
assert_eq!(index_settings(&mut s).unwrap().1, Some(leader), "{align:?}, {inherit_later_stop}");
s.run("references.updateIndex", &json!({})).unwrap();
assert_eq!(index_settings(&mut s).unwrap().1, Some(leader), "kept on update: {align:?}, {inherit_later_stop}");
}
// Updating an imported field consumes the result, so its tab must be read before conversion.
let (_, instr) = index_field(&s).unwrap();
let header = s.doc.para_mut(StoryRef::Body, &Path::top(i)).unwrap();
let offset = header.object_offsets()[0];
header.delete(0, offset).unwrap();
header.objects[0] = InlineObject::FieldStart { instr, locked: false, dirty: false };
header.touch();
let entry = s.doc.para_mut(StoryRef::Body, &path).unwrap();
entry.props.tabs = Some(vec![TabStop { pos: 90.0, align: TabAlign::Center, leader: TabLeader::Hyphen }]);
entry.insert_object(entry.len(), InlineObject::FieldEnd, &CharProps::default()).unwrap();
s.touch();
assert_eq!(index_settings(&mut s).unwrap().1, Some(TabLeader::Hyphen));
s.run("references.updateIndex", &json!({})).unwrap();
assert!(s.doc.field_ranges(StoryRef::Body).is_empty());
assert_eq!(index_settings(&mut s).unwrap().1, Some(TabLeader::Hyphen), "kept through wrapped field conversion");
}
#[test]
fn index_keeps_the_page_number_leader_when_the_first_tab_is_hidden() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Kilns and wheels."));
s.view.marks = false;
s.prefs.marks.hidden = false;
for entry in ["Kilns", "Wheels"] {
s.run("references.markEntry", &json!({"entry": entry})).unwrap();
}
s.run("caret.docEnd", &json!({})).unwrap();
s.run("references.index", &json!({"rightAlign": true, "headings": false, "tabLeader": "hyphen"})).unwrap();
let (i, _) = index_field(&s).unwrap();
assert_eq!(index_lines(&s), ["Kilns\t1", "Wheels\t1"]);
for (first, second, hide_second, expected) in [
(TabLeader::Dot, TabLeader::Hyphen, false, TabLeader::Hyphen),
(TabLeader::Hyphen, TabLeader::Hyphen, true, TabLeader::Hyphen),
(TabLeader::Hyphen, TabLeader::None, false, TabLeader::None),
] {
for (block, leader, hidden) in [(i + 1, first, true), (i + 2, second, hide_second)] {
let p = s.doc.para_mut(StoryRef::Body, &Path::top(block)).unwrap();
p.props.tabs.as_mut().unwrap()[0].leader = leader;
let tab = p.text.rfind('\t').unwrap();
p.format(tab, tab + 1, &|props| props.hidden = Some(hidden)).unwrap();
}
s.touch();
let l = s.layout();
assert_eq!(laid_out_leader(&l, Path::top(i + 1), "Kilns".len()), None, "the hidden tab has no layout leader");
assert_eq!(laid_out_leader(&l, Path::top(i + 2), "Wheels".len()), (!hide_second).then_some(second));
assert_eq!(index_settings(&mut s).unwrap().1, Some(expected));
s.run("references.updateIndex", &json!({})).unwrap();
assert_eq!(index_settings(&mut s).unwrap().1, Some(expected), "kept on update");
}
}
/// #3670: an index in a table cell or a text box (as imported documents have it) can't be
/// rebuilt where it is, so Insert and Update Index say so, and Insert Index doesn't add a
/// second index at the caret.
+11 -5
View File
@@ -14,10 +14,10 @@ mod links;
mod objects;
pub(crate) use header_footer::saved_copy;
use header_footer::{create_hf, edit_hf, header_footer, new_empty_headers, strip_headers};
use header_footer::{create_hf, edit_hf, header_footer, new_empty_headers, remove_first_hf, strip_headers};
pub use items::{
DropCapState, default_date_picture, drop_cap_state, format_date, format_date_at, format_date_at_in, format_date_in, format_date_parts,
format_date_parts_in,
DropCapState, default_date_picture, default_time_picture, drop_cap_state, format_date, format_date_at, format_date_at_in, format_date_in,
format_date_parts, format_date_parts_in,
};
use items::{cover_page, date_time, drop_cap, drop_cap_off, field, page_number, symbol};
use links::{bookmark, delete_bookmark, link, link_targets};
@@ -56,7 +56,7 @@ pub fn specs() -> Vec<CommandSpec> {
.then_some("text boxes can't go inside a text box")
}),
CommandSpec::new("insert.link", "Link", "Insert › Links", link).key("Mod+K").params(
r#"{"url": string} | {"bookmark": name} | {"heading": block (see link.targets)} | {"top": true}, "text"?: string (Place in This Document: a bookmark, a heading or the top of the document)"#,
r#"{"url": string} | {"bookmark": name} | {"heading": block (see link.targets)} | {"top": true}, "text"?: string (Place in This Document: a bookmark, a heading or the top of the document); for every target, the result has a "warning" when a selection keeps its own text instead of "text""#,
),
CommandSpec::new("link.targets", "Link", "Insert › Links", link_targets).pure(),
CommandSpec::new("insert.removeLink", "Remove Hyperlink", "Insert › Links", |s, _| super::format::apply(s, &|c| {
@@ -86,6 +86,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("insert.closeHeader", "Close Header and Footer", "Header & Footer", |s, _| {
// Back where the caret was in the body, as Word does, not on page 1.
let back = s.hf_return.take().filter(|_| s.in_header_footer());
s.hf_section = None;
if !new_empty_headers(s).is_empty() {
// Its own undo step; a protected document keeps it, and the caret still leaves.
let _ = s.run("insert.removeEmptyHeaders", &json!({}));
@@ -102,6 +103,9 @@ pub fn specs() -> Vec<CommandSpec> {
sel_result(s)
}),
CommandSpec::new("insert.removeHeader", "Remove Header", "Insert › Header & Footer › Header", |s, _| {
if remove_first_hf(s, true)? {
return sel_result(s);
}
s.doc.last_section.headers = Default::default();
for path in s.doc.para_paths(StoryRef::Body) {
if s.doc.para(StoryRef::Body, &path).is_some_and(|p| p.section.is_some())
@@ -114,7 +118,9 @@ pub fn specs() -> Vec<CommandSpec> {
sel_result(s)
}),
CommandSpec::new("insert.removeFooter", "Remove Footer", "Insert › Header & Footer › Footer", |s, _| {
s.doc.last_section.footers = Default::default();
if !remove_first_hf(s, false)? {
s.doc.last_section.footers = Default::default();
}
sel_result(s)
}),
CommandSpec::new("insert.dateTime", "Date & Time", "Insert › Text", date_time).params(r#"{"format"?: "M/d/yyyy", "update"?: bool, "language"?: "en-US|pt-BR"}"#),
+78 -10
View File
@@ -3,6 +3,44 @@ use super::{
json, p, para_block,
};
fn slot_of(slot: wordcraft_layout::HfSlot, set: &wordcraft_doc::section::HeaderSet) -> Option<u32> {
match slot {
wordcraft_layout::HfSlot::First => set.first,
wordcraft_layout::HfSlot::Even => set.even,
wordcraft_layout::HfSlot::Default => set.default,
}
}
fn slot_of_mut(slot: wordcraft_layout::HfSlot, set: &mut wordcraft_doc::section::HeaderSet) -> &mut Option<u32> {
match slot {
wordcraft_layout::HfSlot::First => &mut set.first,
wordcraft_layout::HfSlot::Even => &mut set.even,
wordcraft_layout::HfSlot::Default => &mut set.default,
}
}
/// The header (or footer) shown on the caret's page/section (including an inherited one from an
/// earlier section), or a newly created one in the caret's section if none exists yet (#5855).
pub(super) fn shown_or_create_hf_part(s: &mut Session, header: bool) -> u32 {
let sec = crate::cmd::page::hf_section_of_focus(s);
let slot = {
let layout = s.layout();
let page = if s.sel.focus.story == StoryRef::Body { layout.page_of(&s.sel.focus) } else { Some(s.page_hint) };
page.and_then(|pg| layout.pages.get(pg)).map(|pg| pg.hf_slot).unwrap_or_default()
};
let sections = s.doc.sections();
if let Some(id) = sections
.iter()
.take(sec + 1)
.rev()
.find_map(|(_, sp)| slot_of(slot, if header { &sp.headers } else { &sp.footers }))
.filter(|id| s.doc.parts.contains_key(id))
{
return id;
}
hf_part(s, header)
}
/// The header (or footer) of the caret's section in the slot the caret's page uses (first page,
/// even page or the default), made when there is none: with Different First Page on, a header
/// inserted on page 1 is the one page 1 shows (#2826).
@@ -11,22 +49,15 @@ pub(super) fn hf_part(s: &mut Session, header: bool) -> u32 {
let layout = s.layout();
let page = if s.sel.focus.story == StoryRef::Body { layout.page_of(&s.sel.focus) } else { Some(s.page_hint) };
let slot = page.and_then(|pg| layout.pages.get(pg)).map(|pg| pg.hf_slot).unwrap_or_default();
fn slot_of(slot: wordcraft_layout::HfSlot, set: &mut wordcraft_doc::section::HeaderSet) -> &mut Option<u32> {
match slot {
wordcraft_layout::HfSlot::First => &mut set.first,
wordcraft_layout::HfSlot::Even => &mut set.even,
wordcraft_layout::HfSlot::Default => &mut set.default,
}
}
let mut sect = s.doc.section_mut(block).clone();
let existing = *slot_of(slot, if header { &mut sect.headers } else { &mut sect.footers });
let sect = s.doc.section_mut(block).clone();
let existing = slot_of(slot, if header { &sect.headers } else { &sect.footers });
if let Some(id) = existing.filter(|id| s.doc.parts.contains_key(id)) {
return id;
}
let style = if header { "Header" } else { "Footer" };
let id = s.doc.add_part(if header { PartKind::Header } else { PartKind::Footer }, vec![para_block(Paragraph::new().styled(style))]);
let sect = s.doc.section_mut(block);
*slot_of(slot, if header { &mut sect.headers } else { &mut sect.footers }) = Some(id);
*slot_of_mut(slot, if header { &mut sect.headers } else { &mut sect.footers }) = Some(id);
id
}
@@ -88,6 +119,7 @@ pub(super) fn header_footer(s: &mut Session, v: &Value, header: bool) -> CmdResu
Ok(json!({"story": id}))
}
/// Edit the header or footer shown on `page`, or at the caret's current body position.
pub(super) fn edit_hf(s: &mut Session, v: &Value, header: bool) -> CmdResult {
let mut page = p::u64(v, "page").map(|page| usize::try_from(page).unwrap_or(usize::MAX));
if page.is_none() && s.sel.focus.story == StoryRef::Body {
@@ -113,13 +145,46 @@ pub(super) fn edit_hf(s: &mut Session, v: &Value, header: bool) -> CmdResult {
return s.run(cmd, &params);
};
if let Some(page) = page {
// The page's section is what section commands act on; the body position Close Header and
// Footer returns to stays where it was (#3331).
s.page_hint = page;
let sec = s.layout().pages.get(page).map(|pg| pg.section);
s.hf_section = sec.map(|sec| sec.min(s.doc.sections().len().saturating_sub(1)));
}
s.touch();
s.sel = Selection::caret(s.doc.end_of(StoryRef::Part(id)));
Ok(json!({"story": id}))
}
/// Remove the first-page variant while it is being edited, keeping the other page variants.
pub(super) fn remove_first_hf(s: &mut Session, header: bool) -> Result<bool, CmdError> {
let StoryRef::Part(story) = s.sel.focus.story else { return Ok(false) };
let page = s.page_hint;
let layout = s.layout();
let Some(page) = layout.pages.get(page) else { return Ok(false) };
let shown = if header { page.header_story } else { page.footer_story };
if page.hf_slot != wordcraft_layout::HfSlot::First || shown != Some(story) {
return Ok(false);
}
let index = page.section;
let sections = s.doc.sections();
let Some(&(end, _)) = sections.get(index) else { return Ok(false) };
let last = index + 1 == sections.len();
let inherits_first = sections[..index].iter().any(|(_, sec)| if header { sec.headers.first.is_some() } else { sec.footers.first.is_some() });
// An absent slot would show the previous section's first-page story again.
let replacement = if inherits_first {
let (kind, style) = if header { (PartKind::Header, "Header") } else { (PartKind::Footer, "Footer") };
Some(s.doc.try_add_part(kind, vec![para_block(Paragraph::new().styled(style))])?)
} else {
None
};
let section = if last { &mut s.doc.last_section } else { s.doc.section_mut(end) };
let set = if header { &mut section.headers } else { &mut section.footers };
set.first = replacement;
s.sel = s.hf_return.take().unwrap_or_else(|| Selection::caret(s.doc.start_of(StoryRef::Body)));
Ok(true)
}
/// The header (or footer) page `page` shows, if any; an error for a page that isn't there.
fn shown_hf(s: &mut Session, page: usize, header: bool) -> Result<Option<u32>, CmdError> {
let layout = s.layout();
@@ -128,11 +193,14 @@ fn shown_hf(s: &mut Session, page: usize, header: bool) -> Result<Option<u32>, C
Ok(shown.filter(|id| s.doc.parts.contains_key(id)))
}
/// Create and edit a header or footer on `page`, or in the caret's section.
pub(super) fn create_hf(s: &mut Session, v: &Value, header: bool) -> CmdResult {
let id = match p::u64(v, "page") {
Some(page) => {
let page = usize::try_from(page).unwrap_or(usize::MAX);
let sec = s.layout().pages.get(page).map(|pg| pg.section).ok_or_else(|| CmdError::Params(format!("no page {page}")))?;
s.page_hint = page;
s.hf_section = Some(sec.min(s.doc.sections().len().saturating_sub(1)));
page_hf_part(s, page, header)?
}
None => {
+36 -2
View File
@@ -1,5 +1,5 @@
use super::PartKind;
use super::header_footer::hf_part;
use super::header_footer::shown_or_create_hf_part;
use super::{
Align, Block, CharProps, CmdError, CmdResult, InlineObject, Paragraph, Rgb, Selection, Session, StoryRef, TabAlign, TabStop, TextColor, Value,
delete_selection, json, p, para_block, sel_result, type_text, type_text_with_lang,
@@ -85,7 +85,7 @@ pub(super) fn page_number(s: &mut Session, v: &Value) -> CmdResult {
return sel_result(s);
}
let header = position == "top";
let id = hf_part(s, header);
let id = shown_or_create_hf_part(s, header);
let story = StoryRef::Part(id);
let style = if header { "Header" } else { "Footer" };
let mut para = page_number_paragraph(style, align, x_of_y)?;
@@ -218,6 +218,8 @@ struct DateNames {
days_short: [&'static str; 7],
/// The picture of a `DATE` field without `\@`.
default: &'static str,
/// The picture of a `TIME` field without `\@`.
default_time: &'static str,
}
const ENGLISH: DateNames = DateNames {
@@ -226,6 +228,7 @@ const ENGLISH: DateNames = DateNames {
days: ["Thursday", "Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday"],
days_short: ["Thu", "Fri", "Sat", "Sun", "Mon", "Tue", "Wed"],
default: "M/d/yyyy",
default_time: "h:mm am/pm",
};
/// Portuguese (observed in Word for Mac with a pt-BR document): lower-case names, `MMM` = `out`,
@@ -236,6 +239,7 @@ const PORTUGUESE: DateNames = DateNames {
days: ["quinta-feira", "sexta-feira", "sábado", "domingo", "segunda-feira", "terça-feira", "quarta-feira"],
days_short: ["qui", "sex", "sáb", "dom", "seg", "ter", "qua"],
default: "dd/MM/yyyy",
default_time: "h:mm am/pm",
};
/// German (Word's Windows NLS forms): `MMMM` = `März`, `MMM` = `Mrz`, `ddd` = `Fr` (two
@@ -246,6 +250,7 @@ const GERMAN: DateNames = DateNames {
days: ["Donnerstag", "Freitag", "Samstag", "Sonntag", "Montag", "Dienstag", "Mittwoch"],
days_short: ["Do", "Fr", "Sa", "So", "Mo", "Di", "Mi"],
default: "dd.MM.yyyy",
default_time: "HH:mm",
};
/// Austrian Standard German: January is `Jänner`, abbreviated `Jän` (Österreichisches
@@ -256,6 +261,7 @@ const GERMAN_AUSTRIA: DateNames = DateNames {
days: ["Donnerstag", "Freitag", "Samstag", "Sonntag", "Montag", "Dienstag", "Mittwoch"],
days_short: ["Do", "Fr", "Sa", "So", "Mo", "Di", "Mi"],
default: "dd.MM.yyyy",
default_time: "HH:mm",
};
/// Choose month and weekday names from the language tag: the primary subtag picks the language,
@@ -279,6 +285,12 @@ pub fn default_date_picture(lang: Option<&str>) -> &'static str {
date_names(lang).default
}
/// The picture Word gives a `TIME` field that has no `\@` switch, in the field's language: German
/// shows the 24-hour clock (#8562).
pub fn default_time_picture(lang: Option<&str>) -> &'static str {
date_names(lang).default_time
}
/// Format a date and time with a Word picture; `days_since` (days since 1970-01-01) gives the weekday.
pub fn format_date_parts(fmt: &str, y: i64, m: usize, d: u32, hms: (u32, u32, u32), days_since: i64) -> String {
format_date_parts_in(fmt, None, y, m, d, hms, days_since)
@@ -622,6 +634,28 @@ mod date_time_locale_tests {
assert_eq!(default_date_picture(Some("de-CH")), "dd.MM.yyyy");
}
/// A `TIME` field without `\@` shows the 24-hour clock in a German document and the 12-hour
/// clock in an English one (#8562).
#[test]
fn bare_time_field_follows_the_document_language() {
let refreshed = |lang: &str| {
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("review.language", &json!({"lang": lang, "default": true})).unwrap();
s.run("insert.field", &json!({"instr": "TIME", "result": "stale"})).unwrap();
crate::cmd::references::refresh_date_fields(&mut s.doc);
let path = s.doc.para_paths(StoryRef::Body).remove(0);
let p = s.doc.para(StoryRef::Body, &path).unwrap();
let result = p.objects.iter().find_map(|o| if let InlineObject::Field { result, .. } = o { Some(result.clone()) } else { None });
result.expect("a TIME field")
};
for lang in ["de-DE", "de-AT", "de-CH"] {
let time = refreshed(lang);
assert!(time != "stale" && !time.contains("AM") && !time.contains("PM"), "{lang}: {time}");
}
let time = refreshed("en-US");
assert!(time.contains("AM") || time.contains("PM"), "en-US: {time}");
}
/// Windows NLS short forms: two-letter weekdays (`Mo`, `Di`…) and `Mrz` for March, with no
/// trailing full stop (#7146).
#[test]
+10
View File
@@ -75,11 +75,21 @@ pub(super) fn link(s: &mut Session, v: &Value) -> CmdResult {
s.sel = Selection::caret(end);
s.pending = Some(CharProps::default());
} else {
// A Text to display that differs from the selection but can't retype it is not applied:
// the caller is told so rather than left to think it was (#8541).
let kept = p::str(v, "text").is_some_and(|t| !t.is_empty() && one_line_selection(s) != Some(t) && s.selected_text() != t);
let (a, b) = s.sel.ordered();
s.doc.format_range(&a, &b, &|c| {
c.link = Some(url.clone());
c.style = style.clone();
})?;
if kept {
const KEPT: &str = "Text to display was not applied: the selection is linked with its own text.";
s.status = KEPT.into();
let mut out = sel_result(s)?;
out["warning"] = json!(KEPT);
return Ok(out);
}
}
sel_result(s)
}
+168
View File
@@ -133,6 +133,108 @@ fn different_first_page_header_is_reachable_from_page_one() {
assert_eq!((s.doc.last_section.footers.first, s.doc.last_section.footers.default), (Some(foot), None));
}
#[test]
fn removing_a_first_page_header_or_footer_keeps_the_default() {
let mut s = two_pages();
s.run("layout.differentFirstPage", &json!({"value": true})).unwrap();
for (cmd, page, text) in [
("insert.editHeader", 0, "Cover header"),
("insert.editHeader", 1, "Default header"),
("insert.editFooter", 0, "Cover footer"),
("insert.editFooter", 1, "Default footer"),
] {
s.run(cmd, &json!({"page": page})).unwrap();
s.run("text.insert", &json!({"text": text})).unwrap();
s.run("insert.closeHeader", &json!({})).unwrap();
}
let page_stories = |s: &mut Session| {
let pages = &s.layout().pages;
assert_eq!(pages.len(), 2);
[(pages[0].header_story, pages[0].footer_story), (pages[1].header_story, pages[1].footer_story)]
};
let [first, default] = page_stories(&mut s);
assert!(first.0.is_some() && first.1.is_some());
assert!(default.0.is_some() && default.1.is_some());
assert_ne!(first, default);
s.run("insert.editHeader", &json!({"page": 0})).unwrap();
s.run("insert.removeHeader", &json!({})).unwrap();
assert_eq!(page_stories(&mut s), [(None, first.1), default]);
assert_eq!(s.sel.focus.story, StoryRef::Body);
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(page_stories(&mut s), [first, default]);
s.run("insert.closeHeader", &json!({})).unwrap();
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
s.run("insert.removeFooter", &json!({})).unwrap();
assert_eq!(page_stories(&mut s), [(first.0, None), default]);
assert_eq!(s.sel.focus.story, StoryRef::Body);
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(page_stories(&mut s), [first, default]);
}
#[test]
fn refused_first_page_removal_keeps_the_selection_for_close_header_and_footer() {
let mut s = two_pages();
s.run("layout.differentFirstPage", &json!({"value": true})).unwrap();
for (edit, text) in [("insert.editHeader", "Cover header"), ("insert.editFooter", "Cover footer")] {
s.run(edit, &json!({"page": 0})).unwrap();
s.run("text.insert", &json!({"text": text})).unwrap();
s.run("insert.closeHeader", &json!({})).unwrap();
}
s.run("select.text", &json!({"text": "Two"})).unwrap();
s.run("review.restrict", &json!({"exception": "add"})).unwrap();
s.run("review.restrict", &json!({"mode": "readOnly"})).unwrap();
let body_selection = s.sel.clone();
assert_eq!(s.selected_text(), "Two");
let before = s.doc.clone();
for (edit, remove) in [("insert.editHeader", "insert.removeHeader"), ("insert.editFooter", "insert.removeFooter")] {
s.run(edit, &json!({"page": 0})).unwrap();
let editing = s.sel.clone();
assert!(s.in_header_footer());
let error = s.run(remove, &json!({})).unwrap_err().to_string();
assert!(error.contains("only the editable regions"), "{error}");
assert_eq!(s.doc, before);
assert_eq!(s.sel, editing, "the refusal leaves the editor in the first-page story");
s.run("insert.closeHeader", &json!({})).unwrap();
assert_eq!(s.sel, body_selection, "explicit Close returns to the saved selection after {remove}");
}
}
#[test]
fn removing_an_inherited_first_page_header_keeps_the_previous_section() {
let mut s = two_pages();
s.run("layout.differentFirstPage", &json!({"value": true})).unwrap();
let first = s.run("insert.editHeader", &json!({"page": 0})).unwrap()["story"].as_u64().unwrap() as u32;
s.run("text.insert", &json!({"text": "Cover header"})).unwrap();
s.run("insert.closeHeader", &json!({})).unwrap();
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
s.run("text.insert", &json!({"text": "Section two"})).unwrap();
s.run("layout.differentFirstPage", &json!({"value": true})).unwrap();
// Start with a linked first-page slot in the later section.
s.doc.last_section.headers.first = None;
s.touch();
let page = s.layout().pages.iter().position(|page| page.section == 1).unwrap();
assert_eq!(s.layout().pages[page].header_story, Some(first));
s.run("insert.editHeader", &json!({"page": page})).unwrap();
s.run("insert.removeHeader", &json!({})).unwrap();
let blank = s.doc.last_section.headers.first.unwrap();
assert_ne!(blank, first);
assert_eq!(s.layout().pages[0].header_story, Some(first));
assert_eq!(s.layout().pages[page].header_story, Some(blank));
assert!(s.doc.para(StoryRef::Part(blank), &Path(vec![0])).unwrap().text.is_empty());
let saved = wordcraft_docx::write(&s.doc).unwrap();
let mut reopened = Session::new(wordcraft_docx::read(&saved).unwrap());
let reopened_layout = reopened.layout();
let cover = reopened_layout.pages[0].header_story.unwrap();
let blank = reopened_layout.pages.iter().find(|page| page.section == 1).unwrap().header_story.unwrap();
assert_eq!(reopened.doc.para(StoryRef::Part(cover), &Path(vec![0])).unwrap().text.as_str(), "Cover header");
assert!(reopened.doc.para(StoryRef::Part(blank), &Path(vec![0])).unwrap().text.is_empty());
}
fn two_pages() -> Session {
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("text.insert", &json!({"text": "One"})).unwrap();
@@ -214,6 +316,24 @@ fn new_header_links_to_previous_and_even_pages_edit_what_they_show() {
assert_eq!(s.doc.sections()[0].1.headers.even, None, "nothing made");
}
/// Edit Header from the body on a later section's page makes the header in the first section,
/// linked through to every page, as on main: the caret's page selects the page, not the section.
#[test]
fn edit_header_from_the_body_links_to_previous_sections() {
let mut s = two_pages();
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
s.run("text.insert", &json!({"text": "Three"})).unwrap();
let pages = s.layout().pages.len();
assert!(pages >= 3 && s.layout().pages[pages - 1].section == 1, "a second section");
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
let id = s.run("insert.editHeader", &json!({})).unwrap()["story"].as_u64().unwrap() as u32;
s.run("text.insert", &json!({"text": "Draft"})).unwrap();
s.run("insert.closeHeader", &json!({})).unwrap();
assert!(s.layout().pages.iter().all(|p| p.header_story == Some(id)), "every page shows it");
assert_eq!(s.doc.sections()[0].1.headers.default, Some(id), "made in the first section");
assert_eq!(s.doc.sections()[1].1.headers.default, None, "the later section inherits it");
}
#[test]
fn base64_round_trip() {
let data = b"hello world!?";
@@ -418,6 +538,54 @@ fn local_civil_date_follows_the_utc_offset() {
}
}
/// Close Header and Footer restores the body selection, with or without a page argument.
#[test]
fn close_header_preserves_original_body_selection() {
let mut s = Session::new(wordcraft_doc::Document::from_text("First paragraph.\nSecond paragraph with more text."));
// Place caret at offset 7 in the second paragraph.
s.sel = Selection::caret(Pos::new(StoryRef::Body, Path::top(1), 7));
let original = s.sel.clone();
// Edit footer from ribbon without a page argument.
s.run("insert.editFooter", &json!({})).unwrap();
assert!(s.in_header_footer());
// Close header and footer.
s.run("insert.closeHeader", &json!({})).unwrap();
assert_eq!(s.sel, original, "original body selection was preserved without page argument");
// Edit footer explicitly specifying the page of the current section.
s.sel = original.clone();
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
assert!(s.in_header_footer());
// Close header and footer.
s.run("insert.closeHeader", &json!({})).unwrap();
assert_eq!(s.sel, original, "original body selection was preserved with same-section page argument");
}
/// Entering a header or footer on another section's page leaves the body caret that Close Header
/// and Footer returns to where it was (#3331); the page only picks the section commands act on.
#[test]
fn closing_a_header_on_another_sections_page_returns_to_the_body_caret() {
let mut s = Session::new(wordcraft_doc::Document::from_text("front\nbody"));
s.run("select.text", &json!({"text": "front"})).unwrap();
s.run("caret.end", &json!({})).unwrap();
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
s.run("text.insert", &json!({"text": "Footer on sec 0"})).unwrap();
s.run("insert.closeHeader", &json!({})).unwrap();
// The body caret stays in the first section, page 1 belongs to the second.
let before = Selection::caret(Pos::new(StoryRef::Body, Path::top(0), 2));
s.sel = before.clone();
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
// A click into the footer on page 1's page, while the footer is open.
s.run("insert.editFooter", &json!({"page": 1})).unwrap();
assert!(s.in_header_footer());
s.run("insert.closeHeader", &json!({})).unwrap();
assert_eq!(s.sel, before);
}
#[test]
fn shared_base64_preserves_command_payload_bytes() {
for (plain, encoded) in [("", ""), ("f", "Zg=="), ("fo", "Zm8="), ("foo", "Zm9v"), ("foobar", "Zm9vYmFy")] {
+12
View File
@@ -668,6 +668,18 @@ fn recipient_lists_in_legacy_and_utf16_encodings() {
assert_eq!(s.merge.rows, [["José"]]);
}
#[test]
fn recipient_list_with_generic_utf32_uses_its_big_endian_bom() {
let mut data = vec![0x00, 0x00, 0xFE, 0xFF];
for c in "Name,City\nAda,A🌍\n".chars() {
data.extend_from_slice(&(c as u32).to_be_bytes());
}
let mut s = Session::new(Document::new());
s.run("mailings.recipients", &json!({"path": "list.csv", "data": b64(&data), "encoding": "utf-32"})).unwrap();
assert_eq!(s.merge.headers, ["Name", "City"]);
assert_eq!(s.merge.rows, [["Ada", "A🌍"]]);
}
/// #778: legacy Excel 97–2003 workbooks are recipient lists; a CSV named .xls reads as text.
#[test]
fn recipients_from_an_xls_workbook() {
+4 -2
View File
@@ -21,7 +21,7 @@ mod shape;
mod specs;
pub use arrange::moves_with_text;
pub(crate) use arrange::{anchor_paragraph, nearest_line};
pub(crate) use arrange::{anchor_paragraph, nearest_line, shifted_float_offset};
#[cfg(test)]
use group::ungroup;
pub use picture::{OriginalSize, PictureLook, cropped_original_size, fit_size, original_size};
@@ -33,7 +33,9 @@ pub(crate) use select::select_object;
pub(crate) use select::{edit_obj, has_shape_or_canvas};
#[cfg(test)]
use select::{has_group, holds_ink, obj_size, with_obj};
pub use select::{min_size, object_selection, picked_objects, selected, selected_all, selected_or_text_box, target_objects};
pub use select::{
has_picture_format_target, min_size, object_selection, picked_objects, selected, selected_all, selected_or_text_box, target_objects,
};
#[cfg(test)]
use shape::can_link;
pub(crate) use shape::set_text_body;
+46 -3
View File
@@ -24,8 +24,22 @@ pub(super) fn bounds(s: &mut Session, v: &Value) -> CmdResult {
// A size not given stays as it is: a move must not give a level line (0 high) a height.
let w = p::f32(v, "width").map_or(w0, |w| w.clamp(min, MAX_OFFSET));
let h = p::f32(v, "height").map_or(h0, |h| h.clamp(min, MAX_OFFSET));
if (w, h) != (w0, h0) {
with_obj(s, |o| o.set_size(w, h))?;
// A size given sets that side outright, in place of a share of the page or a margin (#6770),
// even one equal to the object's own size, which the share hid.
let shared = obj.frame().map_or((false, false), |(_, _, f)| (f.rel_w.is_some(), f.rel_h.is_some()));
let (set_w, set_h) = (p::f32(v, "width").is_some() && shared.0, p::f32(v, "height").is_some() && shared.1);
if (w, h) != (w0, h0) || set_w || set_h {
with_obj(s, |o| {
o.set_size(w, h);
if let Some(f) = o.float_mut() {
if set_w {
f.rel_w = None;
}
if set_h {
f.rel_h = None;
}
}
})?;
}
let pos = match (to, in_text) {
(Some((x, y)), _) => move_object(s, pos, p::u64(v, "page"), x, y, (w, h))?,
@@ -212,9 +226,29 @@ fn move_object_once(s: &mut Session, pos: &Pos, page: usize, x: f32, y: f32, (w,
f.x = (x - origin.x).clamp(-MAX_OFFSET, MAX_OFFSET);
f.y = (y - origin.y).clamp(-MAX_OFFSET, MAX_OFFSET);
})?;
if let Some(offset) = shifted_float_offset(s, &at, page, y, origin.y) {
edit_float(s, &at, |f| f.y = offset.clamp(-MAX_OFFSET, MAX_OFFSET))?;
}
Ok(at)
}
/// A page-to-paragraph conversion can make a float move from the unpushed paragraph top to
/// the pushed first line. Once layout has resolved that choice, offset from the origin it used.
/// Leave other layout effects, such as wrapping settlement or a change of page, to the caller.
pub(crate) fn shifted_float_offset(s: &mut Session, at: &Pos, page: usize, y: f32, old_origin: f32) -> Option<f32> {
let offset = y - old_origin;
if offset >= 0.0
|| at.story != StoryRef::Body
|| at.path.depth() != 0
|| (!s.view.read_mode && !matches!(s.view.mode, wordcraft_layout::ViewMode::Print | wordcraft_layout::ViewMode::Read))
{
return None;
}
s.touch();
let hit = s.layout().object(at, page)?;
(hit.page == page && hit.origin.y > old_origin + 0.01 && (hit.rect.y - hit.origin.y - offset).abs() < 0.01).then_some(y - hit.origin.y)
}
/// Turn the selected floating object's alignment (left, centred, …) into an offset from its
/// column / paragraph that keeps it where it is, so it can be moved by an offset.
pub(super) fn unalign(s: &mut Session) -> Result<(), CmdError> {
@@ -245,6 +279,12 @@ pub(super) fn unalign(s: &mut Session) -> Result<(), CmdError> {
f.y = oy.clamp(-MAX_OFFSET, MAX_OFFSET);
}
})?;
if float.v_align.is_some()
&& float.v_rel != Anchor::Page
&& let Some(offset) = shifted_float_offset(s, &pos, hit.page, hit.rect.y, hit.origin.y)
{
edit_float(s, &pos, |f| f.y = offset.clamp(-MAX_OFFSET, MAX_OFFSET))?;
}
Ok(())
}
@@ -268,11 +308,14 @@ pub(super) fn move_with_text(s: &mut Session, with_text: bool) -> CmdResult {
let hit = s.layout().object(&pos, s.page_hint).ok_or_else(|| CmdError::Failed("the object isn't laid out".into()))?;
// Paragraph offsets start at the paragraph's top (the hit's origin), page offsets at the page's.
let y = if with_text { hit.rect.y - hit.origin.y } else { hit.rect.y };
let o = edit_float(s, &pos, |f| {
let mut o = edit_float(s, &pos, |f| {
f.v_rel = if with_text { Anchor::Paragraph } else { Anchor::Page };
f.v_align = None;
f.y = y.clamp(-MAX_OFFSET, MAX_OFFSET);
})?;
if with_text && let Some(offset) = shifted_float_offset(s, &pos, hit.page, hit.rect.y, hit.origin.y) {
o = edit_float(s, &pos, |f| f.y = offset.clamp(-MAX_OFFSET, MAX_OFFSET))?;
}
Ok(json!({"object": serde_json::to_value(o).unwrap_or(Value::Null)}))
}
+48 -5
View File
@@ -116,8 +116,13 @@ pub(super) fn group(s: &mut Session, _: &Value) -> CmdResult {
GroupChild { x: x - x0, y: y - y0, obj }
})
.collect();
// The group takes the first member's placement; its members keep their own alt text.
let mut float = found.first().and_then(|(o, _)| o.frame()).map(|(_, _, f)| Float { alt: Default::default(), ..f.clone() }).unwrap_or_default();
// The group takes the first member's placement, not its size as a share of the page or a
// margin (the group's box is the one around its members); its members keep their own alt text.
let mut float = found
.first()
.and_then(|(o, _)| o.frame())
.map(|(_, _, f)| Float { alt: Default::default(), rel_w: None, rel_h: None, ..f.clone() })
.unwrap_or_default();
float.set_spin(Spin::default());
let grouped = InlineObject::Group { w, h, float, ch_w: w, ch_h: h, children, canvas: None };
// Take the members out, last first so the earlier positions hold, and put the group where
@@ -147,7 +152,9 @@ pub(super) fn ungroup(s: &mut Session, _: &Value) -> CmdResult {
return Err(CmdError::Disabled(INK_GROUP.into()));
}
// Its offsets, explicit: the members are placed from the same anchor.
let pos = if float.wrap == Wrap::Inline {
// In line with text it is drawn at its own size, whatever share it holds.
let was_inline = float.wrap == Wrap::Inline;
let pos = if was_inline {
if pos.path.depth() > 0 || !movable_story(s, pos.story) {
return Err(CmdError::Disabled("only groups in the body text, headers and footers can be ungrouped in line with text".into()));
}
@@ -159,8 +166,43 @@ pub(super) fn ungroup(s: &mut Session, _: &Value) -> CmdResult {
};
let obj = s.doc.para_at(&pos).and_then(|p| p.object_at(pos.off)).cloned().ok_or_else(|| CmdError::Failed("object vanished".into()))?;
let Some((w, h, float)) = obj.frame() else { return Err(CmdError::Failed("object vanished".into())) };
let float = float.clone();
// Each member where the group shows it: the group's turn moves its centre about the group's
// A floating group sized as a share of the page or a margin shows its members at the size it
// is drawn at; they take their places and sizes there, not the share (each would be all of it).
// One that was in line with text was drawn at its own size.
let shared = !was_inline && (float.rel_w.is_some() || float.rel_h.is_some());
// Where the group is drawn: its size there, and the page whose width, height or margin its
// share is a share of.
let lay = shared.then(|| s.layout());
let drawn = lay.as_ref().and_then(|lay| {
let hit = lay.object(&pos, s.page_hint)?;
Some((hit.rect.w, hit.rect.h, lay.pages.get(hit.page)?))
});
let (w, h) = drawn.map_or((w, h), |(dw, dh, _)| (dw, dh));
let group_share = (float.rel_w, float.rel_h);
let float = Float { rel_w: None, rel_h: None, ..float.clone() };
// What the group's share is of on each axis, as layout placed it on that page: in the
// section its anchor is in (a header's or footer's goes with the page's), on the page that
// section is laid out on in the view (as wide as the window in the continuous views, on its
// side in a turned section).
let anchor_block = (pos.story == wordcraft_doc::StoryRef::Body).then(|| pos.path.0.first().copied()).flatten();
let si = anchor_block.and_then(|b| s.doc.sections().iter().position(|(end, _)| b as usize <= *end));
let view = s.view_layout_options();
let base_of = |share: Option<wordcraft_doc::para::RelSize>, across: bool| {
let (r, (_, _, page)) = (share?, drawn?);
Some(wordcraft_layout::share_base_on(&s.doc, page, si, &view, r.from, across))
};
let bases = (base_of(group_share.0, true), base_of(group_share.1, false));
// A member drawn past the 4000 pt an object's own size stops at keeps the size it showed as a
// share of what the group's share is of (its drawn length over that length); a smaller one
// takes its size outright.
let part = |share: Option<wordcraft_doc::para::RelSize>, member: f32, across: bool| {
let r = share.filter(|_| member > MAX_OFFSET)?;
let base = if across { bases.0 } else { bases.1 }?;
(base > 0.0).then(|| wordcraft_doc::para::RelSize {
pct: (f64::from(member) / f64::from(base) * 100_000.0).round().clamp(1.0, f64::from(u32::MAX)) as u32,
..r
})
}; // Each member where the group shows it: the group's turn moves its centre about the group's
// centre and adds to its own turn.
let members: Vec<InlineObject> = shown_members(&obj, [0.0, 0.0, w, h])
.into_iter()
@@ -175,6 +217,7 @@ pub(super) fn ungroup(s: &mut Session, _: &Value) -> CmdResult {
let alt = std::mem::take(&mut f.alt);
*f = Float { x: (float.x + x).clamp(-MAX_OFFSET, MAX_OFFSET), y: (float.y + y).clamp(-MAX_OFFSET, MAX_OFFSET), alt, ..float.clone() };
f.set_spin(spin);
(f.rel_w, f.rel_h) = (part(group_share.0, mw, true), part(group_share.1, mh, false));
}
c
})
+50 -5
View File
@@ -1,4 +1,4 @@
use super::select::{edit_obj, is_shape_or_canvas, obj_size, selected, target_objects, with_obj};
use super::select::{edit_obj, has_picture, is_shape_or_canvas, obj_size, select_object, selected, target_objects, with_obj};
use super::{CmdError, CmdResult, InlineObject, Pos, Rgb, Session, Value, Wrap, json, p};
use wordcraft_doc::picfx::PicFx;
@@ -70,9 +70,10 @@ pub fn cropped_original_size(s: &Session, o: &InlineObject) -> Option<(f32, f32)
Some((orig.w * part(crop[0], crop[2]), orig.h * part(crop[1], crop[3])))
}
fn planned_size(s: &Session, o: &InlineObject, v: &Value) -> Result<(f32, f32), CmdError> {
fn planned_size(s: &mut Session, pos: &Pos, o: &InlineObject, v: &Value) -> Result<(f32, f32), CmdError> {
let lock = p::bool(v, "lockAspect").unwrap_or(true);
let (w0, h0) = obj_size(o);
let has_share = o.frame().is_some_and(|(_, _, f)| f.rel_w.is_some() || f.rel_h.is_some());
let (w0, h0) = if has_share { s.layout().object(pos, s.page_hint).map_or_else(|| obj_size(o), |r| (r.rect.w, r.rect.h)) } else { obj_size(o) };
let (mut w, mut h) = (w0, h0);
let scale = p::f32(v, "scale");
let original = p::bool(v, "original").unwrap_or(false);
@@ -128,15 +129,35 @@ fn size_matching(s: &mut Session, v: &Value, pred: impl Fn(&InlineObject) -> boo
if targets.is_empty() {
return Err(CmdError::Disabled(empty_msg.into()));
}
let planned: Vec<(Pos, f32, f32)> =
targets.into_iter().map(|(pos, o)| planned_size(s, &o, v).map(|(w, h)| (pos, w, h))).collect::<Result<Vec<_>, _>>()?;
let mut planned = Vec::with_capacity(targets.len());
for (pos, o) in targets {
let (w, h) = planned_size(s, &pos, &o, v)?;
planned.push((pos, w, h));
}
let lock = p::bool(v, "lockAspect").unwrap_or(true);
let (has_w, has_h) = (p::f32(v, "width").is_some(), p::f32(v, "height").is_some());
let both = p::bool(v, "original").unwrap_or(false) || p::f32(v, "scale").is_some() || (lock && (has_w || has_h));
let (clear_w, clear_h) = (both || has_w, both || has_h);
// Any drawing: a group's members scale with its frame (its child space is kept); a chart or
// SmartArt graphic lays itself out again at the new size.
let theme = s.doc.settings.theme_colors.clone();
let mut last = Value::Null;
for (pos, w, h) in &planned {
let o = edit_obj(s, pos, |o| {
let saved = o.frame().map(|(_, _, f)| (f.rel_w, f.rel_h));
o.set_size(*w, *h);
if let Some(f) = o.float_mut() {
if clear_w {
f.rel_w = None;
} else if let Some((rw, _)) = saved {
f.rel_w = rw;
}
if clear_h {
f.rel_h = None;
} else if let Some((_, rh)) = saved {
f.rel_h = rh;
}
}
crate::cmd::chart::redraw(o, &theme);
crate::cmd::smart_art::redraw(o, &theme);
})?;
@@ -186,6 +207,30 @@ pub fn fit_size(w: f32, h: f32, keep: bool) -> (f32, f32) {
(side(w), side(h))
}
/// Runs a one-picture command on each selected picture in turn (several selected with Shift or
/// Ctrl+click, #8832), one undo step. The selection is as it was afterwards.
pub(super) fn each_picture(s: &mut Session, run: impl Fn(&mut Session) -> CmdResult) -> CmdResult {
let picks = target_objects(s, |o| matches!(o, InlineObject::Image { .. }));
if picks.is_empty() || (picks.len() == 1 && has_picture(s).is_none()) {
return run(s);
}
let (sel, also) = (s.sel.clone(), s.also_selected.clone());
// The failed command's rollback restores the document but not these maps: put them back too.
let (originals, looks) = (s.originals.clone(), s.picture_looks.clone());
let mut out = Ok(Value::Null);
for (pos, _) in &picks {
select_object(s, pos);
s.also_selected.clear();
out = run(s);
if out.is_err() {
(s.originals, s.picture_looks) = (originals, looks);
break;
}
}
(s.sel, s.also_selected) = (sel, also);
out
}
/// Apply an image operation to the selected picture's bitmap (stored as a new PNG).
pub(super) fn adjust(s: &mut Session, f: impl Fn(image::DynamicImage) -> Result<image::DynamicImage, CmdError>) -> CmdResult {
let (_, o) = selected(s).ok_or_else(|| CmdError::Disabled("no picture".into()))?;
+11
View File
@@ -7,6 +7,17 @@ pub(super) fn has_picture(s: &Session) -> Option<&'static str> {
}
}
/// Whether commands that already format multiple pictures have a target. A secondary
/// picture can be in the text range or among explicitly picked objects.
pub fn has_picture_format_target(s: &Session) -> bool {
has_picture(s).is_none()
|| ((!s.sel.is_collapsed() || !s.also_selected.is_empty()) && !target_objects(s, |o| matches!(o, InlineObject::Image { .. })).is_empty())
}
pub(super) fn has_any_picture(s: &Session) -> Option<&'static str> {
(!has_picture_format_target(s)).then_some("select a picture first")
}
/// Guard returning `None` when a picture, shape, or active text box is selected.
pub(super) fn has_object(s: &Session) -> Option<&'static str> {
if selected_or_text_box(s).is_some() { None } else { Some("select a picture or shape first") }
+104 -84
View File
@@ -1,10 +1,12 @@
use super::arrange::{MAX_OFFSET, bounds, copy_to, move_with_text, unalign};
use super::group::{add_object, group, ungroup};
use super::picture::{adjust, adjust_media, clear_lum, crop, original_media, recolor, relook, remove_background, reset, shape_size, size};
use super::picture::{
adjust, adjust_media, clear_lum, crop, each_picture, original_media, recolor, relook, remove_background, reset, shape_size, size,
};
use super::select::{
all_objects, alt_text, can_group, edit_obj, has_any_movable, has_any_shape, has_floating, has_group, has_movable, has_object, has_picture,
has_placeable, has_shape, has_shape_or_canvas, has_sizable, is_shape_or_canvas, obj_size, objects_list, selected_or_text_box, target_objects,
with_float, with_floats_matching, with_movable_floats, with_obj,
all_objects, alt_text, can_group, edit_obj, has_any_movable, has_any_picture, has_any_shape, has_floating, has_group, has_movable, has_object,
has_picture, has_placeable, has_shape, has_shape_or_canvas, has_sizable, is_shape_or_canvas, obj_size, objects_list, selected_or_text_box,
target_objects, with_float, with_floats_matching, with_movable_floats, with_obj,
};
use super::shape::{NO_TEXT_BOX, can_link, has_text_box, link_text_box, set_text_body, shape_effects, text_box_target};
use super::{CmdError, CommandSpec, InlineObject, Pos, Rgb, Selection, Spin, TextVert, VAlign, Wrap, WrapText, json, p, sel_result};
@@ -58,98 +60,112 @@ pub fn specs() -> Vec<CommandSpec> {
.params(r#"{"text"?: string, "title"?: string, "decorative"?: bool} (the selected picture, shape, text box, group or chart)"#)
.when(has_object),
CommandSpec::new("picture.corrections", "Corrections", "Picture Format › Adjust", |s, v| {
let b = p::f32(v, "brightness").unwrap_or(0.0).clamp(-100.0, 100.0);
let c = p::f32(v, "contrast").unwrap_or(0.0).clamp(-100.0, 100.0);
let sharpen = p::f32(v, "sharpen").unwrap_or(0.0).clamp(-100.0, 100.0);
// Absolute from the original (like transparency): re-setting all three to 0
// restores the original pixels instead of stacking on the last pass.
// The file's own brightness and contrast (`fx`) are replaced, not stacked on.
let base = original_media(s)?;
adjust_media(s, &base, clear_lum, move |img| {
let mut img = img;
if b != 0.0 {
img = image::DynamicImage::ImageRgba8(image::imageops::colorops::brighten(&img, (b * 2.55) as i32));
}
if c != 0.0 {
img = image::DynamicImage::ImageRgba8(image::imageops::colorops::contrast(&img, c));
}
if sharpen > 0.0 {
img = img.unsharpen(1.0 + sharpen / 50.0, 2);
} else if sharpen < 0.0 && (-sharpen / 25.0).is_normal() {
// `blur` asserts on a subnormal width.
img = img.blur(-sharpen / 25.0);
}
Ok(img)
each_picture(s, |s| {
let b = p::f32(v, "brightness").unwrap_or(0.0).clamp(-100.0, 100.0);
let c = p::f32(v, "contrast").unwrap_or(0.0).clamp(-100.0, 100.0);
let sharpen = p::f32(v, "sharpen").unwrap_or(0.0).clamp(-100.0, 100.0);
// Absolute from the original (like transparency): re-setting all three to 0
// restores the original pixels instead of stacking on the last pass.
// The file's own brightness and contrast (`fx`) are replaced, not stacked on.
let base = original_media(s)?;
adjust_media(s, &base, clear_lum, move |img| {
let mut img = img;
if b != 0.0 {
img = image::DynamicImage::ImageRgba8(image::imageops::colorops::brighten(&img, (b * 2.55) as i32));
}
if c != 0.0 {
img = image::DynamicImage::ImageRgba8(image::imageops::colorops::contrast(&img, c));
}
if sharpen > 0.0 {
img = img.unsharpen(1.0 + sharpen / 50.0, 2);
} else if sharpen < 0.0 && (-sharpen / 25.0).is_normal() {
// `blur` asserts on a subnormal width.
img = img.blur(-sharpen / 25.0);
}
Ok(img)
})
})
})
.params(r#"{"brightness"?: -100..100, "contrast"?: -100..100, "sharpen"?: -100..100}"#)
.when(has_picture),
.when(has_any_picture),
CommandSpec::new("picture.color", "Color", "Picture Format › Adjust", |s, v| {
let mode = p::str(v, "mode").unwrap_or("grayscale").to_string();
let sat = p::f32(v, "saturation").unwrap_or(100.0);
// Absolute from the original (like transparency): saturation 100 restores it.
// Color and Corrections are independent, as in Word: only Washout, which Word stores
// as brightness and contrast (`a:lum`), replaces the file's own (`fx`).
let base = original_media(s)?;
let fx: fn(&mut PicFx) = if mode == "washout" { clear_lum } else { |_| {} };
adjust_media(s, &base, fx, move |img| Ok(recolor(img, &mode, sat)))
each_picture(s, |s| {
let mode = p::str(v, "mode").unwrap_or("grayscale").to_string();
let sat = p::f32(v, "saturation").unwrap_or(100.0);
// Absolute from the original (like transparency): saturation 100 restores it.
// Color and Corrections are independent, as in Word: only Washout, which Word stores
// as brightness and contrast (`a:lum`), replaces the file's own (`fx`).
let base = original_media(s)?;
let fx: fn(&mut PicFx) = if mode == "washout" { clear_lum } else { |_| {} };
adjust_media(s, &base, fx, move |img| Ok(recolor(img, &mode, sat)))
})
})
.params(r#"{"mode": "grayscale|sepia|washout|blackAndWhite|saturation|tint", "saturation"?: 0..400}"#)
.when(has_picture),
.when(has_any_picture),
CommandSpec::new("picture.iconColor", "Icon Color", "Picture Format › Adjust", |s, v| {
let c = p::str(v, "color").and_then(Rgb::parse).ok_or_else(|| CmdError::Params("`color` (RRGGBB) is required".into()))?;
// One colour everywhere, transparency kept: recolours an inserted icon or other
// one-colour line art without redrawing it.
adjust(s, move |img| {
let mut rgba = img.to_rgba8();
for px in rgba.pixels_mut() {
px.0 = [c.0, c.1, c.2, px.0[3]];
}
Ok(image::DynamicImage::ImageRgba8(rgba))
each_picture(s, |s| {
let c = p::str(v, "color").and_then(Rgb::parse).ok_or_else(|| CmdError::Params("`color` (RRGGBB) is required".into()))?;
// One colour everywhere, transparency kept: recolours an inserted icon or other
// one-colour line art without redrawing it.
adjust(s, move |img| {
let mut rgba = img.to_rgba8();
for px in rgba.pixels_mut() {
px.0 = [c.0, c.1, c.2, px.0[3]];
}
Ok(image::DynamicImage::ImageRgba8(rgba))
})
})
})
.params(r#"{"color": "RRGGBB"}"#)
.when(has_picture),
.when(has_any_picture),
CommandSpec::new("picture.effects", "Artistic Effects", "Picture Format › Adjust", |s, v| {
// One effect at a time, as in Word: a second one replaces the first (#2052).
let e = p::str(v, "effect").unwrap_or("blur").to_string();
relook(s, move |l| l.effect = (e != "none").then_some(e))
each_picture(s, |s| {
// One effect at a time, as in Word: a second one replaces the first (#2052).
let e = p::str(v, "effect").unwrap_or("blur").to_string();
relook(s, move |l| l.effect = (e != "none").then_some(e))
})
})
.params(r#"{"effect": "blur|sharpen|invert|posterize|pixelate|none"} (replaces the picture's effect)"#)
.when(has_picture),
.when(has_any_picture),
CommandSpec::new("picture.transparency", "Transparency", "Picture Format › Adjust", |s, v| {
let t = p::f32(v, "percent").unwrap_or(50.0).clamp(0.0, 100.0);
// Absolute, not compounding: 0% is always the original pixels fully opaque.
// The base is the pre-edit original (kept for Reset Picture), so dragging a
// slider back and forth never fades what a previous pass already faded.
// (Combining with other pixel edits then re-setting transparency drops those
// edits; a full live-effect stack is future work.)
// The file's own transparency (`fx`, `a:alphaModFix`) is replaced too: it's baked
// into the pixels from here on.
let base = original_media(s)?;
adjust_media(s, &base, |fx: &mut PicFx| fx.transparency = 0, move |img| {
let mut rgba = img.to_rgba8();
for px in rgba.pixels_mut() {
px.0[3] = (px.0[3] as f32 * (1.0 - t / 100.0)) as u8;
}
Ok(image::DynamicImage::ImageRgba8(rgba))
each_picture(s, |s| {
let t = p::f32(v, "percent").unwrap_or(50.0).clamp(0.0, 100.0);
// Absolute, not compounding: 0% is always the original pixels fully opaque.
// The base is the pre-edit original (kept for Reset Picture), so dragging a
// slider back and forth never fades what a previous pass already faded.
// (Combining with other pixel edits then re-setting transparency drops those
// edits; a full live-effect stack is future work.)
// The file's own transparency (`fx`, `a:alphaModFix`) is replaced too: it's baked
// into the pixels from here on.
let base = original_media(s)?;
adjust_media(s, &base, |fx: &mut PicFx| fx.transparency = 0, move |img| {
let mut rgba = img.to_rgba8();
for px in rgba.pixels_mut() {
px.0[3] = (px.0[3] as f32 * (1.0 - t / 100.0)) as u8;
}
Ok(image::DynamicImage::ImageRgba8(rgba))
})
})
})
.params(r#"{"percent": 0..100}"#)
.when(has_picture),
.when(has_any_picture),
CommandSpec::new("picture.removeBackground", "Remove Background", "Picture Format › Adjust", |s, v| {
let tol = p::f32(v, "tolerance").unwrap_or(30.0).clamp(0.0, 255.0);
adjust(s, move |img| Ok(remove_background(img, tol)))
each_picture(s, |s| {
let tol = p::f32(v, "tolerance").unwrap_or(30.0).clamp(0.0, 255.0);
adjust(s, move |img| Ok(remove_background(img, tol)))
})
})
.params(r#"{"tolerance"?: 0..255}"#)
.when(has_picture),
.when(has_any_picture),
CommandSpec::new("picture.compress", "Compress Pictures", "Picture Format › Adjust", |s, v| {
let max = p::u64(v, "maxPixels").unwrap_or(1600).clamp(32, 20000) as u32;
adjust(s, move |img| Ok(if img.width().max(img.height()) > max { img.resize(max, max, image::imageops::FilterType::Lanczos3) } else { img }))
each_picture(s, |s| {
let max = p::u64(v, "maxPixels").unwrap_or(1600).clamp(32, 20000) as u32;
adjust(s, move |img| Ok(if img.width().max(img.height()) > max { img.resize(max, max, image::imageops::FilterType::Lanczos3) } else { img }))
})
})
.params(r#"{"maxPixels"?: n}"#)
.when(has_picture),
CommandSpec::new("picture.reset", "Reset Picture", "Picture Format › Adjust", reset).when(has_picture),
.when(has_any_picture),
CommandSpec::new("picture.reset", "Reset Picture", "Picture Format › Adjust", |s, v| each_picture(s, |s| reset(s, v))).when(has_any_picture),
CommandSpec::new("picture.change", "Change Picture", "Picture Format › Adjust", |s, v| {
let bytes = if let Some(d) = p::str(v, "data") {
crate::cmd::insert::base64_decode(d).ok_or_else(|| CmdError::Params("bad base64".into()))?
@@ -184,23 +200,27 @@ pub fn specs() -> Vec<CommandSpec> {
.params(r#"{"path"?: string, "data"?: base64}"#)
.when(has_picture),
CommandSpec::new("picture.style", "Picture Styles", "Picture Format › Picture Styles", |s, v| {
// A style replaces the picture's style and border, as Word's gallery does (#2052).
let style = p::str(v, "style").unwrap_or("simpleFrame").to_string();
relook(s, move |l| {
l.style = Some(style);
l.border = None;
each_picture(s, |s| {
// A style replaces the picture's style and border, as Word's gallery does (#2052).
let style = p::str(v, "style").unwrap_or("simpleFrame").to_string();
relook(s, move |l| {
l.style = Some(style);
l.border = None;
})
})
})
.params(r#"{"style": "simpleFrame|thickFrame|rounded|softEdge|shadow"} (replaces the picture's style and border)"#)
.when(has_picture),
.when(has_any_picture),
CommandSpec::new("picture.border", "Picture Border", "Picture Format › Picture Styles", |s, v| {
let c = p::str(v, "color").and_then(Rgb::parse).unwrap_or(Rgb::BLACK);
let w = p::u64(v, "width").unwrap_or(4).clamp(1, 200) as u32;
// Replaces the picture's border, keeping its style (#2052).
relook(s, move |l| l.border = Some((c, w)))
each_picture(s, |s| {
let c = p::str(v, "color").and_then(Rgb::parse).unwrap_or(Rgb::BLACK);
let w = p::u64(v, "width").unwrap_or(4).clamp(1, 200) as u32;
// Replaces the picture's border, keeping its style (#2052).
relook(s, move |l| l.border = Some((c, w)))
})
})
.params(r#"{"color"?: "RRGGBB", "width"?: px} (replaces the picture's border)"#)
.when(has_picture),
.when(has_any_picture),
CommandSpec::new("arrange.rotate", "Rotate", "Layout › Arrange", |s, v| {
// Turns and flips are the object's angle and mirroring (DrawingML `a:xfrm`): the
// picture's pixels are never rewritten. A flip mirrors what is on the page, so a
+465
View File
@@ -432,6 +432,127 @@ fn two_inserted_pictures_in_a_row_are_both_kept() {
assert_eq!(s.run("arrange.selectionPane", &json!({})).unwrap().as_array().map(Vec::len), Some(2));
}
#[test]
fn picture_border_uses_picked_pictures_even_when_a_shape_is_primary() {
for (picked, expected) in
[(&[2, 0][..], [true, false]), (&[2, 0, 1][..], [true, true]), (&[0, 2, 1][..], [true, true]), (&[2][..], [false, false])]
{
let mut s = Session::new(wordcraft_doc::Document::new());
for w in [20, 24] {
let data = super::super::insert::base64_encode(&png(w, 10));
s.run("insert.picture", &json!({"data": data})).unwrap();
}
s.run("caret.docEnd", &json!({})).unwrap();
s.run("insert.shape", &json!({"kind": "rectangle"})).unwrap();
s.run("caret.docStart", &json!({})).unwrap();
for index in picked {
s.run("select.addObject", &json!({"index": index})).unwrap();
}
let selection = s.sel.clone();
let extras = s.also_selected.clone();
let undo = s.undo_depth();
let shape = |s: &Session| {
let (_, object) = all_objects(s).into_iter().find(|(_, o)| matches!(o, InlineObject::Shape { .. })).unwrap();
serde_json::to_value(object).unwrap()
};
let shape_before = shape(&s);
let borders = |s: &Session| {
all_objects(s)
.into_iter()
.filter_map(|(_, o)| match o {
InlineObject::Image { media, .. } => Some(s.picture_looks.get(&media).is_some_and(|l| l.border.is_some())),
_ => None,
})
.collect::<Vec<_>>()
};
let result = s.run("picture.border", &json!({"width": 3}));
if expected == [false, false] {
assert!(result.is_err(), "a shape alone cannot take a picture border");
assert_eq!(s.undo_depth(), undo);
} else {
result.unwrap();
assert_eq!(s.undo_depth(), undo + 1);
}
assert_eq!(s.sel, selection);
assert_eq!(s.also_selected, extras);
assert_eq!(shape(&s), shape_before);
assert_eq!(borders(&s), expected);
if expected != [false, false] {
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(borders(&s), [false, false]);
assert_eq!(shape(&s), shape_before);
}
}
}
#[test]
fn picture_border_uses_pictures_in_a_text_range_in_either_order() {
let data = super::super::insert::base64_encode(&png(20, 10));
for (order, picture_first) in
[(&["insert.shape", "insert.picture"][..], false), (&["insert.picture", "insert.shape"][..], true), (&["insert.shape"][..], false)]
{
let mut s = Session::new(wordcraft_doc::Document::from_text("Lead "));
for command in order {
s.run("caret.docEnd", &json!({})).unwrap();
let params = if *command == "insert.shape" { json!({"kind": "rectangle"}) } else { json!({"data": data}) };
s.run(command, &params).unwrap();
}
s.run("caret.docEnd", &json!({})).unwrap();
s.run("text.insert", &json!({"text": " tail"})).unwrap();
let focus = s.doc.end_of(StoryRef::Body);
s.run("select.range", &json!({"anchor": Pos::body(0, 0), "focus": focus})).unwrap();
let selection = s.sel.clone();
assert!(s.also_selected.is_empty());
assert!(object_selection(&s).is_none(), "this selects ordinary text as well as the object anchors");
let shape = |s: &Session| all_objects(s).into_iter().find(|(_, o)| matches!(o, InlineObject::Shape { .. })).map(|(_, o)| o).unwrap();
let media =
|s: &Session| all_objects(s).into_iter().find_map(|(_, o)| if let InlineObject::Image { media, .. } = o { Some(media) } else { None });
let before = (shape(&s), media(&s), s.undo_depth());
if !picture_first {
assert!(matches!(s.run("picture.crop", &json!({"left": 0.1})), Err(CmdError::Disabled(_))));
}
let result = s.run("picture.border", &json!({"width": 3}));
assert_eq!(s.sel, selection);
assert!(s.also_selected.is_empty());
assert_eq!(shape(&s), before.0);
if let Some(original) = &before.1 {
result.unwrap();
let image = media(&s).unwrap();
assert!(s.picture_looks.get(&image).is_some_and(|l| l.border.is_some()));
assert_eq!(s.undo_depth(), before.2 + 1);
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(media(&s).as_ref(), Some(original));
assert_eq!(shape(&s), before.0);
assert_eq!(s.sel, selection);
} else {
assert!(matches!(result, Err(CmdError::Disabled(_))));
assert_eq!(s.undo_depth(), before.2);
}
}
}
/// #8832: a picture command on several selected pictures changes each, in one undo step.
#[test]
fn picture_border_applies_to_every_selected_picture() {
let data = super::super::insert::base64_encode(&png(20, 10));
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("insert.picture", &json!({"data": data})).unwrap();
s.run("insert.picture", &json!({"data": data})).unwrap();
s.run("select.addObject", &json!({"index": 0})).unwrap();
s.run("select.addObject", &json!({"index": 1})).unwrap();
let media = |s: &Session| {
all_objects(s)
.into_iter()
.map(|(_, o)| matches!(o, InlineObject::Image { media, .. } if s.picture_looks.get(&media).is_some_and(|l| l.border.is_some())))
.collect::<Vec<_>>()
};
assert_eq!(media(&s), [false, false]);
s.run("picture.border", &json!({"width": 3})).unwrap();
assert_eq!(media(&s), [true, true]);
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(media(&s), [false, false]);
}
/// #2019: Insert › Shapes adds each new shape beside the selected one, as Word draws it, so
/// shapes inserted in a row are all kept (the second used to replace the first, which stays
/// selected after its insert). Selected text stays too, and the new shape is selected.
@@ -2245,3 +2366,347 @@ fn shape_size_and_rotation_only_affect_shapes_in_mixed_selection() {
assert_eq!(objs2[1].1.frame().unwrap().0, 180.0);
assert_eq!(objs2[2].1.frame().unwrap().0, 180.0);
}
#[test]
fn picture_format_commands_stay_enabled_when_shape_is_selected_first() {
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("insert.shape", &json!({"kind": "rectangle", "width": 100.0, "height": 60.0})).unwrap();
let data = super::super::insert::base64_encode(&png(12, 12));
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
s.run("insert.picture", &json!({"data": data})).unwrap();
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
s.run("insert.picture", &json!({"data": data})).unwrap();
// Shape clicked first, then one picture added.
s.run("select.objects", &json!({"index": 0})).unwrap();
s.run("select.addObject", &json!({"index": 1})).unwrap();
s.run("picture.border", &json!({"color": "FF0000", "width": 3})).unwrap();
assert!(matches!(
&all_objects(&s)[1].1,
InlineObject::Image { media, .. } if s.picture_looks.get(media).is_some_and(|l| l.border.is_some())
));
// Shape clicked first, then two pictures added.
s.run("select.addObject", &json!({"index": 2})).unwrap();
s.run("picture.style", &json!({"style": "rounded"})).unwrap();
let objs = all_objects(&s);
for idx in [1, 2] {
assert!(
matches!(&objs[idx].1, InlineObject::Image { media, .. } if s.picture_looks.get(media).is_some_and(|l| l.style.as_deref() == Some("rounded"))),
"picture {idx} should get rounded style"
);
}
}
#[test]
fn single_object_picture_commands_need_the_picture_selected_first() {
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("insert.shape", &json!({"kind": "rectangle", "width": 100.0, "height": 60.0})).unwrap();
let data = super::super::insert::base64_encode(&png(12, 12));
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
s.run("insert.picture", &json!({"data": data})).unwrap();
// Shape clicked first, then the picture added: Crop, Change Picture and Alt Text would act on the shape.
s.run("select.objects", &json!({"index": 0})).unwrap();
s.run("select.addObject", &json!({"index": 1})).unwrap();
for (cmd, args) in [("picture.crop", json!({"left": 0.1})), ("picture.altText", json!({"text": "x"})), ("picture.change", json!({"data": data}))]
{
assert!(matches!(s.run(cmd, &args), Err(CmdError::Disabled(_))), "{cmd}");
}
// Picture first: enabled.
s.run("select.objects", &json!({"index": 1})).unwrap();
s.run("picture.crop", &json!({"left": 0.1})).unwrap();
}
/// #6770: an object's size as a share of the page or a margin stays its own: a size set by
/// dragging replaces it (even the object's own size, which the share hid), a group made with it
/// first doesn't take it, and ungrouping a group sized so leaves each member the size it showed.
#[test]
fn a_share_of_the_page_stays_with_its_object() {
use wordcraft_doc::para::{RelSize, SizeFrom};
let quarter = Some(RelSize { from: SizeFrom::Page, pct: 25_000 });
let share_of = |s: &Session| selected(s).and_then(|(_, o)| o.frame().map(|(_, _, f)| (f.rel_w, f.rel_h)));
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("document.setText", &json!({"text": "one\ntwo"})).unwrap();
let page_w = s.doc.last_section.page_w;
s.sel = Selection::caret(s.doc.start_of(StoryRef::Body));
s.run("insert.shape", &json!({"kind": "rectangle", "width": 100, "height": 50})).unwrap();
s.run("arrange.bounds", &json!({"page": 0, "x": 100, "y": 150})).unwrap();
super::select::with_obj(&mut s, |o| {
if let Some(f) = o.float_mut() {
f.rel_w = quarter;
}
})
.unwrap();
s.touch();
let (pos, _) = selected(&s).unwrap();
assert!((rect_of(&mut s, &pos)[2] - page_w / 4.0).abs() < 0.5);
// Dragged to 100 pt wide, its own width: that is the width it shows now.
s.run("arrange.bounds", &json!({"width": 100, "height": 50})).unwrap();
assert_eq!(share_of(&s), Some((None, None)));
let (pos, _) = selected(&s).unwrap();
assert!((rect_of(&mut s, &pos)[2] - 100.0).abs() < 0.5);
// Grouped first with another: the group's box is the one around them, not a share.
super::select::with_obj(&mut s, |o| {
if let Some(f) = o.float_mut() {
f.rel_w = quarter;
}
})
.unwrap();
s.touch();
s.run("select.collapse", &json!({"end": true})).unwrap();
s.run("insert.shape", &json!({"kind": "ellipse", "width": 60, "height": 40})).unwrap();
s.run("arrange.bounds", &json!({"page": 0, "x": 300, "y": 200})).unwrap();
s.run("select.addObject", &json!({"index": 0})).unwrap();
let g = s.run("arrange.group", &json!({})).unwrap();
let gpos: Pos = serde_json::from_value(g["pos"].clone()).unwrap();
assert_eq!(share_of(&s), Some((None, None)));
assert!(near(rect_of(&mut s, &gpos), [100.0, 150.0, 260.0, 90.0]), "{:?}", rect_of(&mut s, &gpos));
// A group sized as half the page: ungrouped, its members keep the places and sizes it showed
// them at, none of them half the page.
super::select::with_obj(&mut s, |o| {
if let Some(f) = o.float_mut() {
f.rel_w = Some(RelSize { from: SizeFrom::Page, pct: 50_000 });
}
})
.unwrap();
s.touch();
let shown = rect_of(&mut s, &gpos);
assert!((shown[2] - page_w / 2.0).abs() < 0.5, "{shown:?}");
s.run("arrange.ungroup", &json!({})).unwrap();
let list = all_objects(&s);
assert_eq!(list.len(), 2);
for (_, o) in &list {
assert_eq!(o.frame().map(|(_, _, f)| (f.rel_w, f.rel_h)), Some((None, None)));
}
let rects: Vec<[f32; 4]> = list.iter().map(|(p, _)| rect_of(&mut s, p)).collect();
let (x0, x1) = rects.iter().fold((f32::MAX, f32::MIN), |(a, b), r| (a.min(r[0]), b.max(r[0] + r[2])));
assert!((x0 - shown[0]).abs() < 0.5 && (x1 - (shown[0] + shown[2])).abs() < 0.5, "{rects:?} in {shown:?}");
}
/// #6770 review: a group in line with text is drawn at its own size whatever share it holds, so
/// ungrouping it leaves its members the sizes it showed them at, not the share's.
#[test]
fn an_inline_group_with_a_share_ungroups_at_its_own_size() {
use wordcraft_doc::para::{RelSize, SizeFrom, Wrap};
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("document.setText", &json!({"text": "one\ntwo"})).unwrap();
s.sel = Selection::caret(s.doc.start_of(StoryRef::Body));
s.run("insert.shape", &json!({"kind": "rectangle", "width": 100, "height": 50})).unwrap();
s.run("arrange.bounds", &json!({"page": 0, "x": 100, "y": 150})).unwrap();
s.run("select.collapse", &json!({"end": true})).unwrap();
s.run("insert.shape", &json!({"kind": "ellipse", "width": 60, "height": 40})).unwrap();
s.run("arrange.bounds", &json!({"page": 0, "x": 300, "y": 200})).unwrap();
s.run("select.addObject", &json!({"index": 0})).unwrap();
s.run("arrange.group", &json!({})).unwrap();
super::select::with_obj(&mut s, |o| {
if let Some(f) = o.float_mut() {
f.wrap = Wrap::Inline;
f.rel_w = Some(RelSize { from: SizeFrom::Page, pct: 50_000 });
}
})
.unwrap();
s.touch();
s.run("arrange.ungroup", &json!({})).unwrap();
let sizes: Vec<(f32, f32)> = all_objects(&s).iter().filter_map(|(_, o)| o.frame().map(|(w, h, _)| (w, h))).collect();
let has = |w: f32, h: f32| sizes.iter().any(|&(x, y)| (x - w).abs() < 0.5 && (y - h).abs() < 0.5);
assert!(sizes.len() == 2 && has(100.0, 50.0) && has(60.0, 40.0), "{sizes:?}");
}
/// #9830 review: ungrouping a group its share of the page draws past 4000 pt leaves a member that
/// tall its size, as its share of what the group's share is of; the 4000 pt an object's own size
/// stops at would shrink it. A share past the longest a share draws (4000 % here, as JSON import
/// accepts) leaves the group drawn at that longest, and its members at their part of it.
#[test]
fn an_ungrouped_member_past_4000_pt_keeps_its_size() {
use wordcraft_doc::para::{RelSize, SizeFrom};
for pct in [1_000_000, 4_000_000] {
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("document.setText", &json!({"text": "one\ntwo"})).unwrap();
let page_h = s.doc.last_section.page_h;
s.sel = Selection::caret(s.doc.start_of(StoryRef::Body));
s.run("insert.shape", &json!({"kind": "rectangle", "width": 100, "height": 50})).unwrap();
s.run("arrange.bounds", &json!({"page": 0, "x": 100, "y": 150})).unwrap();
s.run("select.collapse", &json!({"end": true})).unwrap();
s.run("insert.shape", &json!({"kind": "ellipse", "width": 60, "height": 40})).unwrap();
s.run("arrange.bounds", &json!({"page": 0, "x": 300, "y": 200})).unwrap();
s.run("select.addObject", &json!({"index": 0})).unwrap();
s.run("arrange.group", &json!({})).unwrap();
super::select::with_obj(&mut s, |o| {
if let Some(f) = o.float_mut() {
f.rel_h = Some(RelSize { from: SizeFrom::Page, pct });
}
})
.unwrap();
s.touch();
let (gpos, _) = selected(&s).unwrap();
let group_h = rect_of(&mut s, &gpos)[3];
let drawn = (page_h * pct as f32 / 100_000.0).min(wordcraft_doc::para::MAX_SHARE_LEN);
assert!((group_h - drawn).abs() < 0.5, "{pct}: {group_h}");
s.run("arrange.ungroup", &json!({})).unwrap();
let mut heights: Vec<f32> = all_objects(&s).iter().map(|(p, _)| rect_of(&mut s, p)[3]).collect();
heights.sort_by(f32::total_cmp);
// The group was 90 pt tall: the rectangle 50 of them, the ellipse 40.
let want = [group_h * 40.0 / 90.0, group_h * 50.0 / 90.0];
assert!(heights.len() == 2 && heights.iter().zip(want).all(|(h, w)| (h - w).abs() < 1.0), "{pct}: {heights:?}, not {want:?}");
}
}
/// #9802: `picture.size` / `shape.size` work from the drawn size when a share applies, and clear
/// the share of any side they set even when the new value equals the object's hidden own size.
#[test]
fn size_command_uses_drawn_size_and_clears_share_even_at_own_size() {
use wordcraft_doc::para::{RelSize, SizeFrom};
let half_page = Some(RelSize { from: SizeFrom::Page, pct: 50_000 });
let share_of = |s: &Session| selected(s).and_then(|(_, o)| o.frame().map(|(_, _, f)| (f.rel_w, f.rel_h)));
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("document.setText", &json!({"text": "one"})).unwrap();
let (page_w, page_h) = (s.doc.last_section.page_w, s.doc.last_section.page_h);
s.sel = Selection::caret(s.doc.start_of(StoryRef::Body));
s.run("insert.shape", &json!({"kind": "rectangle", "width": 100, "height": 50})).unwrap();
s.run("arrange.bounds", &json!({"page": 0, "x": 100, "y": 150})).unwrap();
super::select::with_obj(&mut s, |o| {
if let Some(f) = o.float_mut() {
f.rel_w = half_page;
f.rel_h = half_page;
}
})
.unwrap();
s.touch();
let (pos, _) = selected(&s).unwrap();
assert!((rect_of(&mut s, &pos)[2] - page_w / 2.0).abs() < 0.5);
assert!((rect_of(&mut s, &pos)[3] - page_h / 2.0).abs() < 0.5);
// Scaling by 50% scales from the drawn half-page size, not the hidden 100x50 own size.
s.run("shape.size", &json!({"scale": 50})).unwrap();
assert_eq!(share_of(&s), Some((None, None)));
let (pos, _) = selected(&s).unwrap();
let scaled = rect_of(&mut s, &pos);
assert!((scaled[2] - page_w / 4.0).abs() < 0.5, "{scaled:?}");
assert!((scaled[3] - page_h / 4.0).abs() < 0.5, "{scaled:?}");
// Setting width to the hidden own width (100) with lockAspect=false clears rel_w while keeping rel_h.
s.run("shape.size", &json!({"width": 100, "height": 50, "lockAspect": false})).unwrap();
super::select::with_obj(&mut s, |o| {
if let Some(f) = o.float_mut() {
f.rel_w = half_page;
f.rel_h = half_page;
}
})
.unwrap();
s.touch();
s.run("shape.size", &json!({"width": 100, "lockAspect": false})).unwrap();
assert_eq!(share_of(&s), Some((None, half_page)));
let (pos, _) = selected(&s).unwrap();
let resized = rect_of(&mut s, &pos);
assert!((resized[2] - 100.0).abs() < 0.5, "{resized:?}");
assert!((resized[3] - page_h / 2.0).abs() < 0.5, "{resized:?}");
}
/// #9830 review: in Web view a share is of the page as wide as the window, so ungrouping a
/// share-sized group there works its members' shares out from that page: they keep their sizes.
#[test]
fn an_ungrouped_member_in_web_view_keeps_its_size() {
use wordcraft_doc::para::{RelSize, SizeFrom};
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("document.setText", &json!({"text": "one\ntwo"})).unwrap();
s.sel = Selection::caret(s.doc.start_of(StoryRef::Body));
s.run("insert.shape", &json!({"kind": "rectangle", "width": 100, "height": 50})).unwrap();
s.run("arrange.bounds", &json!({"page": 0, "x": 100, "y": 150})).unwrap();
s.run("select.collapse", &json!({"end": true})).unwrap();
s.run("insert.shape", &json!({"kind": "ellipse", "width": 60, "height": 40})).unwrap();
s.run("arrange.bounds", &json!({"page": 0, "x": 300, "y": 200})).unwrap();
s.run("select.addObject", &json!({"index": 0})).unwrap();
s.run("arrange.group", &json!({})).unwrap();
s.view.mode = wordcraft_layout::ViewMode::Web;
s.view.web_width = 1000.0;
super::select::with_obj(&mut s, |o| {
if let Some(f) = o.float_mut() {
f.rel_w = Some(RelSize { from: SizeFrom::Page, pct: 2_000_000 });
}
})
.unwrap();
s.touch();
let (gpos, _) = selected(&s).unwrap();
let group_w = rect_of(&mut s, &gpos)[2];
assert!((group_w - wordcraft_doc::para::MAX_SHARE_LEN).abs() < 0.5, "{group_w}");
s.run("arrange.ungroup", &json!({})).unwrap();
let mut widths: Vec<f32> = all_objects(&s).iter().map(|(p, _)| rect_of(&mut s, p)[2]).collect();
widths.sort_by(f32::total_cmp);
// The group was 260 pt wide: the rectangle 100 of them, the ellipse 60.
let want = [group_w * 60.0 / 260.0, group_w * 100.0 / 260.0];
assert!(widths.len() == 2 && widths.iter().zip(want).all(|(w, x)| (w - x).abs() < 1.0), "{widths:?}, not {want:?}");
}
/// A session whose body is "one" then "two", the second paragraph in its own section (a
/// continuous one with a wider left margin when `continuous`), with a rectangle and an ellipse
/// in it grouped and selected on the page that section starts on: 260 pt wide, 90 pt tall.
fn grouped_in_second_section(continuous: bool) -> Session {
use wordcraft_doc::section::{SectionProps, SectionStart};
let mut d = wordcraft_doc::Document::from_text("one\ntwo");
let first = SectionProps { margin_left: 72.0, margin_right: 72.0, ..d.last_section.clone() };
d.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap().section = Some(Box::new(first));
if continuous {
d.last_section.start = SectionStart::Continuous;
(d.last_section.margin_left, d.last_section.margin_right) = (172.0, 72.0);
}
let mut s = Session::new(d);
s.sel = Selection::caret(Pos::body(1, 0));
// On the page the section starts on: its own when it starts a new one.
let page = if continuous { 0 } else { 1 };
s.run("insert.shape", &json!({"kind": "rectangle", "width": 100, "height": 50})).unwrap();
s.run("arrange.bounds", &json!({"page": page, "x": 100, "y": 300})).unwrap();
s.run("select.collapse", &json!({"end": true})).unwrap();
s.run("insert.shape", &json!({"kind": "ellipse", "width": 60, "height": 40})).unwrap();
s.run("arrange.bounds", &json!({"page": page, "x": 300, "y": 350})).unwrap();
s.run("select.addObject", &json!({"index": 0})).unwrap();
s.run("arrange.group", &json!({})).unwrap();
s
}
/// Ungroups the selected group after giving it a width share `share`, and checks that it was
/// drawn `group_w` wide and that its members keep the widths they were drawn at.
fn ungroups_keeping_widths(s: &mut Session, share: wordcraft_doc::para::RelSize, group_w: f32) {
super::select::with_obj(s, |o| {
if let Some(f) = o.float_mut() {
f.rel_w = Some(share);
}
})
.unwrap();
s.touch();
let (gpos, _) = selected(s).unwrap();
assert_eq!(gpos.path.0.first(), Some(&1), "the group is anchored in the second section");
let drawn = rect_of(s, &gpos)[2];
assert!((drawn - group_w).abs() < 0.5, "{drawn}, not {group_w}");
s.run("arrange.ungroup", &json!({})).unwrap();
let mut widths: Vec<f32> = all_objects(s).iter().map(|(p, _)| rect_of(s, p)[2]).collect();
widths.sort_by(f32::total_cmp);
// The group was 260 pt wide: the rectangle 100 of them, the ellipse 60.
let want = [drawn * 60.0 / 260.0, drawn * 100.0 / 260.0];
assert!(widths.len() == 2 && widths.iter().zip(want).all(|(w, x)| (w - x).abs() < 1.0), "{widths:?}, not {want:?}");
}
/// #9830 review: a group in a continuous section that starts partway down a page is sized from
/// that section's margins, not the page's first section's, and so are its members' shares.
#[test]
fn an_ungrouped_member_in_a_continuous_section_keeps_its_size() {
use wordcraft_doc::para::{RelSize, SizeFrom};
let mut s = grouped_in_second_section(true);
let text_w = s.doc.last_section.text_width();
ungroups_keeping_widths(&mut s, RelSize { from: SizeFrom::Margin, pct: 3_000_000 }, (text_w * 30.0).min(wordcraft_doc::para::MAX_SHARE_LEN));
}
/// #9830 review: in Read Mode a section whose text runs down is laid out on its page turned on
/// its side, not on the reflowed page, and its members' shares are worked out from that page.
#[test]
fn an_ungrouped_member_in_a_turned_section_in_read_mode_keeps_its_size() {
use wordcraft_doc::para::{RelSize, SizeFrom};
let mut s = grouped_in_second_section(false);
s.doc.last_section.text_direction = wordcraft_doc::props::TextDirection::Down;
s.touch();
s.view.read_mode = true;
s.view.read_width = 500.0;
let page_h = s.doc.last_section.page_h;
ungroups_keeping_widths(&mut s, RelSize { from: SizeFrom::Page, pct: 2_000_000 }, (page_h * 20.0).min(wordcraft_doc::para::MAX_SHARE_LEN));
}
+126 -17
View File
@@ -287,9 +287,39 @@ fn prepare_custom_dictionary(s: &Session, setting: Option<&str>) -> Result<(Opti
}
}
/// The user's home folder: `USERPROFILE` first on Windows, `HOME` first elsewhere, skipping
/// empty values. The recent list reads it in the same order (#8865), so `~/…` means one folder.
fn home_dir() -> Option<std::path::PathBuf> {
home_from(std::env::var_os("HOME"), std::env::var_os("USERPROFILE"))
}
/// [`home_dir`] without the environment: the order the two values are read in depends on the
/// platform, so it takes them as they are read.
fn home_from(home: Option<std::ffi::OsString>, userprofile: Option<std::ffi::OsString>) -> Option<std::path::PathBuf> {
let set = |v: Option<std::ffi::OsString>| v.filter(|h| !h.is_empty()).map(std::path::PathBuf::from);
let (first, second) = if cfg!(windows) { (userprofile, home) } else { (home, userprofile) };
set(first).or_else(|| set(second))
}
/// Expand a file or folder path under the home folder with the saved settings' platform-specific prefix.
fn expand_home(key: &str, f: &str, home: Option<&std::path::Path>) -> Result<std::path::PathBuf, CmdError> {
let prefix = if cfg!(windows) && f.starts_with("~\\") { "~\\" } else { "~/" };
let Some(rest) = f.strip_prefix(prefix) else { return Ok(std::path::PathBuf::from(f)) };
let Some(home) = home else {
return Err(CmdError::Params(format!("`{key}`: cannot expand `{prefix}` because HOME or USERPROFILE is not set")));
};
// A Windows drive, device or root in the suffix would replace the home path on join.
if prefix == "~\\"
&& matches!(std::path::Path::new(rest).components().next(), Some(std::path::Component::Prefix(_) | std::path::Component::RootDir))
{
return Err(CmdError::Params(format!("`{key}`: {f:?} must be relative to the home folder")));
}
Ok(home.join(rest))
}
/// A folder setting (`dictionariesFolder`, `userTemplatesFolder`): `auto` (or nothing) forgets
/// it; otherwise an existing folder, given as an absolute path or one starting with `~/`. With
/// `local_only`, a network folder is refused before anything looks at it (#2852): even checking
/// it; otherwise an existing folder, given as an absolute path or one starting with `~/` (`~\` also works on Windows).
/// With `local_only`, a network folder is refused before anything looks at it (#2852): even checking
/// that it exists would make Windows authenticate to that host.
fn folder_setting(key: &str, f: &str, local_only: bool) -> Result<Option<String>, CmdError> {
let f = f.trim();
@@ -299,11 +329,7 @@ fn folder_setting(key: &str, f: &str, local_only: bool) -> Result<Option<String>
if f.chars().count() > MAX_FOLDER_CHARS || f.chars().any(char::is_control) {
return Err(CmdError::Params(format!("`{key}` isn't a folder path")));
}
let home = std::env::var_os("HOME").filter(|h| !h.is_empty()).map(std::path::PathBuf::from);
let path = match (f.strip_prefix("~/"), home) {
(Some(rest), Some(h)) => h.join(rest),
_ => std::path::PathBuf::from(f),
};
let path = expand_home(key, f, home_dir().as_deref())?;
if local_only && (super::templates::is_network_path(f) || super::templates::is_network_path(&path.to_string_lossy())) {
return Err(CmdError::Params(format!("`{key}` can't be a network folder")));
}
@@ -319,8 +345,12 @@ fn folder_setting(key: &str, f: &str, local_only: bool) -> Result<Option<String>
}
/// A file setting (`customDictionary`): `auto` (or nothing) forgets it; otherwise an existing
/// file, given as an absolute path or one starting with `~/`.
/// file, given as an absolute path or one starting with `~/` (`~\` also works on Windows).
fn file_setting(key: &str, f: &str) -> Result<Option<String>, CmdError> {
file_setting_in(key, f, home_dir().as_deref())
}
fn file_setting_in(key: &str, f: &str, home: Option<&std::path::Path>) -> Result<Option<String>, CmdError> {
let f = f.trim();
if f.is_empty() || f.eq_ignore_ascii_case("auto") {
return Ok(None);
@@ -328,15 +358,7 @@ fn file_setting(key: &str, f: &str) -> Result<Option<String>, CmdError> {
if f.chars().count() > MAX_FOLDER_CHARS || f.chars().any(char::is_control) {
return Err(CmdError::Params(format!("`{key}` isn't a file path")));
}
let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).filter(|h| !h.is_empty()).map(std::path::PathBuf::from);
let path = if let Some(rest) = f.strip_prefix("~/") {
match home {
Some(h) => h.join(rest),
None => return Err(CmdError::Params(format!("`{key}`: cannot expand `~/` because HOME or USERPROFILE is not set"))),
}
} else {
std::path::PathBuf::from(f)
};
let path = expand_home(key, f, home)?;
if !path.is_absolute() {
return Err(CmdError::Params(format!("`{key}`: {f:?} isn't a full path")));
}
@@ -355,3 +377,90 @@ fn file_setting(key: &str, f: &str) -> Result<Option<String>, CmdError> {
pub fn use_dictionaries_folder(folder: Option<&str>) {
wordcraft_proof::set_dictionaries_folder(folder.map(std::path::PathBuf::from));
}
#[cfg(test)]
mod tests {
use super::{expand_home, file_setting_in, home_from};
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};
fn os(s: &str) -> Option<OsString> {
Some(OsString::from(s))
}
#[test]
fn the_home_folder_is_the_profile_folder_on_windows_and_home_elsewhere() {
let home = home_from(os("/home/u"), os("C:\\Users\\u"));
let expected = if cfg!(windows) { PathBuf::from("C:\\Users\\u") } else { PathBuf::from("/home/u") };
assert_eq!(home, Some(expected));
}
#[test]
fn an_empty_home_folder_is_skipped_for_the_other_one() {
assert_eq!(home_from(os(""), os("C:\\Users\\u")), Some(PathBuf::from("C:\\Users\\u")));
assert_eq!(home_from(os(""), None), None);
}
#[test]
fn no_home_folder_at_all_expands_to_nothing() {
assert_eq!(home_from(None, None), None);
}
#[test]
fn a_tilde_path_expands_under_the_home_folder() {
let home = Path::new("/home/u");
assert_eq!(expand_home("dictionariesFolder", "~/dic", Some(home)).unwrap(), PathBuf::from("/home/u/dic"));
assert_eq!(expand_home("dictionariesFolder", "/abs/dic", Some(home)).unwrap(), PathBuf::from("/abs/dic"));
}
#[test]
fn a_tilde_path_without_a_home_folder_is_refused() {
let err = expand_home("dictionariesFolder", "~/dic", None).unwrap_err();
assert!(format!("{err:?}").contains("cannot expand"), "{err:?}");
}
#[test]
fn custom_dictionary_expands_tilde_with_the_same_platform_prefix() {
static NEXT: AtomicUsize = AtomicUsize::new(0);
struct TempHome(PathBuf);
impl TempHome {
fn remove(self) -> std::io::Result<()> {
let res = std::fs::remove_dir_all(&self.0);
std::mem::forget(self);
res
}
}
impl Drop for TempHome {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
let dir = loop {
let n = NEXT.fetch_add(1, Ordering::Relaxed);
let candidate = std::env::temp_dir().join(format!("wc-options-home-{}-{n}", std::process::id()));
match std::fs::create_dir(&candidate) {
Ok(()) => break TempHome(candidate),
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
Err(e) => panic!("temp dir {}: {e}", candidate.display()),
}
};
let dic = dir.0.join("custom.dic");
std::fs::write(&dic, "wordcraftdictionary\n").unwrap();
let expected = dic.to_string_lossy().into_owned();
assert_eq!(file_setting_in("customDictionary", "~/custom.dic", Some(&dir.0)).unwrap().as_deref(), Some(expected.as_str()));
let missing_home = file_setting_in("customDictionary", "~/custom.dic", None).unwrap_err();
assert!(format!("{missing_home:?}").contains("cannot expand"), "{missing_home:?}");
if cfg!(windows) {
assert_eq!(file_setting_in("customDictionary", r"~\custom.dic", Some(&dir.0)).unwrap().as_deref(), Some(expected.as_str()));
let drive = file_setting_in("customDictionary", r"~\C:\custom.dic", Some(&dir.0)).unwrap_err();
assert!(format!("{drive:?}").contains("relative to the home folder"), "{drive:?}");
} else {
let backslash = file_setting_in("customDictionary", r"~\custom.dic", Some(&dir.0)).unwrap_err();
assert!(format!("{backslash:?}").contains("isn't a full path"), "{backslash:?}");
}
dir.remove().unwrap();
}
}
+2 -2
View File
@@ -97,8 +97,8 @@ mod tests {
use super::*;
use crate::packs::{Backend, FixedBackend};
/// Tests that set the process-wide backend take turns.
static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
/// Tests that set the process-wide backend or packs directory share the dictionary test lock.
use crate::custom_dict::DICT_TEST_LOCK as LOCK;
/// Puts the process back to no backend and no background thread when dropped, even when
/// the test panicked.
+72 -13
View File
@@ -51,7 +51,7 @@ pub fn specs() -> Vec<CommandSpec> {
s.push_ui_request(json!({"open": "pageSetup"}));
Ok(serde_json::to_value(sect(s)).unwrap_or(Value::Null))
})
.params(r#"{"section"?: SectionProps} (replaces the whole section, headers and footers included; checked like Size, Margins, Columns, Line Numbers, Footnotes and Page Borders: non-finite numbers and margins that leave no room for text are refused; page sides 7.2–1584 pt, 1–12 columns with 0–300 pt gaps, header/footer/gutter 0–1584 pt, page border width 0.25–6 pt and distance 0–31 pt, note start 1–32767, line numbers start 1–32767, countBy 1–100, distance 0–1584 pt are clamped)"#),
.params(r#"{"section"?: SectionProps} (replaces the whole section, headers and footers included; checked like Size, Margins, Columns, Line Numbers, Footnotes and Page Borders: non-finite numbers and margins that leave no room for text are refused; negative marginTop/marginBottom are kept as exact margins and counted by their magnitude while negative marginLeft/marginRight clamp to 0; page sides 7.2–1584 pt, 1–12 columns with 0–300 pt gaps, header/footer/gutter 0–1584 pt, page border width 0.25–6 pt and distance 0–31 pt, note start 1–32767, line numbers start 1–32767, countBy 1–100, distance 0–1584 pt are clamped)"#),
CommandSpec::new("layout.verticalAlign", "Vertical Alignment", "Layout › Page Setup › Layout", |s, v| {
let va = wordcraft_doc::section::PageVAlign::parse(p::str(v, "value").unwrap_or_default());
with_sect(s, |x| x.valign = va)
@@ -224,8 +224,51 @@ fn manual_hyphenation(s: &mut Session, v: &Value) -> CmdResult {
Ok(best.map(|(_, v)| v).unwrap_or_else(|| json!({"done": true})))
}
/// Whether `sec` displays header/footer part `id` (directly or inherited from an earlier section).
pub(crate) fn section_uses_hf_part(sections: &[(usize, &SectionProps)], sec: usize, id: u32) -> bool {
let slice = sections.get(..=sec).unwrap_or(sections);
[
slice.iter().rev().find_map(|(_, sp)| sp.headers.default),
slice.iter().rev().find_map(|(_, sp)| sp.headers.first),
slice.iter().rev().find_map(|(_, sp)| sp.headers.even),
slice.iter().rev().find_map(|(_, sp)| sp.footers.default),
slice.iter().rev().find_map(|(_, sp)| sp.footers.first),
slice.iter().rev().find_map(|(_, sp)| sp.footers.even),
]
.contains(&Some(id))
}
/// Resolve the section index associated with a header, footer, or note part `id`.
pub(crate) fn section_of_part(s: &Session, id: u32) -> usize {
let sections = s.doc.sections();
if s.doc.parts.get(&id).is_some_and(|p| matches!(p.kind, wordcraft_doc::PartKind::Header | wordcraft_doc::PartKind::Footer)) {
let uses_hf = |sec: usize| section_uses_hf_part(&sections, sec, id);
// The section of the page whose header or footer was opened decides: a footer inherited from
// an earlier section still belongs to the later section that shows it. It is kept apart
// from the page hint because a taller footer can repaginate the pages under it.
if let Some(sec) = s.hf_section.map(|sec| sec.min(sections.len().saturating_sub(1)))
&& uses_hf(sec)
{
return sec;
}
// Entered without a page (Insert › Header, a page number): the page the hint names.
if let Some(pg) = s.cached_layout().and_then(|l| l.pages.get(s.page_hint)) {
let sec = pg.section.min(sections.len().saturating_sub(1));
if uses_hf(sec) {
return sec;
}
}
// Neither names a section that uses it (a stale page hint): the body position the header
// was entered from.
if let Some(ret) = &s.hf_return
&& ret.focus.story == wordcraft_doc::StoryRef::Body
{
let sec = s.doc.section_index_of(ret.focus.path.0.first().copied().unwrap_or(0) as usize);
if uses_hf(sec) {
return sec;
}
}
}
for (i, (_, sp)) in sections.iter().enumerate() {
if [sp.headers.default, sp.headers.first, sp.headers.even, sp.footers.default, sp.footers.first, sp.footers.even].contains(&Some(id)) {
return i;
@@ -289,8 +332,15 @@ fn selected_section_ends(s: &Session) -> Vec<usize> {
(first..=last).map(|k| ends.get(k).copied().unwrap_or(0)).collect()
}
/// Apply to the section(s) of the selection.
/// Apply a mutation to each section touched by the current selection.
///
/// When the caret or selection is outside the body (such as in a header, footer, or note),
/// refreshes the layout so the section resolved from the cached layout reflects the current
/// document state before mutating section properties.
pub(crate) fn with_sect(s: &mut Session, f: impl Fn(&mut SectionProps)) -> CmdResult {
if s.sel.focus.story != wordcraft_doc::StoryRef::Body {
let _ = s.layout();
}
for block in selected_section_ends(s) {
f(s.doc.section_mut(block));
}
@@ -455,8 +505,7 @@ fn validate_section(x: &mut SectionProps) -> Result<(), CmdError> {
if x.page_w != x.page_h {
x.landscape = x.page_w > x.page_h;
}
x.margin_top = x.margin_top.max(0.0);
x.margin_bottom = x.margin_bottom.max(0.0);
// Negative top/bottom margins encode Word's exact (fixed) margins and must survive round-trips.
x.margin_left = x.margin_left.max(0.0);
x.margin_right = x.margin_right.max(0.0);
x.header = x.header.clamp(0.0, x.page_h);
@@ -465,7 +514,8 @@ fn validate_section(x: &mut SectionProps) -> Result<(), CmdError> {
// A page narrower than the usual text room (the smallest is 0.1") needs only margins that
// leave the whole of it: zero margins, gutter included.
let room = |side: f32| MIN_TEXT_ROOM.min(side);
if x.margin_left + x.margin_right + x.gutter > x.page_w - room(x.page_w) || x.margin_top + x.margin_bottom > x.page_h - room(x.page_h) {
if x.margin_left + x.margin_right + x.gutter > x.page_w - room(x.page_w) || x.margin_top.abs() + x.margin_bottom.abs() > x.page_h - room(x.page_h)
{
return Err(CmdError::Params("margins leave no room for text".into()));
}
x.columns.space = x.columns.space.clamp(0.0, 300.0);
@@ -514,26 +564,31 @@ fn border_sides_mut(b: &mut Borders) -> impl Iterator<Item = &mut Border> {
fn margins(s: &mut Session, v: &Value) -> CmdResult {
let preset = p::str(v, "preset");
if s.sel.focus.story != wordcraft_doc::StoryRef::Body {
let _ = s.layout();
}
let (t, b, l, r) = match preset {
Some(x) => match MARGIN_PRESETS.iter().find(|(id, _)| *id == x) {
Some((_, [t, b, l, r])) => (*t, *b, *l, *r),
None => return Err(CmdError::Params(format!("unknown preset `{x}`"))),
},
None => {
// A negative margin given counts as zero; one left out keeps its value, so an exact
// (negative) top or bottom from the file stays exact when another side changes, as
// in Word.
let c = sect(s);
let given = |k: &str| p::f32(v, k).map(|m| m.max(0.0));
(
p::f32(v, "top").unwrap_or(c.margin_top),
p::f32(v, "bottom").unwrap_or(c.margin_bottom),
p::f32(v, "left").unwrap_or(c.margin_left),
p::f32(v, "right").unwrap_or(c.margin_right),
given("top").unwrap_or(c.margin_top),
given("bottom").unwrap_or(c.margin_bottom),
given("left").unwrap_or(c.margin_left.max(0.0)),
given("right").unwrap_or(c.margin_right.max(0.0)),
)
}
};
// Negative margins count as zero before the fit check, so one can't offset another.
let (t, b, l, r) = (t.max(0.0), b.max(0.0), l.max(0.0), r.max(0.0));
let gutter = p::f32(v, "gutter").map(|g| g.max(0.0));
let cur = sect(s);
if !margins_fit((cur.page_w, cur.page_h), (t, b, l, r), gutter.unwrap_or(cur.gutter)) {
if !margins_fit((cur.page_w, cur.page_h), (t.abs(), b.abs(), l, r), gutter.unwrap_or(cur.gutter)) {
return Err(CmdError::Params("margins leave no room for text".into()));
}
// A preset picks mirrored or not, as does `mirror` (Page Setup's Multiple pages); plain numbers
@@ -569,6 +624,7 @@ pub fn margins_fit(page: (f32, f32), (t, b, l, r): (f32, f32, f32, f32), gutter:
pub const MIN_PAGE_SIDE: f32 = 7.2;
pub const MAX_PAGE_SIDE: f32 = 1584.0;
/// Change paper size of the selected section(s) to the given dimensions or preset name.
fn size(s: &mut Session, v: &Value) -> CmdResult {
let (w, h) = if let Some(n) = p::str(v, "name") {
let (_, w, h) = wordcraft_geom::PAPER_SIZES
@@ -583,12 +639,15 @@ fn size(s: &mut Session, v: &Value) -> CmdResult {
let (w, h) = (w.clamp(MIN_PAGE_SIDE, MAX_PAGE_SIDE), h.clamp(MIN_PAGE_SIDE, MAX_PAGE_SIDE));
// Each section keeps its orientation: the long side across in landscape, down in portrait.
let oriented = |x: &SectionProps| if x.landscape { (w.max(h), w.min(h)) } else { (w.min(h), w.max(h)) };
if s.sel.focus.story != wordcraft_doc::StoryRef::Body {
let _ = s.layout();
}
let sections = s.doc.sections();
let fits = |block: usize| {
sections
.iter()
.find(|(e, _)| *e == block)
.is_none_or(|(_, x)| margins_fit(oriented(x), (x.margin_top, x.margin_bottom, x.margin_left, x.margin_right), x.gutter))
.is_none_or(|(_, x)| margins_fit(oriented(x), (x.margin_top.abs(), x.margin_bottom.abs(), x.margin_left, x.margin_right), x.gutter))
};
if !selected_section_ends(s).into_iter().all(fits) {
return Err(CmdError::Params(MARGINS_DONT_FIT.into()));
+478 -3
View File
@@ -1,4 +1,5 @@
use super::*;
use wordcraft_doc::section::NumFormat;
fn doc() -> Session {
Session::new(wordcraft_doc::Document::from_text("one\ntwo\nthree"))
@@ -43,7 +44,7 @@ fn page_setup_section_is_validated() {
v["pageH"] = json!(100.0);
v["marginTop"] = json!(-10.0);
v["marginBottom"] = json!(0.0);
v["marginLeft"] = json!(0.0);
v["marginLeft"] = json!(-10.0);
v["marginRight"] = json!(0.0);
v["header"] = json!(-3.0);
v["footer"] = json!(1e6);
@@ -61,7 +62,8 @@ fn page_setup_section_is_validated() {
.unwrap();
let x = sect(&s);
assert_eq!((x.page_w, x.page_h), (100.0, 100.0));
assert_eq!(x.margin_top, 0.0);
assert_eq!(x.margin_top, -10.0);
assert_eq!(x.margin_left, 0.0);
assert_eq!(x.header, 0.0);
assert_eq!(x.footer, x.page_h, "a footer distance stays on the page");
assert_eq!(x.columns.count, 12);
@@ -142,6 +144,26 @@ fn page_setup_section_allows_a_tiny_page_without_margins() {
assert_eq!((sect(&s).page_w, sect(&s).page_h), (7.2, 20.0));
}
#[test]
fn page_setup_section_keeps_exact_vertical_margins_and_checks_their_sizes() {
let mut s = doc();
s.doc.last_section.margin_top = -54.0;
s.doc.last_section.margin_bottom = -48.0;
let mut roundtrip = s.run("layout.pageSetup", &json!({})).unwrap();
roundtrip["marginLeft"] = json!(60.0);
s.run("layout.pageSetup", &json!({"section": roundtrip})).unwrap();
let x = sect(&s);
assert_eq!((x.margin_top, x.margin_bottom, x.margin_left), (-54.0, -48.0, 60.0));
let too_tall = with_section(|v| {
v["pageH"] = json!(100.0);
v["marginTop"] = json!(-40.0);
v["marginBottom"] = json!(-40.0);
});
assert!(s.run("layout.pageSetup", &too_tall).is_err(), "exact vertical margins whose sizes leave too little room must be refused");
}
/// Layout › Text Direction turns the section, or the table cell the caret is in; one undo step.
#[test]
fn text_direction_turns_the_section_or_the_cell() {
@@ -417,7 +439,6 @@ fn hyphenation_options_and_manual_hyphenation() {
/// section" (#1113).
#[test]
fn page_number_format_keeps_or_clears_the_start() {
use wordcraft_doc::section::NumFormat;
let mut s = doc();
s.run("layout.pageNumberFormat", &json!({"format": "upperRoman", "start": 3})).unwrap();
let x = sect(&s);
@@ -432,4 +453,458 @@ fn page_number_format_keeps_or_clears_the_start() {
let back = s.run("layout.pageNumberFormat", &json!({"format": "decimal", "start": 1})).unwrap();
assert_eq!(back["pageNumFormat"], "decimal");
assert_eq!(back["pageNumStart"], 1);
// #5855: from a linked footer on a later section's page, `sect` and `layout.pageNumberFormat`
// read and update that page's section, not the earlier section that defined the footer.
let mut s = Session::new(wordcraft_doc::Document::from_text("front\nbody"));
s.run("select.text", &json!({"text": "front"})).unwrap();
s.run("caret.end", &json!({})).unwrap();
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
s.run("text.insert", &json!({"text": "Footer on sec 0"})).unwrap();
s.run("insert.closeHeader", &json!({})).unwrap();
s.run("insert.editFooter", &json!({"page": 1})).unwrap();
assert_eq!(section_index_of_focus(&s), 1);
s.run("layout.pageNumberFormat", &json!({"format": "lowerRoman", "start": 5})).unwrap();
let secs = s.doc.sections();
assert_eq!((secs[0].1.page_num_format, secs[0].1.page_num_start), (NumFormat::Decimal, None));
assert_eq!((secs[1].1.page_num_format, secs[1].1.page_num_start), (NumFormat::LowerRoman, Some(5)));
assert_eq!(s.layout().pages[1].number, 5);
}
/// Section commands from an inherited footer target the active section rather than section 0.
#[test]
fn section_command_from_inherited_footer_targets_active_section() {
let mut s = Session::new(wordcraft_doc::Document::from_text("front\nbody"));
s.run("select.text", &json!({"text": "front"})).unwrap();
s.run("caret.end", &json!({})).unwrap();
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
s.run("text.insert", &json!({"text": "Footer on sec 0"})).unwrap();
s.run("insert.closeHeader", &json!({})).unwrap();
s.run("insert.editFooter", &json!({"page": 1})).unwrap();
assert_eq!(section_index_of_focus(&s), 1);
s.run("layout.orientation", &json!({"value": "landscape"})).unwrap();
let secs = s.doc.sections();
assert!(!secs[0].1.landscape);
assert!(secs[1].1.landscape);
// layout.size also targets the active section from an inherited footer.
s.run("layout.size", &json!({"name": "A5"})).unwrap();
let secs = s.doc.sections();
let a5 = wordcraft_geom::PAPER_SIZES.iter().find(|(n, _, _)| *n == "A5").unwrap();
assert_ne!((secs[0].1.page_w, secs[0].1.page_h), (a5.1.max(a5.2), a5.1.min(a5.2)));
assert_eq!((secs[1].1.page_w, secs[1].1.page_h), (a5.1.max(a5.2), a5.1.min(a5.2)));
}
/// Inserting a page number while editing an inherited footer preserves the inherited content
/// and keeps both sections sharing the footer part without unlinking.
#[test]
fn inherited_footer_preserves_content_when_numbering_from_inherited_footer() {
let mut s = Session::new(wordcraft_doc::Document::from_text("front\nbody"));
s.run("select.text", &json!({"text": "front"})).unwrap();
s.run("caret.end", &json!({})).unwrap();
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
s.run("text.insert", &json!({"text": "Footer on sec 0"})).unwrap();
s.run("insert.closeHeader", &json!({})).unwrap();
// Edit the inherited footer from section 1's page.
s.run("insert.editFooter", &json!({"page": 1})).unwrap();
assert_eq!(section_index_of_focus(&s), 1);
// Insert page number at bottom of page.
s.run("insert.pageNumber", &json!({"position": "bottom", "align": "right"})).unwrap();
// Verify footer text retains "Footer on sec 0" as well as the PAGE field.
let secs = s.doc.sections();
assert_eq!(secs[1].1.footers.default, None, "section 1 continues to inherit footer from section 0");
let fid = secs[0].1.footers.default.expect("section 0 footer exists");
let footer_text = s.doc.plain_text(wordcraft_doc::StoryRef::Part(fid));
assert!(footer_text.contains("Footer on sec 0"), "inherited footer content was preserved");
let has_page_field = s.doc.story(wordcraft_doc::StoryRef::Part(fid)).is_some_and(|blocks| {
blocks.iter().any(|b| match &**b {
wordcraft_doc::Block::Para(p) => p.objects.iter().any(|obj| match obj {
wordcraft_doc::InlineObject::Field { instr, .. } | wordcraft_doc::InlineObject::FieldStart { instr, .. } => {
instr.split_whitespace().next().is_some_and(|name| name.eq_ignore_ascii_case("PAGE"))
}
_ => false,
}),
_ => false,
})
});
assert!(has_page_field, "footer contains the PAGE field");
// Both page 0 and page 1 render the shared footer with page numbers.
let l = s.layout();
assert_eq!(l.pages[0].footer_story, Some(fid));
assert_eq!(l.pages[1].footer_story, Some(fid));
}
/// Inserting a page number into the footer while editing an inherited header preserves the
/// inherited footer content and keeps both sections sharing the footer part without unlinking.
#[test]
fn inherited_footer_preserves_content_when_numbering_from_inherited_header() {
let mut s = Session::new(wordcraft_doc::Document::from_text("front\nbody"));
s.run("select.text", &json!({"text": "front"})).unwrap();
s.run("caret.end", &json!({})).unwrap();
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
// Set up header and footer in section 0.
s.run("insert.editHeader", &json!({"page": 0})).unwrap();
s.run("text.insert", &json!({"text": "Header on sec 0"})).unwrap();
s.run("insert.closeHeader", &json!({})).unwrap();
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
s.run("text.insert", &json!({"text": "Footer on sec 0"})).unwrap();
s.run("insert.closeHeader", &json!({})).unwrap();
// Edit the inherited header from section 1's page.
s.run("insert.editHeader", &json!({"page": 1})).unwrap();
assert_eq!(section_index_of_focus(&s), 1);
// Insert page number at bottom of page (into the footer).
s.run("insert.pageNumber", &json!({"position": "bottom", "align": "right"})).unwrap();
// Verify footer text retains "Footer on sec 0" as well as the PAGE field.
let secs = s.doc.sections();
assert_eq!(secs[1].1.footers.default, None, "section 1 continues to inherit footer from section 0");
let fid = secs[0].1.footers.default.expect("section 0 footer exists");
let footer_text = s.doc.plain_text(wordcraft_doc::StoryRef::Part(fid));
assert!(footer_text.contains("Footer on sec 0"), "inherited footer content was preserved");
let has_page_field = s.doc.story(wordcraft_doc::StoryRef::Part(fid)).is_some_and(|blocks| {
blocks.iter().any(|b| match &**b {
wordcraft_doc::Block::Para(p) => p.objects.iter().any(|obj| match obj {
wordcraft_doc::InlineObject::Field { instr, .. } | wordcraft_doc::InlineObject::FieldStart { instr, .. } => {
instr.split_whitespace().next().is_some_and(|name| name.eq_ignore_ascii_case("PAGE"))
}
_ => false,
}),
_ => false,
})
});
assert!(has_page_field, "footer contains the PAGE field");
// Both page 0 and page 1 render the shared footer with page numbers.
let l = s.layout();
assert_eq!(l.pages[0].footer_story, Some(fid));
assert_eq!(l.pages[1].footer_story, Some(fid));
}
/// When a shared footer grows and repagination causes the preceding section to expand
/// onto the hinted page, the active section being edited is preserved rather than
/// reverting to the preceding section.
#[test]
fn repagination_during_shared_footer_edit_preserves_active_section() {
// Determine the line count that exactly fills 1 page with a single-line footer.
let mut n_lines: usize = 10;
while n_lines < 100 {
let lines = (0..n_lines).map(|i| format!("Line {i}")).collect::<Vec<_>>().join("\n");
let mut s = Session::new(wordcraft_doc::Document::from_text(&lines));
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
s.run("text.insert", &json!({"text": "Footer"})).unwrap();
s.run("insert.closeHeader", &json!({})).unwrap();
if s.layout().pages.len() == 1 {
n_lines += 1;
} else {
n_lines = n_lines.saturating_sub(3);
break;
}
}
let lines = (0..n_lines).map(|i| format!("Line {i}")).collect::<Vec<_>>().join("\n");
let mut s = Session::new(wordcraft_doc::Document::from_text(&lines));
s.run("caret.docEnd", &json!({})).unwrap();
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
s.run("text.insert", &json!({"text": "Section 1 body"})).unwrap();
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
s.run("text.insert", &json!({"text": "Shared footer"})).unwrap();
s.run("insert.closeHeader", &json!({})).unwrap();
// Verify initial layout: Section 0 is on page 0, Section 1 is on page 1.
let l = s.layout();
assert_eq!(l.pages.len(), 2);
assert_eq!(l.pages[0].section, 0);
assert_eq!(l.pages[1].section, 1);
// Edit inherited footer from section 1's page.
s.run("insert.editFooter", &json!({"page": 1})).unwrap();
assert_eq!(section_index_of_focus(&s), 1);
// Expand the shared footer so section 0 no longer fits on 1 page and spills onto page 1.
for _ in 0..8 {
s.run("text.newParagraph", &json!({})).unwrap();
s.run("text.insert", &json!({"text": "Expanded footer row"})).unwrap();
}
// Verify repagination: Section 0 now occupies page 0 and page 1; Section 1 is pushed to page 2.
let l = s.layout();
assert!(l.pages.len() >= 3);
assert_eq!(l.pages[0].section, 0);
assert_eq!(l.pages[1].section, 0, "page 1 now occupied by section 0");
assert_eq!(l.pages[2].section, 1, "section 1 pushed to page 2");
// The active section being edited remains section 1 despite page 1 now holding section 0.
assert_eq!(section_index_of_focus(&s), 1);
// Formatting page numbers updates section 1 rather than section 0.
s.run("layout.pageNumberFormat", &json!({"format": "lowerRoman", "start": 10})).unwrap();
let secs = s.doc.sections();
assert_eq!((secs[0].1.page_num_format, secs[0].1.page_num_start), (NumFormat::Decimal, None));
assert_eq!((secs[1].1.page_num_format, secs[1].1.page_num_start), (NumFormat::LowerRoman, Some(10)));
}
/// Section commands follow the page whose header or footer is open, not the body caret's section.
#[test]
fn section_commands_follow_the_page_being_edited() {
let mut s = Session::new(wordcraft_doc::Document::from_text("front\nbody"));
s.run("select.text", &json!({"text": "front"})).unwrap();
s.run("caret.end", &json!({})).unwrap();
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
let body_end = s.doc.end_of(StoryRef::Body);
s.sel = Selection::caret(body_end.clone());
// Page 0 is the first section's, page 1 the second's.
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
s.run("text.insert", &json!({"text": "Footer on the first section"})).unwrap();
s.run("insert.closeHeader", &json!({})).unwrap();
assert_eq!(s.sel, Selection::caret(body_end), "close returns to the body caret");
// Editing page 1's footer (inherited) acts on section 1...
s.run("insert.editFooter", &json!({"page": 1})).unwrap();
assert_eq!(section_index_of_focus(&s), 1);
s.run("insert.closeHeader", &json!({})).unwrap();
// ...and going back to page 0's own footer acts on section 0, though the body caret is in 1.
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
assert_eq!(section_index_of_focus(&s), 0);
s.run("layout.orientation", &json!({"value": "landscape"})).unwrap();
let secs = s.doc.sections();
assert!(secs[0].1.landscape, "the section whose footer is open");
assert!(!secs[1].1.landscape);
}
/// #5855: an out-of-range `insert.createFooter` page leaves the active header/footer section intact.
#[test]
fn create_footer_out_of_range_page_preserves_active_hf_section() {
let mut s = Session::new(wordcraft_doc::Document::from_text("front\nbody"));
s.run("select.text", &json!({"text": "front"})).unwrap();
s.run("caret.end", &json!({})).unwrap();
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
s.run("text.insert", &json!({"text": "Shared footer"})).unwrap();
s.run("insert.closeHeader", &json!({})).unwrap();
// Edit page 1's inherited footer (active section 1), then fail `insert.createFooter` with an
// out-of-range page number.
s.run("insert.editFooter", &json!({"page": 1})).unwrap();
assert_eq!(section_index_of_focus(&s), 1);
assert!(s.run("insert.createFooter", &json!({"page": 99})).is_err());
// Section targeting still points at section 1 rather than falling back to section 0.
assert_eq!(section_index_of_focus(&s), 1);
s.run("layout.pageNumberFormat", &json!({"format": "lowerRoman", "start": 7})).unwrap();
let secs = s.doc.sections();
assert_eq!((secs[0].1.page_num_format, secs[0].1.page_num_start), (NumFormat::Decimal, None));
assert_eq!((secs[1].1.page_num_format, secs[1].1.page_num_start), (NumFormat::LowerRoman, Some(7)));
}
/// #5855: `take_view`/`put_view` preserves `hf_section` when section structure matches, and clears
/// it when a section break is added or removed across another edit.
#[test]
fn take_view_put_view_tracks_hf_section_across_revisions_and_section_breaks() {
// Build a two-section document whose expanded shared footer causes section 0 to spill onto
// page 1 and push section 1 to page 2.
let mut n_lines: usize = 10;
while n_lines < 100 {
let lines = (0..n_lines).map(|i| format!("Line {i}")).collect::<Vec<_>>().join("\n");
let mut s = Session::new(wordcraft_doc::Document::from_text(&lines));
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
s.run("text.insert", &json!({"text": "Footer"})).unwrap();
s.run("insert.closeHeader", &json!({})).unwrap();
if s.layout().pages.len() == 1 {
n_lines += 1;
} else {
n_lines = n_lines.saturating_sub(3);
break;
}
}
let lines = (0..n_lines).map(|i| format!("Line {i}")).collect::<Vec<_>>().join("\n");
let mut s = Session::new(wordcraft_doc::Document::from_text(&lines));
s.run("caret.docEnd", &json!({})).unwrap();
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
s.run("text.insert", &json!({"text": "Section 1 body"})).unwrap();
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
s.run("text.insert", &json!({"text": "Shared footer"})).unwrap();
s.run("insert.closeHeader", &json!({})).unwrap();
// Open section 1's inherited footer on page 1, then expand the footer so page 1 belongs to
// section 0 while `hf_section` still targets section 1.
s.run("insert.editFooter", &json!({"page": 1})).unwrap();
for _ in 0..8 {
s.run("text.newParagraph", &json!({})).unwrap();
s.run("text.insert", &json!({"text": "Expanded footer row"})).unwrap();
}
assert_eq!(s.layout().pages[1].section, 0);
assert_eq!(section_index_of_focus(&s), 1);
// Same revision (`current == true`): `put_view` restores `hf_section`.
let same_rev_view = s.take_view();
s.put_view(same_rev_view);
assert_eq!(section_index_of_focus(&s), 1, "same-revision view swap keeps hf_section");
// Revision changed without changing section breaks: `put_view` still preserves `hf_section`.
let view_before_format = s.take_view();
s.run("select.text", &json!({"text": "Line 0"})).unwrap();
s.run("format.bold", &json!({})).unwrap();
s.put_view(view_before_format);
assert_eq!(section_index_of_focus(&s), 1, "unchanged section breaks preserve hf_section across revision bump");
// Revision changed with a section break added: stale `hf_section` is cleared and resolution
// falls back to `page_hint` (page 1 -> section 0) once layout is refreshed.
let view_before_added_break = s.take_view();
s.run("caret.docEnd", &json!({})).unwrap();
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
s.run("text.insert", &json!({"text": "Section 2"})).unwrap();
s.put_view(view_before_added_break);
assert_eq!(s.hf_section, None);
let _ = s.layout();
assert_eq!(section_index_of_focus(&s), 0, "adding a section break clears stale hf_section");
// Revision changed with a section break removed in a 3-section document: stale `hf_section`
// (`Some(2)`) is cleared rather than clamping onto section 1, both before and after relayout.
let mut s3 = Session::new(wordcraft_doc::Document::from_text("s0\ns1\ns2"));
s3.run("select.text", &json!({"text": "s0"})).unwrap();
s3.run("caret.end", &json!({})).unwrap();
s3.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
s3.run("select.text", &json!({"text": "s1"})).unwrap();
s3.run("caret.end", &json!({})).unwrap();
s3.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
s3.run("insert.editFooter", &json!({"page": 0})).unwrap();
s3.run("text.insert", &json!({"text": "Shared footer"})).unwrap();
s3.run("insert.closeHeader", &json!({})).unwrap();
s3.run("caret.docStart", &json!({})).unwrap();
s3.run("insert.editFooter", &json!({"page": 2})).unwrap();
assert_eq!(section_index_of_focus(&s3), 2);
let view3 = s3.take_view();
s3.run("select.all", &json!({})).unwrap();
s3.run("text.insert", &json!({"text": "a"})).unwrap();
s3.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
s3.run("text.insert", &json!({"text": "b"})).unwrap();
s3.put_view(view3);
assert_eq!(s3.hf_section, None);
assert_eq!(section_index_of_focus(&s3), 0, "stale cached layout does not clamp onto section 1");
let _ = s3.layout();
assert_eq!(section_index_of_focus(&s3), 0, "removing a section break clears stale hf_section");
}
/// #5855: `preview_layout` copies the active header/footer section context so previews target the
/// section whose inherited footer is being edited.
#[test]
fn preview_layout_formats_active_inherited_section_footer() {
let mut s = Session::new(wordcraft_doc::Document::from_text("front\nbody"));
s.run("select.text", &json!({"text": "front"})).unwrap();
s.run("caret.end", &json!({})).unwrap();
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
s.run("insert.pageNumber", &json!({"position": "bottom"})).unwrap();
s.run("insert.closeHeader", &json!({})).unwrap();
s.run("insert.editFooter", &json!({"page": 1})).unwrap();
let (doc, _sel, layout) = s.preview_layout("layout.pageNumberFormat", &json!({"format": "lowerRoman", "start": 7})).unwrap();
let secs = doc.sections();
assert_eq!((secs[0].1.page_num_format, secs[0].1.page_num_start), (NumFormat::Decimal, None));
assert_eq!((secs[1].1.page_num_format, secs[1].1.page_num_start), (NumFormat::LowerRoman, Some(7)));
let page1_footer: String = layout.pages[1]
.footer
.iter()
.flat_map(|it| match it {
crate::layout::Placed::Lines { para, .. } => para.shown.iter().map(|part| part.1.clone()).collect::<Vec<_>>(),
_ => Vec::new(),
})
.collect();
assert!(page1_footer.contains("vii"), "preview renders section 1 footer as vii, got {page1_footer:?}");
}
/// #5855: Moving the caret into a linked footer on another page (via click or keyboard without
/// re-running `editFooter`) updates `hf_section` so section commands target that page's section.
#[test]
fn linked_footer_caret_move_updates_hf_section_without_edit_footer() {
let mut s = Session::new(wordcraft_doc::Document::from_text("front\nbody"));
s.run("select.text", &json!({"text": "front"})).unwrap();
s.run("caret.end", &json!({})).unwrap();
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
// Enter footer on page 0 (section 0) and insert a page number; section 1 inherits it.
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
s.run("insert.pageNumber", &json!({"position": "bottom"})).unwrap();
assert_eq!(s.hf_section, Some(0));
assert_eq!(section_index_of_focus(&s), 0);
// Move caret into the same linked footer on page 1 without calling `insert.editFooter`.
let (x, y) = {
let l = s.layout();
let c = l.caret_on(&s.sel.focus, 1).expect("linked footer laid out on page 1");
(c.x, c.top + c.height * 0.5)
};
let story = match s.sel.focus.story {
wordcraft_doc::StoryRef::Part(id) => format!("part:{id}"),
wordcraft_doc::StoryRef::Body => "body".to_string(),
};
s.run("caret.set", &json!({"page": 1, "x": x, "y": y, "story": story})).unwrap();
assert_eq!(s.hf_section, Some(1));
assert_eq!(section_index_of_focus(&s), 1);
// Formatting page numbers now updates section 1, leaving section 0 untouched.
s.run("layout.pageNumberFormat", &json!({"format": "lowerRoman", "start": 5})).unwrap();
let secs = s.doc.sections();
assert_eq!((secs[0].1.page_num_format, secs[0].1.page_num_start), (NumFormat::Decimal, None));
assert_eq!((secs[1].1.page_num_format, secs[1].1.page_num_start), (NumFormat::LowerRoman, Some(5)));
}
/// #5855: `layout.margins` refreshes layout before reading existing edges when editing a header/footer.
#[test]
fn margins_from_inherited_footer_targets_active_section() {
let mut s = Session::new(wordcraft_doc::Document::from_text("front\nbody"));
s.run("select.text", &json!({"text": "front"})).unwrap();
s.run("caret.end", &json!({})).unwrap();
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
s.run("layout.margins", &json!({"top": 108.0})).unwrap();
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
s.run("text.insert", &json!({"text": "Shared footer"})).unwrap();
s.run("insert.closeHeader", &json!({})).unwrap();
s.run("insert.editFooter", &json!({"page": 1})).unwrap();
s.run("layout.margins", &json!({"left": 90.0})).unwrap();
let secs = s.doc.sections();
assert_eq!(secs[0].1.margin_left, SectionProps::default().margin_left);
assert_eq!(secs[1].1.margin_left, 90.0);
assert_eq!(secs[1].1.margin_top, 108.0);
}
/// An exact (negative) top or bottom margin survives Margins and Orientation: changing another
/// margin keeps it exact, and turning the page moves its size, as a plain margin, to the side it
/// goes to.
#[test]
fn exact_margins_survive_margins_and_orientation() {
let mut s = doc();
s.doc.last_section.margin_top = -60.0;
s.doc.last_section.margin_bottom = -40.0;
s.run("layout.margins", &json!({"left": 80.0})).unwrap();
let x = &s.doc.last_section;
assert_eq!((x.margin_top, x.margin_bottom, x.margin_left), (-60.0, -40.0, 80.0));
// A negative margin given still counts as zero.
s.run("layout.margins", &json!({"top": -30.0})).unwrap();
assert_eq!((s.doc.last_section.margin_top, s.doc.last_section.margin_bottom), (0.0, -40.0));
s.doc.last_section.margin_top = -60.0;
s.run("layout.orientation", &json!({"value": "landscape"})).unwrap();
let x = &s.doc.last_section;
assert!(x.margin_left >= 0.0 && x.margin_right >= 0.0, "{x:?}");
let mut sides = [x.margin_left, x.margin_right];
sides.sort_by(f32::total_cmp);
assert_eq!(sides, [40.0, 60.0], "the exact margins' sizes go to the sides");
}
+6 -1
View File
@@ -18,6 +18,7 @@ mod styles;
mod tabs_borders;
mod tools;
pub(super) use format::drop_direct_indents;
use format::{align, asian_typography, cur, direction, line_spacing, ls, set_align, set_props, tog};
pub use format::{cur as selection_para, fmt, indent, outdent};
pub use lists::{ListButtons, list_buttons, manage_list, touch_all};
@@ -166,13 +167,17 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("para.heading3", "Heading 3", "Home › Styles", |s, _| apply_style(s, &json!({"style": "Heading3"}))).key("Mod+Alt+3"),
CommandSpec::new("para.bullets", "Bullets", "Home › Paragraph", |s, v| list(s, v, ListKind::Bullet)).params(r#"{"kind"?: "bullet" | single char, "off"?: bool}"#).key("Mod+Shift+L"),
CommandSpec::new("para.numbering", "Numbering", "Home › Paragraph", |s, v| list(s, v, ListKind::Numbered))
.params(r#"{"kind"?: "numbered|numberedParen|upperLetter|lowerLetter|lowerRoman|outline", "off"?: bool}"#),
.params(r#"{"kind"?: "numbered|numberedParen|outline|upperLetter|lowerLetter|lowerLetterDot|lowerRoman", "off"?: bool}"#),
CommandSpec::new("para.multilevel", "Multilevel List", "Home › Paragraph", |s, v| list(s, v, ListKind::Legal)).params(r#"{"kind"?: "legal|outline"}"#),
CommandSpec::new("para.listLevel", "Change List Level", "Home › Paragraph › Bullets", |s, v| {
let lvl = p::u64(v, "level").unwrap_or(0).min(8) as u8;
fmt(s, &|p| {
if let Some(n) = p.numbering.as_mut() {
let moved = n.level != lvl;
n.level = lvl;
if moved {
format::drop_direct_indents(p);
}
}
})
})
+24 -2
View File
@@ -163,6 +163,16 @@ pub(super) fn set_props(s: &mut Session, v: &Value) -> CmdResult {
sel_result(s)
}
/// A list item that moves to another level takes that level's indents: a direct indent (a ruler
/// drag, a pasted block, a Word file's `w:ind`) would otherwise win over them and leave the item
/// out of line with its level (#4287).
pub(in crate::cmd) fn drop_direct_indents(p: &mut ParaProps) {
p.indent_left = None;
p.indent_first = None;
p.indent_left_chars = None;
p.indent_first_chars = None;
}
pub fn indent(s: &mut Session, _: &Value) -> CmdResult {
let a = s.sel.ordered().0;
let paths = crate::cmd::selected_paths(s);
@@ -174,7 +184,13 @@ pub fn indent(s: &mut Session, _: &Value) -> CmdResult {
};
let para = s.doc.para_mut(a.story, &path)?;
match num {
Some(n) => para.props.numbering = Some(NumRef { num: n.num, level: n.level.saturating_add(1).min(8) }),
Some(n) => {
let level = n.level.saturating_add(1).min(8);
para.props.numbering = Some(NumRef { num: n.num, level });
if level != n.level {
drop_direct_indents(&mut para.props);
}
}
None => {
para.props.indent_left = Some(((left / tab).floor() + 1.0) * tab);
para.props.cancel_char_indents(true, false, false);
@@ -196,7 +212,13 @@ pub fn outdent(s: &mut Session, _: &Value) -> CmdResult {
};
let para = s.doc.para_mut(a.story, &path)?;
match num {
Some(n) => para.props.numbering = Some(NumRef { num: n.num, level: n.level.saturating_sub(1) }),
Some(n) => {
let level = n.level.saturating_sub(1);
para.props.numbering = Some(NumRef { num: n.num, level });
if level != n.level {
drop_direct_indents(&mut para.props);
}
}
None => {
para.props.indent_left = Some((((left / tab).ceil() - 1.0) * tab).max(0.0));
para.props.cancel_char_indents(true, false, false);
+17 -6
View File
@@ -13,13 +13,24 @@ pub(super) fn list(s: &mut Session, v: &Value, default: ListKind) -> CmdResult {
.map(|p| s.doc.para(a.story, p).and_then(|x| s.doc.styles.resolve_para(&x.props).numbering).filter(|n| n.num != 0))
.collect();
let same_kind = |n: &NumRef| {
s.doc.numbering.level(n.num, n.level).is_some_and(|l| {
let want = wordcraft_doc::numbering::levels_for(kind);
want.get(usize::from(n.level)).is_some_and(|w| {
let want = wordcraft_doc::numbering::levels_for(kind);
// Is the list's level `i` (with this list's own overrides) the preset's level `i`?
let level_is = |i: u8, with_text: bool| match (s.doc.numbering.level(n.num, i), want.get(usize::from(i))) {
(Some(l), Some(w)) => {
(w.format == wordcraft_doc::section::NumFormat::Bullet) == (l.format == wordcraft_doc::section::NumFormat::Bullet)
&& (p::str(v, "kind").is_none() || w.text == l.text)
})
})
// A named preset is the same one only in its number style and text: "1." and "A." are
// both `%1.`, so picking one over the other changes the list, not switches it off (#4281).
&& (!with_text || (w.text == l.text && w.format == l.format))
}
_ => false,
};
let named = p::str(v, "kind").is_some();
// A named preset is told by its first level as well as the paragraph's own, as deeper levels of
// two presets can look alike; unless the list starts with the other kind of marker (a bullet
// above numbers, or the reverse), where the paragraph's own level decides.
let is_bullet = |i: u8| s.doc.numbering.level(n.num, i).map(|l| l.format == wordcraft_doc::section::NumFormat::Bullet);
let one_kind_throughout = is_bullet(0) == is_bullet(n.level);
level_is(n.level, named) && (!named || !one_kind_throughout || level_is(0, true))
};
let remove = off || (!current.is_empty() && current.iter().all(|n| n.as_ref().is_some_and(same_kind)));
if remove {
+1 -1
View File
@@ -113,7 +113,7 @@ pub(super) fn outline_step(s: &mut Session, promote: bool) -> CmdResult {
// Outline view: the headings hidden under a collapsed heading move a level with it.
let carried = crate::cmd::outline::hidden_subheadings(s);
let (a, b) = s.sel.ordered();
let paths = s.doc.paths_between(&a, &b);
let paths = if s.cell_range().is_some_and(|range| !range.stream) { crate::cmd::selected_paths(s) } else { s.doc.paths_between(&a, &b) };
// The heading before the selection, for promoted body text.
let before = s
.doc
+232 -3
View File
@@ -187,12 +187,224 @@ pub(super) fn create_style(s: &mut Session, v: &Value) -> CmdResult {
Ok(json!({"id": id}))
}
/// Deserialize `T` from `v`, rejecting unknown fields on `T` and any nested structs (#9203, #9291).
fn deserialize_strict<T: serde::de::DeserializeOwned>(section: &str, v: &Value) -> Result<T, CmdError> {
use serde::de::{DeserializeSeed, EnumAccess, IntoDeserializer, MapAccess, SeqAccess, VariantAccess, Visitor};
struct StrictDe<'a> {
value: &'a Value,
path: String,
}
struct StrictSeq<'a> {
iter: std::slice::Iter<'a, Value>,
path: &'a str,
index: usize,
}
struct StrictMap<'a> {
iter: serde_json::map::Iter<'a>,
path: &'a str,
current_key: Option<&'a str>,
pending: Option<&'a Value>,
}
struct StrictEnum<'a> {
variant: &'a str,
value: &'a Value,
path: String,
}
fn format_expected(fields: &[&str]) -> String {
match fields {
[] => "there are no fields".into(),
[one] => format!("expected `{one}`"),
[a, b] => format!("expected `{a}` or `{b}`"),
_ => {
let list = fields.iter().map(|f| format!("`{f}`")).collect::<Vec<_>>().join(", ");
format!("expected one of {list}")
}
}
}
// Internally tagged enums buffer their fields before decoding them, bypassing StrictMap.
fn validate_text_fill(path: &str, fill: &Value) -> Result<(), serde_json::Error> {
let fill_path = format!("{path}.fill");
let tag = fill.get("type").or_else(|| fill.get(0));
// Serde's numeric variant indices follow the TextFill declaration order.
let fields: &[_] = match (tag.and_then(Value::as_str), tag.and_then(Value::as_u64)) {
(Some("none"), _) | (_, Some(0)) => &["type"],
(Some("solid"), _) | (_, Some(1)) => &["type", "color", "transparency"],
(Some("gradient"), _) | (_, Some(2)) => &["type", "stops", "angle"],
_ => return Ok(()), // The regular decoder reports missing or unknown tags.
};
let stops = if let Some(map) = fill.as_object() {
if let Some(key) = map.keys().find(|key| !fields.contains(&key.as_str())) {
return Err(serde::de::Error::custom(format!("`{fill_path}`: unknown field `{key}`, {}", format_expected(fields))));
}
map.get("stops")
} else if fields.contains(&"stops") {
fill.get(1)
} else {
None
};
if let Some(stops) = stops.and_then(Value::as_array) {
for (i, stop) in stops.iter().enumerate() {
let stop_path = format!("{fill_path}.stops[{i}]");
<wordcraft_doc::wordart::GradStop as serde::Deserialize>::deserialize(StrictDe { value: stop, path: stop_path.clone() })
.map_err(|e| with_path(&stop_path, e))?;
}
}
Ok(())
}
fn has_path_prefix(msg: &str, path: &str) -> bool {
msg.strip_prefix('`').and_then(|rest| rest.strip_prefix(path)).is_some_and(|rest| matches!(rest.chars().next(), Some('`' | '.' | '[')))
}
fn with_path(path: &str, err: serde_json::Error) -> serde_json::Error {
let msg = err.to_string();
if has_path_prefix(&msg, path) { err } else { serde::de::Error::custom(format!("`{path}`: {msg}")) }
}
impl<'de> SeqAccess<'de> for StrictSeq<'_> {
type Error = serde_json::Error;
fn next_element_seed<S: DeserializeSeed<'de>>(&mut self, seed: S) -> Result<Option<S::Value>, Self::Error> {
let Some(v) = self.iter.next() else { return Ok(None) };
let idx = self.index;
self.index += 1;
let child = format!("{}[{idx}]", self.path);
seed.deserialize(StrictDe { value: v, path: child.clone() }).map(Some).map_err(|e| with_path(&child, e))
}
}
impl<'de> MapAccess<'de> for StrictMap<'_> {
type Error = serde_json::Error;
fn next_key_seed<K: DeserializeSeed<'de>>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error> {
let Some((k, v)) = self.iter.next() else { return Ok(None) };
self.current_key = Some(k.as_str());
self.pending = Some(v);
seed.deserialize(k.as_str().into_deserializer()).map(Some)
}
fn next_value_seed<V: DeserializeSeed<'de>>(&mut self, seed: V) -> Result<V::Value, Self::Error> {
let v = self.pending.take().ok_or_else(|| serde::de::Error::custom("missing map value"))?;
let key = self.current_key.take().unwrap_or("");
let child = format!("{}.{key}", self.path);
seed.deserialize(StrictDe { value: v, path: child.clone() }).map_err(|e| with_path(&child, e))
}
}
impl<'de> VariantAccess<'de> for StrictEnum<'_> {
type Error = serde_json::Error;
fn unit_variant(self) -> Result<(), Self::Error> {
serde::Deserialize::deserialize(self.value)
}
fn newtype_variant_seed<T: DeserializeSeed<'de>>(self, seed: T) -> Result<T::Value, Self::Error> {
let child = format!("{}.{}", self.path, self.variant);
seed.deserialize(StrictDe { value: self.value, path: child.clone() }).map_err(|e| with_path(&child, e))
}
fn tuple_variant<V: Visitor<'de>>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error> {
let child = format!("{}.{}", self.path, self.variant);
serde::Deserializer::deserialize_tuple(StrictDe { value: self.value, path: child.clone() }, len, visitor)
.map_err(|e| with_path(&child, e))
}
fn struct_variant<V: Visitor<'de>>(self, fields: &'static [&'static str], visitor: V) -> Result<V::Value, Self::Error> {
let child = format!("{}.{}", self.path, self.variant);
serde::Deserializer::deserialize_struct(StrictDe { value: self.value, path: child.clone() }, "", fields, visitor)
.map_err(|e| with_path(&child, e))
}
}
impl<'de> EnumAccess<'de> for StrictEnum<'_> {
type Error = serde_json::Error;
type Variant = Self;
fn variant_seed<V: DeserializeSeed<'de>>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error> {
let val = seed.deserialize(self.variant.into_deserializer()).map_err(|e| with_path(&self.path, e))?;
Ok((val, self))
}
}
impl<'de> serde::Deserializer<'de> for StrictDe<'_> {
type Error = serde_json::Error;
fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
match self.value {
Value::Null => visitor.visit_unit(),
Value::Bool(b) => visitor.visit_bool(*b),
Value::Number(n) => n.deserialize_any(visitor),
Value::String(s) => visitor.visit_str(s),
Value::Array(arr) => visitor.visit_seq(StrictSeq { iter: arr.iter(), path: &self.path, index: 0 }),
Value::Object(map) => visitor.visit_map(StrictMap { iter: map.iter(), path: &self.path, current_key: None, pending: None }),
}
}
fn deserialize_option<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
if self.value.is_null() { visitor.visit_none() } else { visitor.visit_some(self) }
}
fn deserialize_newtype_struct<V: Visitor<'de>>(self, _name: &'static str, visitor: V) -> Result<V::Value, Self::Error> {
visitor.visit_newtype_struct(self)
}
fn deserialize_enum<V: Visitor<'de>>(
self,
_name: &'static str,
_variants: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Self::Error> {
match self.value {
Value::String(s) => visitor.visit_enum(s.as_str().into_deserializer()).map_err(|e| with_path(&self.path, e)),
Value::Object(map) if map.len() == 1 => {
if let Some((k, v)) = map.iter().next() {
visitor.visit_enum(StrictEnum { variant: k, value: v, path: self.path })
} else {
self.deserialize_any(visitor)
}
}
_ => self.deserialize_any(visitor),
}
}
fn deserialize_struct<V: Visitor<'de>>(
self,
name: &'static str,
fields: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Self::Error> {
if name == "TextEffects" {
let fill = match self.value {
Value::Array(values) => fields.iter().position(|&field| field == "fill").and_then(|index| values.get(index)),
_ => self.value.get("fill"),
};
if let Some(fill) = fill {
validate_text_fill(&self.path, fill)?;
}
}
if let Value::Object(map) = self.value {
for key in map.keys() {
if !fields.contains(&key.as_str()) {
return Err(serde::de::Error::custom(format!("`{}`: unknown field `{key}`, {}", self.path, format_expected(fields))));
}
}
return visitor.visit_map(StrictMap { iter: map.iter(), path: &self.path, current_key: None, pending: None });
}
self.deserialize_any(visitor)
}
serde::forward_to_deserialize_any! {
bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf
unit unit_struct seq tuple tuple_struct map identifier ignored_any
}
}
T::deserialize(StrictDe { value: v, path: section.to_string() }).map_err(|e| {
let msg = e.to_string();
if has_path_prefix(&msg, section) { CmdError::Params(msg) } else { CmdError::Params(format!("`{section}`: {msg}")) }
})
}
/// Modify a style's character and paragraph formatting, display name or next-paragraph style.
pub(super) fn modify_style(s: &mut Session, v: &Value) -> CmdResult {
let id = style_id(s, p::req_str(v, "style")?)?;
let chr: Option<CharProps> = v.get("chr").map(|c| serde_json::from_value(c.clone())).transpose().map_err(|e| CmdError::Params(e.to_string()))?;
let para: Option<ParaProps> =
v.get("para").map(|c| serde_json::from_value(c.clone())).transpose().map_err(|e| CmdError::Params(e.to_string()))?;
let chr: Option<CharProps> = v.get("chr").map(|c| deserialize_strict("chr", c)).transpose()?;
let para: Option<ParaProps> = v.get("para").map(|c| deserialize_strict("para", c)).transpose()?;
let next = p::str(v, "next").map(str::to_string);
let name = p::str(v, "name").map(str::to_string);
let d = &s.doc.styles.default_chr;
@@ -387,3 +599,20 @@ pub(super) fn set_visibility(s: &mut Session, v: &Value) -> CmdResult {
touch_all(s);
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn nested_type_and_enum_errors_include_full_path() {
let err = deserialize_strict::<ParaProps>("para", &json!({"lineSpacing": {"rule": "bogus"}})).unwrap_err();
assert!(matches!(err, CmdError::Params(ref msg) if msg.contains("`para.lineSpacing.rule`")), "{err:?}");
let err = deserialize_strict::<ParaProps>("para", &json!({"borders": {"top": {"width": "bad"}}})).unwrap_err();
assert!(matches!(err, CmdError::Params(ref msg) if msg.contains("`para.borders.top.width`")), "{err:?}");
let err = deserialize_strict::<ParaProps>("para", &json!({"tabs": [{"pos": "bad"}]})).unwrap_err();
assert!(matches!(err, CmdError::Params(ref msg) if msg.contains("`para.tabs[0].pos`")), "{err:?}");
}
}
+1 -1
View File
@@ -337,7 +337,7 @@ fn clipboard_content(s: &mut Session, v: &Value) -> Result<Pasted, CmdError> {
let text = p::str(v, "text").map(|t| t.replace("\r\n", "\n"));
match text {
Some(t) if !t.is_empty() => Ok(Pasted::Text(t)),
_ => Err(CmdError::Failed("the clipboard is empty".into())),
_ => Err(CmdError::ClipboardEmpty),
}
}
+21
View File
@@ -695,6 +695,27 @@ pub(crate) fn typing_pos(s: &Session, p: &Pos) -> Pos {
Pos { off, ..p.clone() }
}
/// The ranges, in any story, that a document protected as read only, comments only or forms
/// lets this author edit; `None` when the protection doesn't limit where edits may land. A command
/// that searches the whole document keeps only its matches inside them, so a match in protected
/// content (a header repeating a placeholder) is left alone instead of failing the command.
pub(crate) fn editable_ranges(s: &Session) -> Option<Vec<(Pos, Pos)>> {
match s.doc.settings.protection.as_deref()? {
"forms" => {
let stories = std::iter::once(StoryRef::Body).chain(s.doc.parts.keys().map(|k| StoryRef::Part(*k)));
Some(
stories
.flat_map(|story| s.doc.control_ranges(story))
.filter(|r| r.control.lock.can_edit())
.map(|r| (r.content_start(), r.end))
.collect(),
)
}
"readOnly" | "comments" => Some(s.doc.perm_ranges().into_iter().filter(|r| editable_by(r, &s.author)).map(|r| (r.start, r.end)).collect()),
_ => None,
}
}
/// The first position in an editable range after `from` (wrapping round), for Find Next Region
/// I Can Edit; with it, the range's end. Filling in forms: the next fillable control's content.
pub fn next_region(s: &Session, from: &Pos) -> Option<(Pos, Pos)> {
+24
View File
@@ -32,6 +32,30 @@ fn read_only_with_an_exception_allows_edits_only_inside_it() {
assert_eq!(s.doc.settings.protection.as_deref(), Some("readOnly"));
}
/// Replace All covers every story, but in a protected document only the editable regions change:
/// the same placeholder in a header, a footnote or the locked body text is left as it is, and
/// the replacement in the editable region still goes through.
#[test]
fn replace_all_in_a_protected_document_skips_protected_matches() {
let mut s = Session::new(Document::from_text("Locked [NAME].\nFill [NAME] in."));
let header = s.run("insert.header", &json!({"text": "Header [NAME]"})).unwrap()["story"].as_u64().unwrap() as u32;
s.run("caret.docStart", &json!({})).unwrap();
let note = s.run("references.footnote", &json!({"text": "Note [NAME]"})).unwrap()["id"].as_u64().unwrap() as u32;
s.sel = Selection::caret(Pos::body(0, 0));
select(&mut s, "Fill [NAME] in.");
s.run("review.restrict", &json!({"exception": "add"})).unwrap();
s.run("review.restrict", &json!({"mode": "readOnly"})).unwrap();
let r = s.run("edit.replaceAll", &json!({"text": "[NAME]", "with": "Jane"})).unwrap();
assert_eq!(r["replaced"], 1, "{r}");
let body = s.doc.plain_text(StoryRef::Body).replace(OBJ, "");
assert!(body.contains("Locked [NAME]."), "{body}");
assert!(body.contains("Fill Jane in."), "{body}");
for id in [header, note] {
let first = Pos::new(StoryRef::Part(id), wordcraft_doc::Path::top(0), 0);
assert!(s.doc.para_at(&first).unwrap().text.contains("[NAME]"));
}
}
/// An exception that starts a line: Home, Left and Down put the caret before its start
/// marker, and Enter and typing there go inside the exception. A caret after the end marker at
/// the end of the line goes back inside it too.
+2 -1
View File
@@ -20,7 +20,8 @@ use fields::caption;
#[cfg(test)]
use fields::output_fields_with;
pub use fields::{
CHAPTER_SEPARATORS, REFERENCE_NOT_FOUND, output_fields, refresh_date_fields, seq_format, update_fields, update_fields_in, update_seq,
CHAPTER_SEPARATORS, REFERENCE_NOT_FOUND, caption_preview, output_fields, refresh_date_fields, seq_format, update_fields, update_fields_in,
update_seq,
};
pub(crate) use fields::{page_at, page_formats, page_label, page_text};
pub(super) use notes::note_options;
+35 -13
View File
@@ -27,12 +27,29 @@ pub const CHAPTER_SEPARATORS: [&str; 5] = ["-", ".", ":", "\u{2014}", "\u{2013}"
/// a chapter number (`STYLEREF n \s` and a separator) and a `SEQ label \* format \s n` number
/// (ECMA-376 §17.16.5.56, §17.16.5.59).
pub(super) fn caption(s: &mut Session, v: &Value) -> CmdResult {
let (story, at) = caption_site(s, v);
let text = p::str(v, "text").unwrap_or("");
s.doc.insert_block(story, &at, Block::Para(caption_paragraph(v, text)?))?;
update_seq(s)?;
let off = s.doc.para(story, &at).map_or(0, |p| p.len());
s.sel = Selection::caret(Pos { story, path: at, off });
sel_result(s)
}
/// Number a prospective caption at its insertion site without changing the document or selection.
pub fn caption_preview(s: &Session, v: &Value) -> Result<String, CmdError> {
let (story, at) = caption_site(s, v);
let mut doc = s.doc.clone();
doc.insert_block(story, &at, Block::Para(caption_paragraph(v, "")?))?;
update_seq_in(&mut doc)?;
Ok(doc.para(story, &at).map_or_else(String::new, Paragraph::plain_text))
}
fn caption_paragraph(v: &Value, text: &str) -> Result<Paragraph, CmdError> {
let label: String = p::str(v, "label").unwrap_or("Figure").chars().filter(|c| !matches!(c, '"' | '\\') && !c.is_control()).take(40).collect();
let label = if label.trim().is_empty() { "Figure".to_string() } else { label.trim().to_string() };
// SEQ identifiers are one word: Word joins a multi-word label with underscores.
let ident = label.split_whitespace().collect::<Vec<_>>().join("_");
let text = p::str(v, "text").unwrap_or("").to_string();
let above = p::str(v, "position") == Some("above");
let format = seq_format(p::str(v, "format").unwrap_or("ARABIC"));
let chapter = p::u64(v, "chapter").filter(|l| (1..=9).contains(l));
let sep = p::str(v, "separator").and_then(|x| CHAPTER_SEPARATORS.iter().find(|s| **s == x)).copied().unwrap_or("-");
@@ -51,10 +68,15 @@ pub(super) fn caption(s: &mut Session, v: &Value) -> CmdResult {
if !text.is_empty() {
para.insert_text(para.len(), &format!(": {text}"), &CharProps::default())?;
}
Ok(para)
}
fn caption_site(s: &Session, v: &Value) -> (StoryRef, Path) {
// A selected picture, shape or chart: next to the paragraph holding it, in the same cell or
// text box (#1230). Otherwise next to the caret's top-level block: a paragraph, or the whole
// table it is in.
let f = s.sel.focus.clone();
let f = &s.sel.focus;
let above = p::str(v, "position") == Some("above");
let at = match crate::cmd::objects::object_selection(s) {
Some((pos, _)) => {
let k = pos.path.last();
@@ -65,11 +87,7 @@ pub(super) fn caption(s: &mut Session, v: &Value) -> CmdResult {
Path::top(if above { top } else { top.saturating_add(1) })
}
};
s.doc.insert_block(f.story, &at, Block::Para(para))?;
update_seq(s)?;
let off = s.doc.para(f.story, &at).map_or(0, |p| p.len());
s.sel = Selection::caret(Pos { story: f.story, path: at, off });
sel_result(s)
(f.story, at)
}
/// Renumber the body's SEQ fields in document order, honouring `\* format`, `\s level` (restart
@@ -78,11 +96,15 @@ pub(super) fn caption(s: &mut Session, v: &Value) -> CmdResult {
/// the last level-n heading's number, or its count when the heading isn't numbered) and the
/// text or number of the nearest paragraph of a style.
pub fn update_seq(s: &mut Session) -> Result<(), CmdError> {
update_seq_in(&mut s.doc)
}
fn update_seq_in(doc: &mut wordcraft_doc::Document) -> Result<(), CmdError> {
// Numbers first: a STYLEREF to a heading that holds a SEQ field shows its new number.
let numbers = seq_results(&s.doc);
apply_results(&mut s.doc, numbers)?;
let refs = styleref_results(&s.doc);
apply_results(&mut s.doc, refs)
let numbers = seq_results(doc);
apply_results(doc, numbers)?;
let refs = styleref_results(doc);
apply_results(doc, refs)
}
/// A field's fresh result: its story and paragraph, its object index there and the text.
@@ -607,7 +629,7 @@ fn created_at(stamp: &str) -> Option<(u64, i64)> {
/// Word's default date or time picture when a field instruction carries no `\@` picture switch.
fn default_picture(name: &str, lang: Option<&str>) -> String {
if name == "TIME" { "h:mm am/pm".into() } else { crate::cmd::insert::default_date_picture(lang).into() }
if name == "TIME" { crate::cmd::insert::default_time_picture(lang).into() } else { crate::cmd::insert::default_date_picture(lang).into() }
}
/// Most names SET fields give values.
const MAX_SET: usize = 10_000;
+7 -1
View File
@@ -44,11 +44,17 @@ fn in_merged_cell(doc: &wordcraft_doc::Document, path: &Path) -> bool {
pub(super) fn para_numbers(doc: &wordcraft_doc::Document) -> std::collections::HashMap<Path, ParaNumber> {
let mut counters = Counters::default();
let mut out = std::collections::HashMap::new();
// The paragraph before ended a section: the lists that start over there do (#7382).
let mut section_ended = false;
for path in doc.para_paths(StoryRef::Body) {
if std::mem::take(&mut section_ended) {
counters.section_break(&doc.numbering);
}
let Some(p) = doc.para(StoryRef::Body, &path) else { continue };
section_ended = p.section.is_some();
if in_merged_cell(doc, &path) {
continue;
}
let Some(p) = doc.para(StoryRef::Body, &path) else { continue };
let Some(n) = p.props.numbering.or_else(|| doc.styles.resolve_para(&p.props).numbering).filter(|n| n.num != 0) else { continue };
let Some((_, def)) = counters.next_label(&doc.numbering, n.num, n.level) else { continue };
if def.format == NumFormat::Bullet {
+31 -1
View File
@@ -707,7 +707,7 @@ fn a_toc_inserted_in_the_middle_of_a_document_leaves_the_caret_after_it() {
s.sel = Selection::caret(Pos { story: StoryRef::Body, path: Path::top(1), off: 0 });
s.run("references.toc", &json!({"levels": 2})).unwrap();
let (start, end) = toc_range(&s).unwrap();
assert!(start > 0, "the TOC is inserted after the intro paragraph");
assert_eq!(start, 1, "the TOC must immediately follow Intro without an extra blank paragraph");
assert_eq!(s.doc.body[0].as_para().map(|p| p.plain_text()).as_deref(), Some("Intro"));
assert_eq!(
s.sel.focus,
@@ -1129,6 +1129,36 @@ fn a_missing_references_error_is_in_the_interface_language() {
assert_eq!(shown, [french, "Target"]);
}
#[test]
fn full_context_ref_keeps_an_ancestor_when_the_label_contains_literal_percent_zero() {
use std::sync::Arc;
use wordcraft_doc::numbering::Level;
use wordcraft_doc::props::NumRef;
use wordcraft_doc::{Document, ListKind};
for (template, own, full) in [("%0-%2.", "%0-1", "1%0-1"), ("%1-%2.", "1-1", "1-1"), ("(%2).", "(1)", "1(1)")] {
let mut doc = Document::from_text("Parent\nTarget\nRefs ");
let numbering = Arc::make_mut(&mut doc.numbering);
let num = numbering.add_list(ListKind::Numbered);
numbering.nums[0].level_overrides = vec![(1, Level { text: template.into(), ..Default::default() })];
for level in 0..=1u8 {
doc.para_mut(StoryRef::Body, &Path::top(usize::from(level))).unwrap().props.numbering = Some(NumRef { num, level });
}
let mut s = Session::new(doc);
s.run("select.text", &json!({"text": "Target"})).unwrap();
s.run("insert.bookmark", &json!({"name": "Mark"})).unwrap();
s.run("caret.docEnd", &json!({})).unwrap();
for instr in [r"REF Mark \n", r"REF Mark \w"] {
s.run("insert.field", &json!({"instr": instr})).unwrap();
s.run("text.insert", &json!({"text": " "})).unwrap();
}
let refs = stale_last_paragraph(&mut s, "stale");
update_fields(&mut s).unwrap();
assert_eq!(results_in(&s.doc, &refs), [own, full], "{template}");
}
}
/// A REF showing the bookmarked paragraph's number (`\r`, `\n`, `\w`), which output doesn't
/// compute, keeps its stored number when printed or exported rather than show the paragraph's
/// text; a plain REF to the same bookmark is filled in.
+8
View File
@@ -121,8 +121,14 @@ fn toc_entries(s: &Session, f: &FieldCode) -> Vec<TocEntry> {
// Every numbered paragraph advances the list counters, so an entry carries the number its
// heading shows (`1.1`), followed by the level's separator, as Word writes it.
let mut counters = Counters::default();
// The paragraph before ended a section: the lists that start over there do (#7382).
let mut section_ended = false;
for path in s.doc.para_paths(StoryRef::Body) {
if std::mem::take(&mut section_ended) {
counters.section_break(&s.doc.numbering);
}
let Some(p) = s.doc.para(StoryRef::Body, &path) else { continue };
section_ended = p.section.is_some();
let number = p
.props
.numbering
@@ -439,6 +445,8 @@ pub(super) fn insert_toc(s: &mut Session, v: &Value) -> CmdResult {
s.doc.remove_block(StoryRef::Body, &at.path)?;
}
at.path.last()
} else if at.off == 0 {
at.path.last()
} else {
s.doc.split_paragraph(&at)?.path.last()
};
+5 -12
View File
@@ -14,15 +14,14 @@ mod comments;
mod proofing;
pub use proofing::thesaurus_word;
pub(crate) use changes::StyleTarget;
pub(crate) use changes::ReviewTarget;
pub use changes::{
DELETION_TEXT_CHARS, DeletionBalloon, deletion_balloons, format_changes, has_deletions, has_format_changes, move_changes, tracking_json,
};
use changes::{list_changes, nav_change, resolve_all_then, resolve_sel_then, tracking_options};
use comments::{
comment_at_caret, comments_change, delete_comment, edit_comment, list_comments, nav_comment, new_comment, reply, validate_comment_id,
};
pub use comments::resolve_comment_target;
pub use comments::{comment_list, comment_range_at_caret};
use comments::{comments_change, delete_comment, edit_comment, list_comments, nav_comment, new_comment, reply, resolve_comment};
use proofing::{all_issues, issue_at, next_issue, suggestions, thesaurus, word_count};
pub fn specs() -> Vec<CommandSpec> {
@@ -37,14 +36,8 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("review.deleteComment", "Delete", "Review › Comments", delete_comment).params(
r#"{"id"?: non-negative 32-bit JSON integer (omit to use the caret), "all"?: bool (every comment), "resolved"?: bool (every resolved comment, with its replies; wins over all)}"#,
),
CommandSpec::new("review.resolveComment", "Resolve", "Review › Comments", |s, v| {
validate_comment_id(v)?;
let id = p::u64(v, "id").map(|x| x as u32).or_else(|| comment_at_caret(s)).ok_or_else(|| CmdError::Params("`id` required".into()))?;
let c = s.doc.comments.get_mut(&id).ok_or_else(|| CmdError::Params("no such comment".into()))?;
c.resolved = p::bool(v, "value").unwrap_or(!c.resolved);
sel_result(s)
})
.params(r#"{"id"?: non-negative 32-bit JSON integer (omit to use the caret), "value"?: bool (omit to toggle)}"#),
CommandSpec::new("review.resolveComment", "Resolve", "Review › Comments", resolve_comment)
.params(r#"{"id"?: non-negative 32-bit JSON integer (a comment or reply; omit to use the caret), "value"?: bool (omit to toggle the whole thread)}"#),
CommandSpec::new("review.nextComment", "Next", "Review › Comments", |s, _| nav_comment(s, 1)).pure(),
CommandSpec::new("review.previousComment", "Previous", "Review › Comments", |s, _| nav_comment(s, -1)).pure(),
CommandSpec::new("review.comments", "Show Comments", "Review › Comments", list_comments).pure(),
+227 -50
View File
@@ -26,7 +26,8 @@ fn resolve_runs(para: &mut wordcraft_doc::Paragraph, from: usize, to: usize, pro
}
/// Accept or reject a revision range in one paragraph; `mark` includes its paragraph mark (and
/// the section break on it), `props` the paragraph's own formatting change.
/// the section break on it), `props` the paragraph's own formatting change. If the next
/// paragraph moves into this path, return how many bytes of this paragraph precede it.
fn resolve_para(
s: &mut Session,
story: StoryRef,
@@ -34,11 +35,11 @@ fn resolve_para(
(from, to): (usize, usize),
(mark, props): (bool, bool),
accept: bool,
) -> Result<(), CmdError> {
) -> Result<Option<usize>, CmdError> {
let para = s.doc.para_mut(story, path)?;
resolve_runs(para, from, to, props, accept)?;
if !mark {
return Ok(());
return Ok(None);
}
if para.mark.fmt_change.is_some() || para.section.as_ref().is_some_and(|x| x.fmt_change.is_some()) {
fmt_revisions::resolve_char(&mut para.mark, accept);
@@ -49,8 +50,9 @@ fn resolve_para(
}
let (ins, del) = (para.mark.ins, para.mark.del);
if ins.is_none() && del.is_none() {
return Ok(());
return Ok(None);
}
let prefix_len = para.len();
// An inserted paragraph mark that is rejected, or a deleted one that is accepted, goes away:
// the next paragraph joins this one (the split is undone). A paragraph left empty goes away
// whole, so the next one keeps its own style and numbering, as in Word. The end mark of a
@@ -66,15 +68,18 @@ fn resolve_para(
if sectioned {
s.doc.remove_section_break(path.last());
}
if crate::cmd::remove_empty_para(s, story, path)? || crate::cmd::join_next_para(s, story, path)? {
return Ok(());
if crate::cmd::remove_empty_para(s, story, path)? {
return Ok(Some(0));
}
if crate::cmd::join_next_para(s, story, path)? {
return Ok(Some(prefix_len));
}
}
let para = s.doc.para_mut(story, path)?;
para.mark.ins = None;
para.mark.del = None;
para.touch();
Ok(())
Ok(None)
}
/// Remove the whole paragraph at `path` when a whole-paragraph revision on its mark resolved to
@@ -102,7 +107,7 @@ fn resolve_cell(s: &mut Session, story: StoryRef, path: &wordcraft_doc::Path, ac
let row = t.rows.get(r);
t.props.fmt_change.is_some()
|| row.is_some_and(|x| x.props.fmt_change.is_some())
|| row.and_then(|x| x.cells.get(c)).is_some_and(|x| x.props.fmt_change.is_some())
|| row.and_then(|x| x.cells.get(c)).is_some_and(|x| x.props.fmt_change.is_some() || x.props.merge_change.is_some())
});
if !has {
return Ok(false);
@@ -133,45 +138,112 @@ fn resolve_styles_sel(s: &mut Session, whole_body: bool, accept: bool) -> Result
Ok(true)
}
/// The style-definition change Next / Previous Change selected (#2697). Every style change sits
/// at the same collapsed anchor at the start of the document, so the selection alone can't say
/// which one it is: this does, for the Accept or Reject that follows, while the selection stays
/// where the navigation left it.
/// The change Next / Previous Change selected when the selection alone can't say which one it is,
/// for the Accept or Reject that follows, while the selection stays where the navigation left it:
/// a style-definition change (`style`; every one sits at the same collapsed anchor at the start
/// of the document, #2697), or a table's, row's or cell's change (`style` `None`: formatting, or
/// a cell's tracked merge or split, at the start of the cell, where tracked text may start too).
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct StyleTarget {
pub(crate) struct ReviewTarget {
document: u64,
sel: Selection,
style: String,
style: Option<String>,
rev: u32,
/// For a table's, row's or cell's change, which one: several share the cell's start, and
/// one revision may have made more than one of them.
pub(crate) scope: Option<Scope>,
}
/// Which of the changes at the start of a table cell a change is: the table's formatting, its
/// row's, the cell's, or the cell's tracked merge or split.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Scope {
Table,
Row,
Cell,
Merge,
}
/// The navigated style change, when the selection is still the one navigation made.
fn navigated_style(s: &Session) -> Option<StyleTarget> {
s.review_style.clone().filter(|t| t.document == s.document_id() && t.sel == s.sel)
fn navigated_target(s: &Session) -> Option<ReviewTarget> {
s.review_target.clone().filter(|t| t.document == s.document_id() && t.sel == s.sel)
}
/// Accept or reject the navigated style change alone: that revision in that style. Returns whether
/// it was still there.
fn resolve_style_change(s: &mut Session, t: &StyleTarget, accept: bool) -> bool {
fn resolve_style_change(s: &mut Session, style: &str, rev: u32, accept: bool) -> bool {
let revs = |st: &wordcraft_doc::styles::Style| [st.para_change.as_ref().map(|c| c.rev), st.chr_change.as_ref().map(|c| c.rev)];
if !s.doc.styles.styles.iter().any(|st| st.id == t.style && revs(st).contains(&Some(t.rev))) {
if !s.doc.styles.styles.iter().any(|st| st.id == style && revs(st).contains(&Some(rev))) {
return false;
}
for st in std::sync::Arc::make_mut(&mut s.doc.styles).styles.iter_mut().filter(|st| st.id == t.style) {
fmt_revisions::resolve_style_rev(st, t.rev, accept);
for st in std::sync::Arc::make_mut(&mut s.doc.styles).styles.iter_mut().filter(|st| st.id == style) {
fmt_revisions::resolve_style_rev(st, rev, accept);
}
true
}
/// Select change `c` and remember which style change it is, if it is one.
/// Select change `c` and remember which style or table change it is, if it is one.
fn select_change(s: &mut Session, c: &Change) {
s.sel = Selection { anchor: c.a.clone(), focus: c.b.clone() };
s.review_style = c.style.clone().zip(c.rev).map(|(style, rev)| StyleTarget { document: s.document_id(), sel: s.sel.clone(), style, rev });
s.review_target = c.rev.filter(|_| c.style.is_some() || c.scope.is_some()).map(|rev| ReviewTarget {
document: s.document_id(),
sel: s.sel.clone(),
style: c.style.clone(),
rev,
scope: c.scope,
});
}
/// Whether `c` is the change target `t` names.
fn is_target(c: &Change, t: &ReviewTarget) -> bool {
c.rev == Some(t.rev) && c.style == t.style && c.scope == t.scope && (t.style.is_some() || c.a == t.sel.anchor)
}
/// Accept or reject the one table, row or cell change `scope` of the table cell `path` is in.
/// Returns whether it was still there.
fn resolve_scope(s: &mut Session, story: StoryRef, path: &wordcraft_doc::Path, scope: Scope, accept: bool) -> Result<bool, CmdError> {
let Some((tp, r, c)) = path.cell() else { return Ok(false) };
let Some(t) = s.doc.table(story, &tp) else { return Ok(false) };
let cell = t.rows.get(r).and_then(|x| x.cells.get(c));
let there = match scope {
Scope::Table => t.props.fmt_change.is_some(),
Scope::Row => t.rows.get(r).is_some_and(|x| x.props.fmt_change.is_some()),
Scope::Cell => cell.is_some_and(|x| x.props.fmt_change.is_some()),
Scope::Merge => cell.is_some_and(|x| x.props.merge_change.is_some()),
};
if !there {
return Ok(false);
}
let t = s.doc.table_mut(story, &tp)?;
match scope {
Scope::Table => fmt_revisions::resolve_table(t, accept),
Scope::Row => {
if let Some(row) = t.rows.get_mut(r) {
fmt_revisions::resolve_row(row, accept);
}
}
// The cell's formatting alone: a tracked merge it also has is a change of its own.
Scope::Cell => {
if let Some(cell) = t.rows.get_mut(r).and_then(|x| x.cells.get_mut(c)) {
let merge = cell.props.merge_change.take();
fmt_revisions::resolve_cell(cell, accept);
cell.props.merge_change = merge;
}
}
// Accepted or rejected alike, only the record goes: the cells stay as they are (Word).
Scope::Merge => {
if let Some(cell) = t.rows.get_mut(r).and_then(|x| x.cells.get_mut(c)) {
cell.props.merge_change = None;
}
}
}
Ok(true)
}
/// A tracked change, for navigation and the Reviewing Pane: its range, kind (`insert`,
/// `delete`, `format`), revision, and for a formatting change the properties it set; for a
/// style-definition change, the style's id.
/// `delete`, `format`, `cellMerge`, `cellSplit`), revision, and for a formatting change the
/// properties it set; for a style-definition change, the style's id; whether it is a table's,
/// row's or cell's (resolved with the cell, [`resolve_cell`]).
struct Change {
a: Pos,
b: Pos,
@@ -179,11 +251,12 @@ struct Change {
rev: Option<u32>,
props: Vec<Value>,
style: Option<String>,
pub(crate) scope: Option<Scope>,
}
impl Change {
fn format(a: Pos, b: Pos, rev: u32, props: Vec<Value>) -> Change {
Change { a, b, kind: "format", rev: Some(rev), props, style: None }
Change { a, b, kind: "format", rev: Some(rev), props, style: None, scope: None }
}
}
@@ -201,7 +274,7 @@ fn mark_change(s: &Session, story: StoryRef, path: &wordcraft_doc::Path) -> Opti
} else {
a.clone()
};
Some(Change { a, b, kind, rev: p.mark.ins.or(p.mark.del), props: Vec::new(), style: None })
Some(Change { a, b, kind, rev: p.mark.ins.or(p.mark.del), props: Vec::new(), style: None, scope: None })
}
/// The kind of an insertion / deletion change: `insert`, `delete`, or for one end of a move
@@ -259,7 +332,50 @@ fn resolve_loose_blocks(blocks: &mut wordcraft_doc::Blocks, accept: bool) -> Res
Ok(())
}
/// Byte offset after resolving the runs in the endpoint's original paragraph.
fn resolved_offset(s: &Session, end: &Pos, accept: bool) -> usize {
let Some(para) = s.doc.para_at(end) else { return end.off };
let removed: usize = para
.run_ranges()
.filter(|(_, c)| if accept { c.del.is_some() } else { c.ins.is_some() })
.map(|(range, _)| end.off.min(range.end).saturating_sub(range.start))
.sum();
end.off - removed
}
/// The next paragraph has moved into `path` (empty removal) or been appended to its surviving
/// prefix (join). Later siblings, including a table containing an endpoint, shift one block back.
fn remap_after_middle_paragraph(s: &mut Session, story: StoryRef, path: &wordcraft_doc::Path, prefix_len: usize, offsets: &mut [usize; 2]) {
let depth = path.parent().len();
for (end, offset) in [&mut s.sel.anchor, &mut s.sel.focus].into_iter().zip(offsets) {
if end.story != story || !end.path.0.starts_with(path.parent()) {
continue;
}
let Some(&block) = end.path.0.get(depth) else { continue };
if block as usize > path.last() {
let mut dest = end.path.clone();
dest.0[depth] -= 1;
// An endpoint in a terminal paragraph removed earlier still uses terminal clamping.
if s.doc.para(story, &dest).is_none() {
continue;
}
if &dest == path {
*offset = offset.saturating_add(prefix_len);
}
end.path = dest;
} else if &end.path == path {
*offset = (*offset).min(prefix_len);
} else {
continue;
}
end.off = *offset;
}
}
fn resolve_all(s: &mut Session, accept: bool) -> CmdResult {
let mut offsets = [&s.sel.anchor, &s.sel.focus].map(|end| resolved_offset(s, end, accept));
s.sel.anchor.off = offsets[0];
s.sel.focus.off = offsets[1];
let stories: Vec<StoryRef> = std::iter::once(StoryRef::Body).chain(s.doc.parts.keys().map(|k| StoryRef::Part(*k))).collect();
for st in stories {
for path in s.doc.para_paths(st).into_iter().rev() {
@@ -269,16 +385,20 @@ fn resolve_all(s: &mut Session, accept: bool) -> CmdResult {
let is_last = s.doc.block(st, &path.with_last(path.last().saturating_add(1))).is_none();
let trailing = is_last && s.doc.para(st, &path).is_some_and(|p| (p.mark.del.is_some() && accept) || (p.mark.ins.is_some() && !accept));
let len = s.doc.para(st, &path).map(|p| p.len()).unwrap_or(0);
resolve_para(s, st, &path, (0, len), (true, true), accept)?;
let prefix_len = resolve_para(s, st, &path, (0, len), (true, true), accept)?;
if trailing && remove_trailing_para(s, st, &path)? {
// Selection ends in the removed paragraph go to the end of the one before it;
// clamping later would keep their offsets in that paragraph's text (#8500).
for end in [&mut s.sel.anchor, &mut s.sel.focus] {
// keep that offset through any later remapping when earlier edits resolve.
for (end, offset) in [&mut s.sel.anchor, &mut s.sel.focus].into_iter().zip(&mut offsets) {
if end.story == st && end.path == path {
*end = s.doc.clamp(&Pos { off: usize::MAX, ..end.clone() });
*offset = end.off;
}
}
}
if let Some(prefix_len) = prefix_len {
remap_after_middle_paragraph(s, st, &path, prefix_len, &mut offsets);
}
}
}
// Tables, rows, cells, sections and style definitions.
@@ -465,8 +585,14 @@ fn remap_row_props(mut r: &mut wordcraft_doc::props::RowProps, remap: &[Option<u
changed
}
// A cell's tracked merge, in the cell's properties as they are and in any it had before a
// formatting change (one is built without it, but one from elsewhere may hold it).
fn collect_cell_props(mut c: &wordcraft_doc::props::CellProps, f: &mut impl FnMut(u32) -> bool) {
while let Some(ch) = c.fmt_change.as_deref() {
loop {
if let Some(m) = c.merge_change {
f(m.rev);
}
let Some(ch) = c.fmt_change.as_deref() else { break };
if !f(ch.rev) {
break;
}
@@ -476,7 +602,15 @@ fn collect_cell_props(mut c: &wordcraft_doc::props::CellProps, f: &mut impl FnMu
fn remap_cell_props(mut c: &mut wordcraft_doc::props::CellProps, remap: &[Option<u32>]) -> bool {
let mut changed = false;
while let Some(old) = step_prop_change(&mut c.fmt_change, remap, &mut changed) {
loop {
if let Some(m) = c.merge_change {
let next = lookup_rev(m.rev, remap).map(|rev| wordcraft_doc::props::CellMergeChange { rev, ..m });
if next != c.merge_change {
c.merge_change = next;
changed = true;
}
}
let Some(old) = step_prop_change(&mut c.fmt_change, remap, &mut changed) else { break };
c = old;
}
changed
@@ -912,12 +1046,21 @@ fn revision_span(p: &Paragraph, off: usize) -> Option<std::ops::Range<usize>> {
fn resolve_sel(s: &mut Session, accept: bool, next: bool) -> CmdResult {
// The style change Next / Previous Change selected: that one alone. A caret put at the
// document start any other way resolves no style change.
let navigated = navigated_style(s);
s.review_style = None;
if let Some(t) = navigated
&& resolve_style_change(s, &t, accept)
{
return if next { select_next_unresolved(s) } else { sel_result(s) };
let navigated = navigated_target(s);
s.review_target = None;
if let Some(t) = navigated {
let done = match &t.style {
Some(style) => resolve_style_change(s, style, t.rev, accept),
// A table's, row's or cell's change: that one, not the cell's others nor tracked text
// that starts there too.
None => match t.scope {
Some(scope) => resolve_scope(s, t.sel.anchor.story, &t.sel.anchor.path, scope, accept)?,
None => false,
},
};
if done {
return if next { select_next_unresolved(s) } else { sel_result(s) };
}
}
let (a, b) = s.sel.ordered();
// Capture this before text revisions are resolved: accepting a deletion or rejecting an
@@ -963,7 +1106,7 @@ fn resolve_sel(s: &mut Session, accept: bool, next: bool) -> CmdResult {
// A paragraph's mark is in the selection when the selection goes on past it.
let mark = path != b.path || caret_mark.as_ref() == Some(&path);
let props = (ranged && (path != b.path || to > from)) || caret_props.as_ref() == Some(&path);
resolve_para(s, a.story, &path, (from, to), (mark, props), accept)?;
let _ = resolve_para(s, a.story, &path, (from, to), (mark, props), accept)?;
if ranged {
resolve_cell(s, a.story, &path, accept)?;
}
@@ -988,19 +1131,39 @@ fn changes(s: &Session) -> Vec<Change> {
for path in s.doc.para_paths(StoryRef::Body) {
let Some(p) = s.doc.para(StoryRef::Body, &path) else { continue };
// A table's, row's and cell's changes sit at the start of the cell's first paragraph.
if path.last() == 0
&& let Some((tp, r, c)) = path.cell()
// At the cell's first paragraph of its own: after a nested table that starts the cell, say.
if let Some((tp, r, c)) = path.cell()
&& let Some(t) = s.doc.table(StoryRef::Body, &tp)
&& let Some(cell) = t.rows.get(r).and_then(|x| x.cells.get(c))
&& cell.blocks.iter().position(|b| b.as_para().is_some()) == Some(path.last())
{
let row = t.rows.get(r);
let cell = row.and_then(|x| x.cells.get(c));
let cell = Some(cell);
let found = [
(r == 0 && c == 0).then(|| t.props.fmt_change.as_ref().map(|ch| (ch.rev, fmt_revisions::table_diff(&t.props)))).flatten(),
(c == 0).then(|| row.and_then(|x| x.props.fmt_change.as_ref().map(|ch| (ch.rev, fmt_revisions::row_diff(&x.props))))).flatten(),
cell.and_then(|x| x.props.fmt_change.as_ref().map(|ch| (ch.rev, fmt_revisions::cell_diff(&x.props)))),
(r == 0 && c == 0)
.then(|| t.props.fmt_change.as_ref().map(|ch| (Scope::Table, ch.rev, fmt_revisions::table_diff(&t.props))))
.flatten(),
(c == 0)
.then(|| row.and_then(|x| x.props.fmt_change.as_ref().map(|ch| (Scope::Row, ch.rev, fmt_revisions::row_diff(&x.props)))))
.flatten(),
cell.and_then(|x| x.props.fmt_change.as_ref().map(|ch| (Scope::Cell, ch.rev, fmt_revisions::cell_diff(&x.props)))),
];
for (rev, props) in found.into_iter().flatten() {
out.push(Change::format(mk(&path, 0), mk(&path, 0), rev, props));
for (scope, rev, props) in found.into_iter().flatten() {
out.push(Change { scope: Some(scope), ..Change::format(mk(&path, 0), mk(&path, 0), rev, props) });
}
// A tracked merge or split of the cell: merged cells when the cell is in a merge after
// it, else split cells (Word for Windows).
if let Some(m) = cell.and_then(|x| x.props.merge_change) {
let kind = if m.v_merge.is_some() { "cellMerge" } else { "cellSplit" };
out.push(Change {
a: mk(&path, 0),
b: mk(&path, 0),
kind,
rev: Some(m.rev),
props: Vec::new(),
style: None,
scope: Some(Scope::Merge),
});
}
}
if let Some(ch) = &p.props.fmt_change {
@@ -1009,13 +1172,22 @@ fn changes(s: &Session) -> Vec<Change> {
for (r, c) in p.run_ranges() {
let kind = run_kind(&s.doc, c.ins, c.del);
if !kind.is_empty() {
out.push(Change { a: mk(&path, r.start), b: mk(&path, r.end), kind, rev: c.ins.or(c.del), props: Vec::new(), style: None });
out.push(Change {
a: mk(&path, r.start),
b: mk(&path, r.end),
kind,
rev: c.ins.or(c.del),
props: Vec::new(),
style: None,
scope: None,
});
}
let Some(ch) = &c.fmt_change else { continue };
let props = fmt_revisions::char_diff(c);
// Neighbouring runs changed the same way by the same revision are one change.
if let Some(last) =
out.last_mut().filter(|l| l.kind == "format" && l.rev == Some(ch.rev) && l.b == mk(&path, r.start) && l.props == props)
if let Some(last) = out
.last_mut()
.filter(|l| l.kind == "format" && l.scope.is_none() && l.rev == Some(ch.rev) && l.b == mk(&path, r.start) && l.props == props)
{
last.b = mk(&path, r.end);
} else {
@@ -1162,7 +1334,7 @@ pub(super) fn nav_change(s: &mut Session, dir: i32) -> CmdResult {
let list = changes(s);
let caret = s.sel.ordered();
// From a navigated style change, the one next to it in the list (they share their anchor).
let at = navigated_style(s).and_then(|t| list.iter().position(|c| c.style.as_deref() == Some(t.style.as_str()) && c.rev == Some(t.rev)));
let at = navigated_target(s).and_then(|t| list.iter().position(|c| is_target(c, &t)));
let t = match at {
Some(i) if dir > 0 && i + 1 < list.len() => list.get(i + 1),
Some(i) if dir < 0 && i > 0 => list.get(i - 1),
@@ -1203,6 +1375,11 @@ pub(super) fn list_changes(s: &mut Session, _: &Value) -> CmdResult {
v["description"] = json!(fmt_revisions::describe(&c.props));
v["props"] = json!(c.props);
}
match c.kind {
"cellMerge" => v["description"] = json!("Merged cells"),
"cellSplit" => v["description"] = json!("Split cells"),
_ => {}
}
// One end of a move: its name links it with the other end.
if let Some(name) = rev.and_then(|r| r.move_name.as_deref()).filter(|_| c.kind.starts_with("move")) {
v["move"] = json!(name);
+32
View File
@@ -186,6 +186,38 @@ fn threads_of(s: &Session, roots: impl IntoIterator<Item = u32>) -> Vec<u32> {
ids
}
/// Validates `review.resolveComment` parameters and resolves the target comment id (#9389).
pub fn resolve_comment_target(s: &Session, v: &Value) -> Result<u32, CmdError> {
validate_comment_id(v)?;
let id = p::u64(v, "id").map(|x| x as u32).or_else(|| comment_at_caret(s)).ok_or_else(|| CmdError::Params("`id` required".into()))?;
if !s.doc.comments.contains_key(&id) {
return Err(CmdError::Params("no such comment".into()));
}
Ok(id)
}
/// Resolve or reopen the whole discussion, even when the target is a reply. A toggle uses
/// the target's state, matching its Resolve/Reopen button even in a mixed-state file.
pub(super) fn resolve_comment(s: &mut Session, v: &Value) -> CmdResult {
let id = resolve_comment_target(s, v)?;
let c = &s.doc.comments[&id];
let resolved = p::bool(v, "value").unwrap_or(!c.resolved);
let mut root = id;
let mut seen = BTreeSet::new();
while seen.insert(root) {
match s.doc.comments.get(&root).and_then(|c| c.parent).filter(|p| s.doc.comments.contains_key(p)) {
Some(parent) => root = parent,
None => break,
}
}
for id in threads_of(s, [root]) {
if let Some(c) = s.doc.comments.get_mut(&id) {
c.resolved = resolved;
}
}
sel_result(s)
}
pub(super) fn delete_comment(s: &mut Session, v: &Value) -> CmdResult {
validate_comment_id(v)?;
let ids: Vec<u32> = if p::bool(v, "resolved").unwrap_or(false) {
+493 -1
View File
@@ -311,7 +311,7 @@ fn comment_range_at_caret_needs_the_caret_inside_the_range() {
assert_eq!(super::comment_range_at_caret(&s), Some(id), "inside the commented text");
s.run("select.text", &json!({"text": "three"})).unwrap();
assert_eq!(super::comment_range_at_caret(&s), None, "elsewhere in the paragraph");
assert_eq!(super::comment_at_caret(&s), Some(id), "the older lookup still falls back to the paragraph's comment");
assert_eq!(super::comments::comment_at_caret(&s), Some(id), "the older lookup still falls back to the paragraph's comment");
}
fn glyph_text(d: &[Draw]) -> String {
@@ -491,6 +491,148 @@ fn deletions_outside_the_body_stay_inline_when_revisions_go_in_balloons() {
assert_eq!(deletion_balloons(&s), vec![DeletionBalloon { at: Pos::body(0, at), author: "Ana".into(), text: "zeta".into() }]);
}
fn assert_revision_arrow_stops(s: &mut Session, story: wordcraft_doc::StoryRef, from: [usize; 2], to: [usize; 2]) {
use wordcraft_doc::{Path, Pos};
let pos = |off| Pos::new(story, Path::top(0), off);
for (key, start, end) in [("Right", from[0], to[0]), ("Left", from[1], to[1])] {
let cmd = s.registry.by_shortcut(key).unwrap().id;
for extend in [false, true] {
s.run("caret.set", &json!({"pos": pos(start)})).unwrap();
s.run(cmd, &json!({"extend": extend})).unwrap();
assert_eq!(s.sel.focus, pos(end), "{key}, Shift {extend}, from {start}");
assert_eq!(s.sel.anchor, pos(if extend { start } else { end }));
}
}
}
#[test]
fn horizontal_arrows_follow_revision_balloon_visibility_by_story() {
use wordcraft_doc::{Path, Pos, StoryRef};
let mut s = Session::new(Document::from_text("AQRSZ"));
let id = s.run("insert.header", &json!({"text": "ABCDZ"})).unwrap()["story"].as_u64().unwrap() as u32;
let header = StoryRef::Part(id);
s.run("insert.closeHeader", &json!({})).unwrap();
s.run("review.trackChanges", &json!({"value": true})).unwrap();
for story in [StoryRef::Body, header] {
let at = |off| Pos::new(story, Path::top(0), off);
s.run("select.range", &json!({"anchor": at(1), "focus": at(4)})).unwrap();
s.run("text.delete", &json!({})).unwrap();
assert!(s.doc.para_at(&at(1)).unwrap().props_of_char(1).del.is_some());
}
s.run("review.trackingOptions", &json!({"balloons": "revisions"})).unwrap();
assert!(s.revisions_in_balloons());
assert_revision_arrow_stops(&mut s, StoryRef::Body, [1, 4], [5, 0]);
assert_revision_arrow_stops(&mut s, header, [1, 4], [2, 3]);
s.run("view.commentsPane", &json!({"value": true})).unwrap();
assert!(!s.revisions_in_balloons());
assert_revision_arrow_stops(&mut s, StoryRef::Body, [1, 4], [2, 3]);
s.run("review.trackingOptions", &json!({"balloons": "inline"})).unwrap();
s.run("view.commentsPane", &json!({"value": false})).unwrap();
assert_revision_arrow_stops(&mut s, StoryRef::Body, [1, 4], [2, 3]);
s.run("review.markup", &json!({"value": "noMarkup"})).unwrap();
for story in [StoryRef::Body, header] {
assert_revision_arrow_stops(&mut s, story, [1, 4], [5, 0]);
}
}
#[test]
fn horizontal_arrows_distinguish_hidden_deletions_from_hidden_move_sources() {
use wordcraft_doc::{Pos, Revision, RevisionKind, StoryRef};
let mut doc = Document::from_text("AxyuvZuv");
let deletion = Revision::new(RevisionKind::Delete, "Author", "");
let source = Revision { move_name: Some("Move1".into()), ..deletion.clone() };
let destination = Revision { kind: RevisionKind::Insert, ..source.clone() };
doc.revisions.extend([deletion, source, destination]);
doc.format_range(&Pos::body(0, 1), &Pos::body(0, 3), &|c| c.del = Some(0)).unwrap();
doc.format_range(&Pos::body(0, 3), &Pos::body(0, 5), &|c| c.del = Some(1)).unwrap();
doc.format_range(&Pos::body(0, 6), &Pos::body(0, 8), &|c| c.ins = Some(2)).unwrap();
let mut s = Session::new(doc);
for (delete_mark, move_from_mark, expected) in [
("strikethrough", "strikethrough", [2, 4]),
("hidden", "strikethrough", [4, 4]),
("strikethrough", "hidden", [2, 2]),
("hidden", "hidden", [6, 0]),
] {
s.run("review.trackingOptions", &json!({"balloons": "inline", "deleteMark": delete_mark, "moveFromMark": move_from_mark})).unwrap();
assert_revision_arrow_stops(&mut s, StoryRef::Body, [1, 5], expected);
}
}
#[test]
fn word_moves_follow_layout_visibility_for_balloons_and_hidden_marks() {
use wordcraft_doc::{Path, Pos, Revision, RevisionKind, StoryRef};
let mut s = Session::new(Document::from_text("one del two"));
let id = s.run("insert.header", &json!({"text": "one del two"})).unwrap()["story"].as_u64().unwrap() as u32;
let header = StoryRef::Part(id);
s.run("insert.closeHeader", &json!({})).unwrap();
s.run("review.trackChanges", &json!({"value": true})).unwrap();
let del_start = "one ".len();
let two_start = "one del ".len();
for story in [StoryRef::Body, header] {
s.run("select.range", &json!({"anchor": Pos::new(story, Path::top(0), del_start), "focus": Pos::new(story, Path::top(0), two_start)}))
.unwrap();
s.run("text.delete", &json!({})).unwrap();
}
s.run("review.trackingOptions", &json!({"balloons": "revisions"})).unwrap();
assert!(s.revisions_in_balloons());
s.run("caret.set", &json!({"pos": Pos::body(0, 0)})).unwrap();
s.run("caret.wordRight", &json!({})).unwrap();
assert_eq!(s.sel.focus, Pos::body(0, two_start), "Body in balloons skips deleted word on Ctrl+Right");
s.run("caret.wordLeft", &json!({})).unwrap();
assert_eq!(s.sel.focus, Pos::body(0, 0), "Body in balloons skips deleted word on Ctrl+Left");
s.run("caret.set", &json!({"pos": Pos::new(header, Path::top(0), 0)})).unwrap();
s.run("caret.wordRight", &json!({})).unwrap();
assert_eq!(s.sel.focus, Pos::new(header, Path::top(0), del_start), "Header inline keeps deleted word stop on Ctrl+Right");
s.run("view.commentsPane", &json!({"value": true})).unwrap();
assert!(!s.revisions_in_balloons());
s.run("caret.set", &json!({"pos": Pos::body(0, 0)})).unwrap();
s.run("caret.wordRight", &json!({})).unwrap();
assert_eq!(s.sel.focus, Pos::body(0, del_start), "Body stops at deleted word once revisions move inline");
let mut doc = Document::from_text("one del mov two");
let deletion = Revision::new(RevisionKind::Delete, "Author", "");
let source = Revision { move_name: Some("Move1".into()), ..deletion.clone() };
let destination = Revision { kind: RevisionKind::Insert, ..source.clone() };
doc.revisions.extend([deletion, source, destination]);
let mov_start = "one del ".len();
let end_two_start = "one del mov ".len();
doc.format_range(&Pos::body(0, del_start), &Pos::body(0, mov_start), &|c| c.del = Some(0)).unwrap();
doc.format_range(&Pos::body(0, mov_start), &Pos::body(0, end_two_start), &|c| c.del = Some(1)).unwrap();
doc.format_range(&Pos::body(0, end_two_start), &Pos::body(0, "one del mov two".len()), &|c| c.ins = Some(2)).unwrap();
let mut s = Session::new(doc);
for (delete_mark, move_from_mark, right_from, right_to, left_to) in [
("strikethrough", "strikethrough", del_start, mov_start, mov_start),
("hidden", "strikethrough", 0, mov_start, mov_start),
("strikethrough", "hidden", del_start, end_two_start, del_start),
("hidden", "hidden", 0, end_two_start, 0),
] {
s.run("review.trackingOptions", &json!({"balloons": "inline", "deleteMark": delete_mark, "moveFromMark": move_from_mark})).unwrap();
s.run("caret.set", &json!({"pos": Pos::body(0, right_from)})).unwrap();
s.run("caret.wordRight", &json!({})).unwrap();
assert_eq!(s.sel.focus, Pos::body(0, right_to), "Ctrl+Right ({delete_mark}, {move_from_mark})");
s.run("caret.set", &json!({"pos": Pos::body(0, end_two_start)})).unwrap();
s.run("caret.wordLeft", &json!({})).unwrap();
assert_eq!(s.sel.focus, Pos::body(0, left_to), "Ctrl+Left ({delete_mark}, {move_from_mark})");
}
s.run("review.trackingOptions", &json!({"balloons": "inline", "deleteMark": "hidden", "moveFromMark": "strikethrough"})).unwrap();
s.run("caret.set", &json!({"pos": Pos::body(0, mov_start)})).unwrap();
s.run("caret.wordLeft", &json!({})).unwrap();
assert_eq!(s.sel.focus, Pos::body(0, 0), "Ctrl+Left from mov skips hidden del");
}
fn body_para(s: &Session) -> &wordcraft_doc::Paragraph {
s.doc.para(wordcraft_doc::StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap()
}
@@ -925,6 +1067,71 @@ fn deleting_a_comment_deletes_replies_to_replies() {
assert_eq!(anchors(&s).len(), 2);
}
/// Resolving from the root, the caret or a nested reply changes the whole discussion in one
/// undo step. Reopening is also thread-wide, and unrelated discussions stay untouched.
#[test]
fn resolving_a_comment_changes_its_whole_thread() {
let mut s = Session::new(Document::from_text("first second"));
s.run("select.text", &json!({"text": "first"})).unwrap();
let root = s.run("review.newComment", &json!({"text": "root"})).unwrap()["id"].as_u64().unwrap();
let reply = s.run("review.reply", &json!({"id": root, "text": "reply"})).unwrap()["id"].as_u64().unwrap();
let nested = s.run("review.reply", &json!({"id": reply, "text": "nested"})).unwrap()["id"].as_u64().unwrap();
s.run("review.reply", &json!({"id": root, "text": "sibling"})).unwrap();
s.run("select.text", &json!({"text": "second"})).unwrap();
let other = s.run("review.newComment", &json!({"text": "other"})).unwrap()["id"].as_u64().unwrap() as u32;
s.run("select.text", &json!({"text": "first"})).unwrap();
let before = s.doc.comments.clone();
let body = s.doc.body.clone();
let parts = s.doc.parts.clone();
let depth = s.undo_depth();
let mut resolved = before.clone();
for (id, c) in &mut resolved {
c.resolved = *id != other;
}
for params in [json!({"id": root, "value": true}), json!({}), json!({"id": nested})] {
s.run("review.resolveComment", &params).unwrap();
assert_eq!(s.doc.comments, resolved, "{params}: all replies resolve, not the other discussion");
assert_eq!(s.undo_depth(), depth + 1, "one undo step for the whole thread");
s.run("review.resolveComment", &json!({"id": reply, "value": true})).unwrap();
assert_eq!(s.undo_depth(), depth + 1, "resolving an already resolved thread adds no step");
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc.comments, before, "one undo restores every comment");
s.run("edit.redo", &json!({})).unwrap();
assert_eq!(s.doc.comments, resolved);
s.run("review.resolveComment", &json!({"id": nested})).unwrap();
assert_eq!(s.doc.comments, before, "toggling a reply reopens the whole thread");
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc.comments, resolved);
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc.comments, before);
}
assert_eq!(s.doc.body, body, "resolution leaves the body and anchors alone");
assert_eq!(s.doc.parts, parts, "resolution leaves the comments' text alone");
}
/// Imported comments can have mixed resolved flags, missing parents or a parent cycle. A
/// thread operation reconciles the connected comments without following a missing parent.
#[test]
fn resolving_a_comment_handles_mixed_state_and_broken_parent_links() {
use wordcraft_doc::Comment;
for parent in [None, Some(99), Some(2)] {
let mut doc = Document::new();
doc.comments.insert(0, Comment { resolved: true, parent, ..Default::default() });
doc.comments.insert(1, Comment { parent: Some(0), ..Default::default() });
doc.comments.insert(2, Comment { parent: Some(1), ..Default::default() });
doc.comments.insert(3, Comment { parent: Some(99), ..Default::default() });
let mut s = Session::new(doc);
s.run("review.resolveComment", &json!({"id": 2})).unwrap();
assert!(
s.doc.comments.iter().all(|(id, c)| c.resolved == (*id != 3)),
"a reply's Resolve action must not reopen its resolved parent: {parent:?}"
);
s.run("review.resolveComment", &json!({"id": 1, "value": false})).unwrap();
assert!(s.doc.comments.values().all(|c| !c.resolved), "{parent:?}");
}
}
/// A parent cycle (possible in a hostile file) doesn't hang Delete; both comments go.
#[test]
fn deleting_a_comment_in_a_parent_cycle_ends() {
@@ -1950,3 +2157,288 @@ fn accept_and_reject_all_reach_fixed_point_with_buried_rev_in_invalid_outer_chan
assert_eq!(s.doc, after_first, "{cmd} mixed: second pass must be a no-op");
}
}
/// wordcraft#7207: a tracked merge or split of a cell (`w:cellMerge`) is listed as Word for Windows
/// lists it, keeps naming its revision when other changes are resolved, and accepting or rejecting
/// it drops only the record: the cells stay as they are.
#[test]
fn a_tracked_cell_merge_is_listed_and_resolved_as_word_does() {
use std::sync::Arc;
use wordcraft_doc::props::{CellMergeChange, MergeMark, VMerge};
use wordcraft_doc::table::Table;
use wordcraft_doc::{Block, Path, Pos, Revision, RevisionKind, StoryRef};
let merges = |s: &Session| -> Vec<Option<CellMergeChange>> {
let t = s.doc.body.iter().find_map(|b| b.as_table()).expect("table");
t.rows.iter().flat_map(|r| r.cells.iter().map(|c| c.props.merge_change)).collect()
};
for (accept, one, all) in [(true, "review.accept", "review.acceptAll"), (false, "review.reject", "review.rejectAll")] {
let mut d = Document::from_text("Intro\nafter");
d.revisions.push(Revision::new(RevisionKind::Insert, "Ada", ""));
d.revisions.push(Revision::new(RevisionKind::Format, "Reviewer", "2020-03-01T12:00:00Z"));
d.format_range(&Pos::body(0, 0), &Pos::body(0, 5), &|c| c.ins = Some(0)).unwrap();
let mut t = Table::new(2, 2, 288.0);
// The right column merged down: resolving the records leaves it so.
t.rows[0].cells[1].props.vmerge = VMerge::Restart;
t.rows[1].cells[1].props.vmerge = VMerge::Continue;
t.rows[1].cells[0].props.merge_change =
Some(CellMergeChange { rev: 1, v_merge: Some(MergeMark::Continue), v_merge_orig: Some(MergeMark::Restart) });
t.rows[1].cells[1].props.merge_change = Some(CellMergeChange { rev: 1, v_merge: None, v_merge_orig: Some(MergeMark::Continue) });
d.body.insert(1, Arc::new(Block::Table(t)));
let mut s = Session::new(d);
let list = s.run("review.changes", &json!({})).unwrap();
let cells: Vec<(String, String, String)> = list
.as_array()
.unwrap()
.iter()
.filter(|c| c["kind"].as_str().is_some_and(|k| k.starts_with("cell")))
.map(|c| (c["kind"].as_str().unwrap().into(), c["description"].as_str().unwrap_or("").into(), c["author"].as_str().unwrap_or("").into()))
.collect();
let want = |k: &str, d: &str| (k.to_string(), d.to_string(), "Reviewer".to_string());
assert_eq!(cells, [want("cellMerge", "Merged cells"), want("cellSplit", "Split cells")]);
// The insertion alone: the records still name the reviewer's revision.
s.sel = crate::Selection { anchor: Pos::body(0, 0), focus: Pos::body(0, 5) };
s.run(one, &json!({})).unwrap();
let named: Vec<Option<&str>> =
merges(&s).into_iter().flatten().map(|m| s.doc.revisions.get(m.rev as usize).map(|r| r.author.as_str())).collect();
assert_eq!(named, [Some("Reviewer"), Some("Reviewer")], "accept {accept}");
// The caret in the split cell: its record alone goes; the cells keep their merges.
let table = s.doc.body.iter().position(|b| b.as_table().is_some()).unwrap();
s.sel = crate::Selection::caret(Pos { story: StoryRef::Body, path: Path(vec![table as u32, 1, 1, 0]), off: 0 });
s.run(one, &json!({})).unwrap();
assert_eq!(merges(&s).iter().map(Option::is_some).collect::<Vec<_>>(), [false, false, true, false], "accept {accept}");
s.run(all, &json!({})).unwrap();
assert!(merges(&s).iter().all(Option::is_none));
let t = s.doc.body.iter().find_map(|b| b.as_table()).unwrap();
let vmerges: Vec<VMerge> = t.rows.iter().flat_map(|r| &r.cells).map(|c| c.props.vmerge).collect();
assert_eq!(vmerges, [VMerge::None, VMerge::Restart, VMerge::None, VMerge::Continue], "the cells stay as they are");
assert!(s.run("review.changes", &json!({})).unwrap().as_array().unwrap().is_empty());
assert!(s.doc.revisions.is_empty(), "{:?}", s.doc.revisions);
}
}
/// wordcraft#7207: pasted content keeps its tracked cell merges naming the revisions it brings.
#[test]
fn an_adopted_tracked_cell_merge_names_its_revision() {
use wordcraft_doc::props::{CellMergeChange, MergeMark};
use wordcraft_doc::table::Table;
use wordcraft_doc::{Block, Path, Revision, RevisionKind, StoryRef};
let mut ours = Document::from_text("ours");
ours.revisions.push(Revision::new(RevisionKind::Insert, "Ada", ""));
let mut theirs = Document::from_text("theirs");
theirs.revisions.push(Revision::new(RevisionKind::Format, "Reviewer", ""));
let mut t = Table::new(2, 1, 144.0);
t.rows[1].cells[0].props.merge_change = Some(CellMergeChange { rev: 0, v_merge: None, v_merge_orig: Some(MergeMark::Continue) });
// One naming a revision theirs doesn't have is dropped.
t.rows[0].cells[0].props.merge_change = Some(CellMergeChange { rev: 7, ..CellMergeChange::default() });
theirs.insert_block(StoryRef::Body, &Path::top(0), Block::Table(t)).unwrap();
let frag = ours.adopt(theirs);
let Some(Block::Table(t)) = frag.blocks.first() else { panic!("{:?}", frag.blocks) };
assert_eq!(t.rows[0].cells[0].props.merge_change, None);
let m = t.rows[1].cells[0].props.merge_change.expect("kept");
assert_eq!(m.v_merge_orig, Some(MergeMark::Continue));
assert_eq!(ours.revisions.get(m.rev as usize).map(|r| r.author.as_str()), Some("Reviewer"));
}
/// wordcraft#7207: a tracked cell merge Accept All leaves (in a table nested past the depth it
/// resolves) keeps naming its revision when the revisions are compacted.
#[test]
fn a_tracked_cell_merge_left_by_accept_all_keeps_its_revision() {
use std::sync::Arc;
use wordcraft_doc::props::{CellMergeChange, MergeMark};
use wordcraft_doc::table::Table;
use wordcraft_doc::{Block, Paragraph, Pos, Revision, RevisionKind};
let mut d = Document::from_text("Intro\nafter");
d.revisions.push(Revision::new(RevisionKind::Insert, "Ada", ""));
d.revisions.push(Revision::new(RevisionKind::Format, "Reviewer", ""));
d.format_range(&Pos::body(0, 0), &Pos::body(0, 5), &|c| c.ins = Some(0)).unwrap();
let mut t = Table::new(1, 1, 144.0);
t.rows[0].cells[0].props.merge_change = Some(CellMergeChange { rev: 1, v_merge: None, v_merge_orig: Some(MergeMark::Continue) });
// A formatting change whose properties before it hold a merge record too.
d.revisions.push(Revision::new(RevisionKind::Format, "Earlier", ""));
let old = wordcraft_doc::props::CellProps { merge_change: Some(CellMergeChange { rev: 2, ..CellMergeChange::default() }), ..Default::default() };
t.rows[0].cells[0].props.fmt_change = wordcraft_doc::props::PropChange::boxed(1, old);
for _ in 0..20 {
let mut outer = Table::new(1, 1, 144.0);
outer.rows[0].cells[0].blocks = vec![Arc::new(Block::Table(t)), Arc::new(Block::Para(Paragraph::new()))];
t = outer;
}
d.body.insert(1, Arc::new(Block::Table(t)));
let mut s = Session::new(d);
s.run("review.acceptAll", &json!({})).unwrap();
let mut t = s.doc.body.iter().find_map(|b| b.as_table()).unwrap();
while let Some(inner) = t.rows[0].cells[0].blocks.iter().find_map(|b| b.as_table()) {
t = inner;
}
let m = t.rows[0].cells[0].props.merge_change.expect("past the depth Accept All resolves");
assert_eq!(s.doc.revisions.get(m.rev as usize).map(|r| r.author.as_str()), Some("Reviewer"), "{:?}", s.doc.revisions);
let before = t.rows[0].cells[0].props.fmt_change.as_ref().and_then(|c| c.old.merge_change).expect("kept with the formatting change");
assert_eq!(s.doc.revisions.get(before.rev as usize).map(|r| r.author.as_str()), Some("Earlier"));
}
/// wordcraft#7207 review: Next Change on a cell's tracked split, where tracked text starts the
/// cell too, then Reject resolves the split, not the text. A cell that starts with a nested table
/// lists its tracked merge at its own first paragraph, which resolves it.
#[test]
fn a_navigated_cell_merge_is_the_one_resolved() {
use std::sync::Arc;
use wordcraft_doc::props::{CellMergeChange, MergeMark};
use wordcraft_doc::table::Table;
use wordcraft_doc::{Block, CharProps, Paragraph, Path, Pos, Revision, RevisionKind, StoryRef};
let mut d = Document::from_text("before\nafter");
d.revisions.push(Revision::new(RevisionKind::Insert, "Ada", ""));
d.revisions.push(Revision::new(RevisionKind::Format, "Reviewer", ""));
let mut t = Table::new(1, 2, 288.0);
t.rows[0].cells[0].props.merge_change = Some(CellMergeChange { rev: 1, v_merge: None, v_merge_orig: Some(MergeMark::Continue) });
t.rows[0].cells[0].blocks = vec![Arc::new(Block::Para(Paragraph::with_text("new", CharProps { ins: Some(0), ..Default::default() })))];
t.rows[0].cells[1].props.merge_change = Some(CellMergeChange { rev: 1, v_merge: Some(MergeMark::Continue), v_merge_orig: None });
t.rows[0].cells[1].blocks = vec![Arc::new(Block::Table(Table::new(1, 1, 100.0))), Arc::new(Block::Para(Paragraph::new()))];
d.body.insert(1, Arc::new(Block::Table(t)));
let mut s = Session::new(d);
let kinds = |s: &mut Session| -> Vec<String> {
let list = s.run("review.changes", &json!({})).unwrap();
list.as_array().unwrap().iter().map(|c| c["kind"].as_str().unwrap_or("").to_string()).collect()
};
// The inserted text and its paragraph mark are two insertions.
assert_eq!(kinds(&mut s), ["cellSplit", "insert", "insert", "cellMerge"]);
s.sel = crate::Selection::caret(Pos::body(0, 0));
s.run("review.nextChange", &json!({})).unwrap();
s.run("review.reject", &json!({})).unwrap();
assert_eq!(kinds(&mut s), ["insert", "insert", "cellMerge"], "the split's record went, the inserted text stays");
let t = s.doc.body.iter().find_map(|b| b.as_table()).unwrap();
assert_eq!(t.rows[0].cells[0].blocks[0].as_para().map(|p| p.plain_text()), Some("new".to_string()));
s.sel = crate::Selection::caret(Pos { story: StoryRef::Body, path: Path(vec![1, 0, 1, 1]), off: 0 });
s.run("review.accept", &json!({})).unwrap();
assert_eq!(kinds(&mut s), ["insert", "insert"]);
}
/// wordcraft#9768 review: a table's and its first cell's formatting changes from one revision share
/// the cell's start; Next Change steps from one to the other and on, without sticking.
#[test]
fn next_change_steps_through_changes_sharing_a_cells_start() {
use std::sync::Arc;
use wordcraft_doc::props::{CellProps, PropChange, TableProps};
use wordcraft_doc::table::Table;
use wordcraft_doc::{Block, Path, Pos, Revision, RevisionKind};
let mut d = Document::from_text("before\nafter");
d.revisions.push(Revision::new(RevisionKind::Insert, "Ada", ""));
d.revisions.push(Revision::new(RevisionKind::Format, "Reviewer", ""));
d.format_range(&Pos::body(1, 0), &Pos::body(1, 5), &|c| c.ins = Some(0)).unwrap();
let mut t = Table::new(1, 1, 144.0);
t.props.fmt_change = PropChange::boxed(1, TableProps::default());
t.rows[0].cells[0].props.fmt_change = PropChange::boxed(1, CellProps::default());
d.body.insert(1, Arc::new(Block::Table(t)));
let mut s = Session::new(d);
s.sel = crate::Selection::caret(Pos::body(0, 0));
let mut seen = Vec::new();
for _ in 0..3 {
s.run("review.nextChange", &json!({})).unwrap();
seen.push((s.sel.anchor.path.clone(), s.review_target.as_ref().and_then(|t| t.scope)));
}
use super::changes::Scope;
let cell = Path(vec![1, 0, 0, 0]);
assert_eq!(seen, [(cell.clone(), Some(Scope::Table)), (cell, Some(Scope::Cell)), (Path::top(2), None)]);
}
/// wordcraft#9768 review: Reject on a navigated tracked merge resolves that record alone, not the
/// cell's formatting change from another revision nor tracked text at the cell's start. A click
/// elsewhere and back ends the navigation: Reject then takes the text, as at any caret.
#[test]
fn a_navigated_merge_resolves_alone_until_a_click_elsewhere() {
use std::sync::Arc;
use wordcraft_doc::props::{CellMergeChange, CellProps, MergeMark, PropChange};
use wordcraft_doc::table::Table;
use wordcraft_doc::{Block, CharProps, Paragraph, Path, Pos, Revision, RevisionKind, StoryRef};
let doc = || {
let mut d = Document::from_text("before\nafter");
d.revisions.push(Revision::new(RevisionKind::Insert, "Ada", ""));
d.revisions.push(Revision::new(RevisionKind::Format, "Reviewer", ""));
d.revisions.push(Revision::new(RevisionKind::Format, "Formatter", ""));
let mut t = Table::new(1, 1, 144.0);
let cell = &mut t.rows[0].cells[0];
cell.props.fmt_change = PropChange::boxed(2, CellProps::default());
cell.props.merge_change = Some(CellMergeChange { rev: 1, v_merge: None, v_merge_orig: Some(MergeMark::Continue) });
cell.blocks = vec![Arc::new(Block::Para(Paragraph::with_text("new", CharProps { ins: Some(0), ..Default::default() })))];
d.body.insert(1, Arc::new(Block::Table(t)));
Session::new(d)
};
let cell_of = |s: &Session| s.doc.body.iter().find_map(|b| b.as_table()).map(|t| t.rows[0].cells[0].clone()).unwrap();
let start = Pos { story: StoryRef::Body, path: Path(vec![1, 0, 0, 0]), off: 0 };
let mut s = doc();
s.sel = crate::Selection::caret(Pos::body(0, 0));
// The cell's formatting change, then its merge.
s.run("review.nextChange", &json!({})).unwrap();
s.run("review.nextChange", &json!({})).unwrap();
s.run("review.reject", &json!({})).unwrap();
let cell = cell_of(&s);
assert!(cell.props.merge_change.is_none(), "the merge record went");
assert!(cell.props.fmt_change.is_some(), "the other revision's formatting stays");
assert_eq!(cell.blocks[0].as_para().map(|p| p.plain_text()), Some("new".to_string()), "the text stays");
let mut s = doc();
s.sel = crate::Selection::caret(Pos::body(0, 0));
s.run("review.nextChange", &json!({})).unwrap();
s.run("review.nextChange", &json!({})).unwrap();
s.set_selection(crate::Selection::caret(Pos::body(0, 2)));
s.set_selection(crate::Selection::caret(start));
s.run("review.reject", &json!({})).unwrap();
let cell = cell_of(&s);
assert!(cell.props.merge_change.is_some(), "no longer the navigated merge");
assert_eq!(cell.blocks[0].as_para().map(|p| p.plain_text()), Some(String::new()), "the tracked text at the caret was rejected");
}
/// #9768 review: a command that moves the selection away from a navigated cell change (Next
/// Comment here) ends it, as a click or caret command does; coming back to it is not navigating.
#[test]
fn a_selection_moving_command_ends_the_navigated_change() {
use std::sync::Arc;
use wordcraft_doc::props::{CellMergeChange, MergeMark};
use wordcraft_doc::table::Table;
use wordcraft_doc::{Block, Pos, Revision, RevisionKind};
let mut d = Document::from_text("before\nafter");
d.revisions.push(Revision::new(RevisionKind::Format, "Reviewer", ""));
let mut t = Table::new(1, 1, 144.0);
t.rows[0].cells[0].props.merge_change = Some(CellMergeChange { rev: 0, v_merge: None, v_merge_orig: Some(MergeMark::Continue) });
d.body.insert(1, Arc::new(Block::Table(t)));
let mut s = Session::new(d);
s.sel = crate::Selection { anchor: Pos::body(0, 0), focus: Pos::body(0, 6) };
s.run("review.newComment", &json!({"text": "A note."})).unwrap();
s.sel = crate::Selection::caret(Pos::body(0, 0));
s.run("review.nextChange", &json!({})).unwrap();
assert!(s.review_target.is_some(), "the merge is the navigated change");
s.run("review.nextComment", &json!({})).unwrap();
assert!(s.review_target.is_none(), "Next Comment moved the selection: {:?}", s.sel);
}
/// #9768 review: a cell's formatting change and its first run's, from one revision setting the
/// same property, stay two changes: the run's is not folded into the cell's.
#[test]
fn a_cells_and_its_first_runs_formatting_changes_stay_apart() {
use std::sync::Arc;
use wordcraft_doc::props::{CellProps, PropChange};
use wordcraft_doc::table::Table;
use wordcraft_doc::{Block, CharProps, Paragraph, Revision, RevisionKind, Rgb};
let mut d = Document::from_text("before\nafter");
d.revisions.push(Revision::new(RevisionKind::Format, "Reviewer", ""));
let shade = Some(Rgb(0xFF, 0xC0, 0));
let mut t = Table::new(1, 1, 144.0);
let cell = &mut t.rows[0].cells[0];
// The cell as it was differs only in its shading, as the run does.
let old = CellProps { ..cell.props.clone() };
cell.props.shading = shade;
cell.props.fmt_change = PropChange::boxed(0, old);
let run = CharProps { shading: shade, fmt_change: PropChange::boxed(0, CharProps::default()), ..Default::default() };
let mut p = Paragraph::with_text("Shaded", run);
p.mark = CharProps::default();
cell.blocks = vec![Arc::new(Block::Para(p))];
d.body.insert(1, Arc::new(Block::Table(t)));
let mut s = Session::new(d);
let list = s.run("review.changes", &json!({})).unwrap();
let formats = list.as_array().unwrap().iter().filter(|c| c["kind"] == "format").count();
assert_eq!(formats, 2, "{list}");
}
+1 -1
View File
@@ -1,7 +1,7 @@
use super::cells::{cell, cell_at, grid_cols, row_ends, selected_cells};
use super::{CmdError, CmdResult, Paragraph, Path, Pos, Selection, Session, StoryRef, Value, sel_result};
/// Ctrl+A in a table, as in Word: the cell, then its row, then the table. A nested table that
/// Explicit staged select-all in a table: the cell, then its row, then the table. A nested table that
/// is already fully selected grows to the cell around it. Returns `None` when the next step is
/// the whole story (not in a table, or the top-level table is already selected).
pub(crate) fn grow_select_all(s: &mut Session) -> Option<CmdResult> {
+4 -4
View File
@@ -630,10 +630,10 @@ fn room_right(l: &DocLayout, doc: &Document, page: usize, target: &ResizeTarget)
let Some(b) = boxes.iter().find(|b| b.story == target.story && b.table == outer && b.row == row && b.cell == cell) else {
return margin;
};
// A right-to-left table has its cells' start (left) margin on their right.
let m = wordcraft_layout::cell_margins(doc, t, row, cell);
let inset = if t.props.bidi_visual { m[1] } else { m[3] };
(b.rect.right() - inset).min(margin)
// A cell's right margin is on its right in a right-to-left table too, as the layout draws
// it (#6941): Word doesn't mirror cell margins.
let right_margin = wordcraft_layout::cell_margins(doc, t, row, cell)[3];
(b.rect.right() - right_margin).min(margin)
}
#[cfg(test)]
@@ -534,6 +534,46 @@ fn a_nested_tables_column_fits_within_its_cell() {
assert_eq!((host1.x, host1.w), (host.x, host.w), "the table around it keeps its columns");
}
/// #8441: a right-to-left table keeps its cells' right margins on their right (#6941), so a
/// nested table in such a cell fits up to that cell's right margin, not its left one, when the
/// two differ.
#[test]
fn a_nested_tables_column_fits_within_a_right_to_left_cell() {
let mut s = rtl_table_session(1, 2);
s.sel = Selection::caret(cell_pos(&s, 0, 0));
s.run("insert.table", &json!({"rows": 1, "cols": 2})).unwrap();
let (inner, _, _) = s.sel.focus.path.cell().unwrap();
let outer = table_path(&s);
// A left margin of 20 pt and a right one of 2 pt; the nested table itself left to right.
s.doc.table_mut(StoryRef::Body, &outer).unwrap().rows[0].cells[0].props.margins = Some([0.0, 20.0, 0.0, 2.0]);
s.doc.table_mut(StoryRef::Body, &inner).unwrap().props.bidi_visual = false;
s.touch();
let rect = |s: &mut Session, table: &Path, cell: usize| {
s.layout().pages[0]
.items
.iter()
.find_map(|it| match it {
Placed::Cell { rect, table: t, row: 0, cell: c, .. } if t == table && *c == cell => Some(*rect),
_ => None,
})
.unwrap()
};
for col in [1, 0] {
let r = rect(&mut s, &inner, col);
s.run("table.fitColumn", &json!({"page": 0, "x": r.right(), "y": mid_y(r)})).unwrap();
}
s.run("text.insert", &json!({"text": "word ".repeat(40)})).unwrap();
let host = rect(&mut s, &outer, 0);
let (a, b) = (rect(&mut s, &inner, 0), rect(&mut s, &inner, 1));
assert!(b.right() < host.right() - 40.0, "{b:?} in {host:?}");
s.run("table.fitColumn", &json!({"page": 0, "x": a.right(), "y": mid_y(a)})).unwrap();
let b1 = rect(&mut s, &inner, 1);
let text_right = host.right() - 2.0;
assert!((b1.right() - text_right).abs() < 0.5, "the table fills its cell's text up to its right margin: {b1:?}, {text_right}");
let host1 = rect(&mut s, &outer, 0);
assert_eq!((host1.x, host1.w), (host.x, host.w), "the table around it keeps its columns");
}
/// Pasting formatting onto a selected column leaves its text (it used to clear it).
#[test]
fn the_format_painter_keeps_a_selected_columns_text() {
+3 -3
View File
@@ -123,12 +123,12 @@ pub(super) fn insert(s: &mut Session, v: &Value) -> CmdResult {
s.push_undo("AutoFormat", doc, sel);
// Undo right after it makes the capitalised word an exception.
let depth = s.undo_steps_so_far();
if let Some(c) = s.autocap.as_mut().filter(|c| c.depth == u64::MAX) {
c.depth = depth;
if let Some(c) = s.autocap.as_mut() {
c.commit_depth(depth);
}
}
}
s.autocap.take_if(|c| c.depth == u64::MAX);
crate::cmd::tools::AutoCap::clear_uncommitted(&mut s.autocap);
s.set_ime_edit_outcome(outcome);
sel_result(s)
}
+26 -13
View File
@@ -87,22 +87,35 @@ fn backspace_inner(s: &mut Session, _: &Value) -> CmdResult {
}
if f.off > 0 {
let a = Pos { off: para.backspace_from(f.off), ..f.clone() };
if let Some(c) = s.autocap.as_mut() {
c.note_backspace(&a, &f);
}
let carried = deleted_char_props(s, &a, &f);
s.sel = Selection { anchor: a.clone(), focus: f };
let effect = delete_selection_effect(s)?;
s.set_ime_edit_outcome(crate::ImeEditOutcome {
classified: true,
content_changed: effect.content_changed,
state_changed: effect.state_changed,
transformed: false,
selection_changed: false,
});
let (content_changed, state_changed, transformed) = if let Some(start) =
s.autocap.as_ref().and_then(|c| c.pronoun_before_separator(&a, &f, s.undo_steps_so_far()))
&& matches!(para.text.get(start.off..f.off), Some("I " | "I," | "I." | "I;" | "I:" | "I!" | "I?"))
{
// This restores a letter in place. Ordinary typing over a selection removes its link.
let props = para.props_of_char(start.off);
let linked_letter = props.link.as_ref().map(|_| props.clone());
s.sel = Selection { anchor: start.clone(), focus: f.clone() };
let pending = std::mem::replace(&mut s.pending, linked_letter);
let effect = crate::cmd::type_text_effect(s, "i");
s.pending = pending;
let effect = effect?;
if let Some(c) = &mut s.autocap {
c.note_backspace(&start, &f);
}
(effect.content_changed, effect.state_changed, true)
} else {
if let Some(c) = s.autocap.as_mut() {
c.note_backspace(&a, &f);
}
s.sel = Selection { anchor: a.clone(), focus: f };
let effect = delete_selection_effect(s)?;
(effect.content_changed, effect.state_changed, false)
};
s.set_ime_edit_outcome(crate::ImeEditOutcome { classified: true, content_changed, state_changed, transformed, selection_changed: false });
// As in Word, text typed next takes the deleted character's formatting until the caret
// moves (#6518): it applies here only, so whatever puts the caret elsewhere drops it.
if effect.content_changed && s.sel.is_collapsed() && s.sel.focus == a {
if content_changed && s.sel.is_collapsed() && s.sel.focus == a {
s.pending_at = carried.as_ref().map(|_| a.clone());
s.pending = carried;
}
+17 -5
View File
@@ -145,7 +145,7 @@ fn enter(s: &mut Session, undo_step: bool) -> Result<(), CmdError> {
if let Some((doc, sel)) = plain {
// Removes the marks, then AutoCorrects the word as without them.
crate::cmd::tools::autocorrect_word(s, true)?;
s.autocap.take_if(|c| c.depth == u64::MAX);
crate::cmd::tools::AutoCap::clear_uncommitted(&mut s.autocap);
let (done_doc, done_sel) = (std::mem::replace(&mut s.doc, doc), std::mem::replace(&mut s.sel, sel));
let new = split_para(s, &at)?;
let c = s.doc.para_at(&new).map(|p| p.mark.clone()).unwrap_or_default();
@@ -165,7 +165,7 @@ fn enter(s: &mut Session, undo_step: bool) -> Result<(), CmdError> {
return Ok(());
}
crate::cmd::tools::autocorrect_word(s, true)?;
s.autocap.take_if(|c| c.depth == u64::MAX);
crate::cmd::tools::AutoCap::clear_uncommitted(&mut s.autocap);
at = s.sel.focus.clone();
}
let new = split_para(s, &at)?;
@@ -206,7 +206,11 @@ pub(super) fn tab(s: &mut Session, _: &Value) -> CmdResult {
&& n.num != 0
{
let para = s.doc.para_mut(f.story, &f.path)?;
para.props.numbering = Some(NumRef { num: n.num, level: n.level.saturating_add(1).min(8) });
let level = n.level.saturating_add(1).min(8);
para.props.numbering = Some(NumRef { num: n.num, level });
if level != n.level {
crate::cmd::para::drop_direct_indents(&mut para.props);
}
para.touch();
return sel_result(s);
}
@@ -255,7 +259,11 @@ fn indent_by_tab(s: &mut Session, f: &Pos) -> CmdResult {
&& let Some(n) = r.numbering.filter(|n| n.num != 0)
{
let p = s.doc.para_mut(f.story, &f.path)?;
p.props.numbering = Some(NumRef { num: n.num, level: n.level.saturating_add(1).min(8) });
let level = n.level.saturating_add(1).min(8);
p.props.numbering = Some(NumRef { num: n.num, level });
if level != n.level {
crate::cmd::para::drop_direct_indents(&mut p.props);
}
p.touch();
return sel_result(s);
}
@@ -288,7 +296,11 @@ pub(super) fn back_tab(s: &mut Session, _: &Value) -> CmdResult {
let f = s.sel.focus.clone();
if let Some(n) = s.doc.para_at(&f).and_then(|x| x.props.numbering).filter(|n| n.num != 0) {
let para = s.doc.para_mut(f.story, &f.path)?;
para.props.numbering = Some(NumRef { num: n.num, level: n.level.saturating_sub(1) });
let level = n.level.saturating_sub(1);
para.props.numbering = Some(NumRef { num: n.num, level });
if level != n.level {
crate::cmd::para::drop_direct_indents(&mut para.props);
}
para.touch();
return sel_result(s);
}
@@ -268,6 +268,16 @@ fn plain_word(w: &str) -> bool {
!w.trim().is_empty() && w.chars().count() <= MAX_FROM && !w.contains(|c: char| c.is_whitespace() || c == '\u{FFFC}')
}
#[derive(Clone, Debug)]
pub(super) struct PronounCap {
depth: u64,
story: wordcraft_doc::StoryRef,
path: wordcraft_doc::Path,
start: usize,
caret: usize,
backspaced: bool,
}
/// The newest automatic capitalisation (a sentence capital, a TWo INitial CApitals fix), kept so
/// that undoing it, or backspacing it and typing the word again, makes an exception (#1857).
#[derive(Clone, Debug)]
@@ -283,11 +293,78 @@ pub struct AutoCap {
pub(super) prev: String,
/// The TWo INitial CApitals word as typed ("TWo").
pub(super) two_caps: Option<String>,
/// The English replacement of lowercase i with uppercase I, kept alongside an earlier sentence
/// capital so an automatic `I` does not wipe the pending first-letter exception.
pub(super) pronoun: Option<PronounCap>,
/// The user backspaced into the word after the change.
pub(super) backspaced: bool,
}
impl AutoCap {
pub(crate) fn commit_depth(&mut self, depth: u64) {
if self.depth == u64::MAX {
self.depth = depth;
}
if let Some(p) = self.pronoun.as_mut().filter(|p| p.depth == u64::MAX) {
p.depth = depth;
}
}
pub(crate) fn clear_uncommitted(slot: &mut Option<Self>) {
if let Some(c) = slot.as_mut() {
if c.pronoun.as_ref().is_some_and(|p| p.depth == u64::MAX) {
c.pronoun = None;
}
if c.depth == u64::MAX {
*slot = None;
}
}
}
pub(super) fn record_pronoun(slot: &mut Option<Self>, story: wordcraft_doc::StoryRef, path: wordcraft_doc::Path, start: usize, caret: usize) {
let pronoun = PronounCap { depth: u64::MAX, story, path: path.clone(), start, caret, backspaced: false };
if let Some(c) = slot.as_mut().filter(|c| !c.prev.is_empty() || c.two_caps.is_some()) {
c.pronoun = Some(pronoun);
} else {
*slot =
Some(Self { depth: u64::MAX, story, path, start, prev: String::new(), two_caps: None, pronoun: Some(pronoun), backspaced: false });
}
}
pub(super) fn take_backspaced_pronoun(slot: &mut Option<Self>, english: bool, word: &str, f: &Pos, start: usize) -> bool {
let Some(c) = slot.as_mut() else { return false };
let Some(p) = c.pronoun.take() else { return false };
if c.prev.is_empty() && c.two_caps.is_none() {
*slot = None;
}
english && word == "i" && p.backspaced && p.story == f.story && p.path == f.path && p.start == start
}
/// The start of a just-corrected I when Backspace removes the separator after it.
pub(crate) fn pronoun_before_separator(&self, a: &Pos, f: &Pos, undo_steps: u64) -> Option<Pos> {
let p = self.pronoun.as_ref()?;
(!p.backspaced
&& p.story == f.story
&& p.path == f.path
&& p.start.checked_add(1) == Some(a.off)
&& p.depth.checked_add(1) == Some(undo_steps))
.then(|| Pos { off: p.start, ..f.clone() })
}
/// Drop the pending pronoun restore once the caret moves away or a selection is made (#9392).
pub(crate) fn drop_stale_pronoun(&mut self, sel: &crate::Selection) {
if let Some(p) = &self.pronoun
&& !p.backspaced
&& (!sel.is_collapsed() || sel.focus.story != p.story || sel.focus.path != p.path || sel.focus.off != p.caret)
{
self.pronoun = None;
}
}
pub(crate) fn is_empty(&self) -> bool {
self.prev.is_empty() && self.two_caps.is_none() && self.pronoun.is_none()
}
pub(crate) fn add_exceptions(self, ac: &mut AutoCorrectPrefs) {
if ac.auto_add_first_letter && !self.prev.is_empty() {
ac.add_exception(self.prev);
@@ -304,6 +381,14 @@ impl AutoCap {
if f.story == self.story && f.path == self.path && a.off <= self.start && f.off > self.start {
self.backspaced = true;
}
if let Some(p) = &mut self.pronoun
&& f.story == p.story
&& f.path == p.path
&& a.off <= p.start
&& f.off > p.start
{
p.backspaced = true;
}
}
}
+21 -9
View File
@@ -260,12 +260,12 @@ fn diff_notes(
}
for &new_id in &notes.inserted {
if let Some(part) = doc.parts.get_mut(&new_id) {
part.blocks = part.blocks.iter().map(|b| Arc::new(mark_block(b, &|c| c.ins = Some(ctx.ins)))).collect();
part.blocks = part.blocks.iter().map(|b| Arc::new(mark_block(b, &|c| c.ins = Some(ctx.ins), &|_| {}))).collect();
}
}
for &orig_id in &notes.deleted {
if let Some(part) = doc.parts.get_mut(&orig_id) {
part.blocks = part.blocks.iter().map(|b| Arc::new(mark_block(b, &|c| c.del = Some(ctx.del)))).collect();
part.blocks = part.blocks.iter().map(|b| Arc::new(mark_block(b, &|c| c.del = Some(ctx.del), &|_| {}))).collect();
}
}
}
@@ -311,6 +311,7 @@ fn strip_block_revisions(b: &mut Block) {
}
for cell in &mut row.cells {
cell.props.fmt_change = None;
cell.props.merge_change = None;
stack.extend(cell.blocks.iter_mut().map(Arc::make_mut));
}
}
@@ -443,14 +444,18 @@ fn diff_blocks(doc: &mut Document, old: &[Arc<Block>], new: &[Arc<Block>], ctx:
(Some(Block::Para(pa)), Some(Block::Para(pb))) => out.push(para_block(word_diff(doc, pa, pb, ctx))),
_ => {
if let Some(x) = a {
out.push(Arc::new(mark_block(x, &|c| {
// An existing deletion is another author's: keep their revision
// stamp instead of re-attributing the paragraph to this compare.
c.del.get_or_insert(ctx.del);
})));
out.push(Arc::new(mark_block(
x,
&|c| {
// An existing deletion is another author's: keep their revision
// stamp instead of re-attributing the paragraph to this compare.
c.del.get_or_insert(ctx.del);
},
&|_| {},
)));
}
if let Some(x) = b {
out.push(Arc::new(mark_block(x, &|c| c.ins = Some(ctx.ins))));
out.push(Arc::new(mark_block(x, &|c| c.ins = Some(ctx.ins), &|c| c.del = None)));
}
}
}
@@ -1627,7 +1632,13 @@ fn block_text(b: &Block, depth: usize) -> String {
/// where the paragraph carries a section break or is the container's only paragraph. A
/// non-terminal section-carrying paragraph is removed whole too: `resolve_para` removes the
/// section break first (#5734, issue #5667), so the following paragraph keeps its own properties.
fn mark_block(b: &Block, f: &dyn Fn(&mut CharProps)) -> Block {
///
/// `mark` additionally updates each paragraph mark. A whole inserted block keeps only the
/// compare's insertion on its mark: a `del` the revised document's mark already carried (a pending
/// deletion by another author) must not survive next to the compare's `ins` — on accept the
/// deletion branch would resolve the inserted paragraph away (#6899). Run-level revisions of the
/// source block are left alone.
fn mark_block(b: &Block, f: &dyn Fn(&mut CharProps), mark: &dyn Fn(&mut CharProps)) -> Block {
let mut out = b.clone();
let mut todo = vec![&mut out];
while let Some(blk) = todo.pop() {
@@ -1636,6 +1647,7 @@ fn mark_block(b: &Block, f: &dyn Fn(&mut CharProps)) -> Block {
let len = p.len();
let _ = p.format(0, len, f);
f(&mut p.mark);
mark(&mut p.mark);
p.touch();
}
Block::Table(t) => {

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