Compare commits

..
Author SHA1 Message Date
skylartaylor 3ffbe57ebe Consume texture deltas in owner-picker test passes 2026-12-03 19:20:09 +01:00
skylartaylor 551463ca51 Deliver cancellation to a superseded PathRow ticket 2026-12-03 18:59:30 +01:00
skylartaylor bd69ff6e73 Pin the frozen private native viewport hook for qualification 2026-12-03 18:51:26 +01:00
skylartaylor c867a329be Merge commit '72ef3083e7e47eea6b314bb50a4269bcf7e67380' into private/wordcraft-windowless-desktop-host 2026-12-03 18:40:45 +01:00
skylartaylor ba68b13b19 Exercise guard Save As with an untitled third document 2026-12-03 18:38:24 +01:00
skylartaylor b0fd8cbfe9 Launch nothing once quit is decided, and let a quit prompt's Save As replace its window's queued pick
A clean quit replayed inside a pump set quit_requested and the same pump could launch a queued dialog; launches now stop once quit is decided. A dirty window that owns the quit prompt could not get its Save As because its own queued, unlaunched pick held the window's slot; that Save As now supersedes exactly such a pick (same window and document, nothing launched or answered), quietly, and everything else stays Busy. No build run.
2026-12-03 18:37:04 +01:00
skylartaylor c6bceddb93 Launch no queued system dialog while a quit waits or asks, except its own Save As
A queued pick could launch in the pass where the dialogs a deferred quit waited for answered. Launches now pause while a quit is deferred or its unsaved-changes guard runs, except the Save As its prompt asks for, and a quit whose dialogs have ended is replayed before the launch loop. No build run.
2026-12-03 18:33:31 +01:00
skylartaylor 5a71494219 Honor a final quit before pumping document pickers 2026-12-03 18:32:29 +01:00
skylartaylor b2adf0f456 Close a retired pick's chooser and Replace question on its window wherever it is retired
Quiescing removed picks without closing the in-app chooser or Replace question they had opened on their window, leaving one on screen that nothing answers. Every retirement now closes exactly those instances first, and give-up refuses while a Replace question shows. No build run.
2026-12-03 18:30:39 +01:00
skylartaylor 255309155b Route PathRow's own picks to the window and dialog that file them in the windowless trial
Compare/Combine, Templates and Add-ins and the Organizer browse through the SDK PathRow, which files its pick on the Env host's file service and keeps the ticket in its row, bypassing ask_file. In the windowless trial the frame host now carries an app-owned Files wrapper (file_dialogs/path_rows.rs) over the app's own host.

A pick is bound when it is filed. It binds to the drawn window's draw scope: logical window, its document, and the exact native window (viewport, mount attempt, incarnation) from the injected lookup. It also binds to the dialog opening running it: overlay::running_dialog, at that opening's serial, read right before the window's dialog run. Every dialog the run shows is open before it starts. A pick from a dialog that cannot be told apart opens nothing.

Staged picks join the owned route through push_owned_pick, the one admission point, after the owner's drawing. The admission rechecks the window, document, native window and opening first. The system dialog launches only on the pinned native window under its lease, one pick per window.

The settled answer is posted under the row's exact ticket. It is read only from a drawing of the same window, document, native window and dialog opening; a row reading it after a detach, recreation or reopen gets nothing. A pick whose window, document, native window or opening goes first is cancelled and posts nothing. Undelivered answers are pruned and bounded per window. A pick filed outside any window's drawing answers Cancelled and opens nothing. Every other file-service call forwards to the app's host, and outside the trial the frame host is unchanged.

Only rustfmt ran; no build or test run here.
2026-12-03 18:29:54 +01:00
skylartaylor daa74a4fda Count admission across the whole pass, defer File Close before its prompt, never cancel a launched system dialog, and quiesce picks at exit
Admission walks the picks in place so the bound of two counts every live and settling dialog. User File Close and every quit path (including the updater) defer before any Save Changes prompt; a deferred close keeps the document it was for. Cancelled picks no longer forget a launched dialog: it finishes as the user answers it, its answer is dropped and its parent lease is held until then, and retired dialogs keep their window for close deferral. quiesce_native_file_panels stops admission and launches at exit and drops unlaunched picks unpumped while launched ones drain. No build run.
2026-12-03 18:29:54 +01:00
skylartaylor ec687a6876 Rename the owner-document predicate so it does not clash with window_shows 2026-12-03 18:29:54 +01:00
skylartaylor 1e2e0cf217 Quiesce windowless picker launches before root shutdown 2026-12-03 18:23:59 +01:00
skylartaylor ba01027379 Pin windowless picks to their exact native window and wait for system dialogs before close and quit
Address ROUTER-REVIEW: an injected read-only NativeWindowLookup pins an attached owner at the gesture (a mounting owner binds once, on its first attachment) and the pin is checked again at every pump and at answer consumption. Native admission is bounded at two operations counting cancelled ones that are still settling; retiring schedules its first drain. Quit and an owner window's Close or File Close are recorded while a system dialog may still use a window, and replayed once through the usual guards. Cancelled Picture and Recipients picks clear only their own window's pending state. Tests reworked; no build run.
2026-12-03 18:20:13 +01:00
skylartaylor 61953d5fa9 Expose exact document attachment identity to picker ownership 2026-12-03 18:17:17 +01:00
skylartaylor ae35ca4fd8 Lease exact native picker parent windows in the desktop host 2026-12-03 18:08:53 +01:00
skylartaylor c7d2d85a86 Start WordCraft windowless by default, with one windowed fallback
The windowless root is now the default. WORDCRAFT_WINDOWLESS_TRIAL=0
(exactly 0) rolls back to a windowed root.

A start that winit will open on X11 or XWayland (forced by the existing
display-server policy, or unforced with no Wayland display) starts
windowed and is never retried. Otherwise, when eframe's windowless
bootstrap returns UnsupportedConfiguration before the app creator has
taken the one-shot startup inputs, the app starts once more with normal
windowed options and hooks. That retry reuses the thread's cached event
loop (run_and_return). Every other error, a second refusal, and any
error after the creator started are returned unchanged.

Not compiled or run here: the focused test build was stopped for host
load and is waiting for admission through the managed lane.
2026-12-03 18:07:11 +01:00
skylartaylor 7c74a5fa93 Bind windowless file picks to their window and launch system dialogs on its live native window
Every windowless-trial pick (Save As, close Save As, template, Export, Print to PDF, Open, Picture, Recipients, Font, Sources) is bound at ask time to the asking window and its document, in an app-wide list that window swaps do not move. A private file service per pick launches the system dialog only with that window's exact live native window (viewport, mount attempt, host incarnation) as parent, and holds a parent lease until the panel answers or its forgotten panel settles. The in-app chooser is used when preferred, when the panel reports Unavailable, when the host has no window lookup, or after a bounded number of scheduled passes with the native window missing. Stale owners cancel only their own pick; quit waits for open system dialogs. No build run here.
2026-12-03 18:04:42 +01:00
skylartaylor 89e336f645 Keep trial chooser history app-wide during window swaps 2026-12-03 17:44:15 +01:00
skylartaylor 18c7cfd8d6 Trial the qualified fallible document window SDK privately 2026-12-03 17:25:44 +01:00
skylartaylor 8670496a46 Merge commit 'c013dff3326543595d6b679be83901d1739720b7' into private/wordcraft-windowless-four-fixes 2026-12-03 17:25:12 +01:00
skylartaylor 2895ab88d4 Cancel only the parked document’s Save As chooser 2026-12-03 17:25:12 +01:00
skylartaylor 5288ef3255 Dispose texture output in the rejection test renderer 2026-12-03 17:24:55 +01:00
skylartaylor 8527081bc2 Keep WordCraft open when a trial document surface is rejected
Use the additive fallible DocumentWindow mount in the windowless trial and preserve the ordinary mount. Park rejected declarations, retain their drafts, and leave the survivor available until an inaccessible draft can be reopened.
2026-12-03 17:24:55 +01:00
skylartaylor 342931078a Expose close guard cancellation to viewport recovery 2026-12-03 17:10:04 +01:00
skylartaylor 6c47d77c19 Cancel Save As when its windowless surface is rejected 2026-12-03 17:09:37 +01:00
skylartaylor 0eed1a0d15 Track the exact windowless Save As Replace opening 2026-12-03 17:09:17 +01:00
skylartaylor 820742d5dc Scope windowless Save As to its document chooser 2026-12-03 17:05:48 +01:00
skylartaylor 5cc4702ca8 Fix file intake for windowless document drops 2026-12-03 16:52:17 +01:00
skylartaylor 1f73bb9486 Require a registered windowless target for automation effects 2026-12-03 16:49:37 +01:00
skylartaylor 017af2f3f9 Pin the landed windowless egui and winit revisions 2026-12-03 16:15:05 +01:00
skylartaylor 72afcbd32d Stage WordCraft windowless adoption pending landed dependencies 2026-12-03 16:14:12 +01:00
autocraft-bot[bot] 72ef3083e7 Merge pull request #8210
With AutoCraft's conflict resolution d24d3034.
2026-12-03 15:10:05 +00:00
autocraft-bot[bot] 27672b2448 Merge pull request #4614
With AutoCraft's conflict resolution 7c41404c.
2026-12-03 15:10:05 +00:00
autocraft-bot[bot] 67d5297c08 Merge pull request #8599 2026-12-03 15:10:05 +00:00
Mat Strange 4c1dfa6367 Say what Ctrl+K does with a column selection
The doc said the link lands at the block's top-left corner; it says now
that insert.link inserts the link text there and leaves the block's own
text unlinked, which is what the command does (#8602).

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

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

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

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

* validate: delimit the measured DrawingML coordinate evidence

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

Resolved the only conflict, in crates/layout/src/tests.rs, by keeping the PR's a_body_text_frame_respects_its_anchors test together with main's env_hash_memoizes_styles_and_invalidates_on_change and evict_unused_caps_stale_entries_across_repeated_edits tests, and closing the first test's brace. No conflict markers remain and cargo fmt --check is clean. I ran two of the three tests and both pass; I did not run the third (evict_unused_caps_stale_entries_across_repeated_edits) or the rest of the layout suite.
2026-12-03 01:41:20 +00:00
batistalucasv 1a05479d99 fix(keys): use fired modifiers for paste-format fallback across windows 2026-12-02 22:28:50 -03:00
batistalucasv fc0acd93b9 fix(keys): preserve paste suppression order and Mod+Shift+V origin 2026-12-02 22:28:50 -03:00
batistalucasv 5c2e7eb296 fix(keys): ignore paired browser paste after Mod+Shift+V (#7608) 2026-12-02 22:28:50 -03:00
batistalucasv cc7f9e2688 test(keys): restore the_ignored_paste_event_never_reaches_an_open_equation test (#7317) 2026-12-02 22:27:11 -03:00
Lucas Batista Vargas d885a9d997 perf(fonts,render): bound FontDb outline caches and prune/LRU media and color-glyph caches (#7900) (#7910) 2026-12-03 01:20:17 +00:00
autocraft-bot[bot] a67df42aa8 Merge pull request #8410 2026-12-03 01:20:17 +00:00
autocraft-bot[bot] 27dea96335 Merge pull request #8345
With AutoCraft's conflict resolution 2b524486.
2026-12-03 01:20:17 +00:00
autocraft-bot[bot] 1fd3163fcc Merge pull request #6642
With AutoCraft's conflict resolution 99c893f6.
2026-12-03 01:20:17 +00:00
autocraft-bot[bot] 3c5aeef936 Merge pull request #6732 2026-12-03 01:20:17 +00:00
autocraft-bot[bot] b29d85119e Merge pull request #8426 2026-12-03 01:20:17 +00:00
autocraft-bot[bot] 4158ed794d Merge pull request #8282 2026-12-03 01:20:17 +00:00
autocraft-bot[bot] b5b6300036 Merge pull request #8408 2026-12-03 01:20:17 +00:00
autocraft-bot[bot] 4fcdd74b9f Merge pull request #8402 2026-12-03 01:20:17 +00:00
autocraft-bot[bot] bcf2aa3b03 The formats crate's tests failed to compile on merged main: main's craft
The formats crate's tests failed to compile on merged main: main's craft-libs update (rev d73e274) puts craft_ods::testing behind craft-ods's test-support feature, and nothing enables it. The tests in crates/formats/src/sheet.rs now use a small local spreadsheet() helper that builds the same .ods package with craft_odf::PackageWriter (craft-odf is already a normal dependency); no dependency or Cargo.toml change, and no test or assertion weakened. cargo test -p wordcraft-formats sheet passes (9 tests), clippy -p wordcraft-formats --all-targets -D warnings is clean, and rustfmt --check on sheet.rs is clean. The CI logs were empty, so I did not run the Print job's own commands (cargo test and clippy on wordcraft and wordcraft-ui-egui), and the Print failure may have another cause.
2026-12-03 01:08:48 +00:00
Lucas Batista Vargas 9dad9fca5f perf(engine,apps): set Linux glibc MALLOC_TRIM_THRESHOLD_ on startup (#7904) (#7914) 2026-12-03 00:52:49 +00:00
codeiouandClaude Opus 5.5 1bd422a454 Ribbon: 24-point small buttons and no empty bands over group titles (#4017) (#8009)
* Ribbon: 24-point small buttons, and Home's Font and Paragraph rows spread over the ribbon's height (#4017)

Small rows were 20 points (`RibbonLook::row`), so icon buttons were 20-point squares packed edge to
edge, under the 24-point least target of the accessibility standard. Font and Paragraph packed their
two rows at the top of a three-row body, leaving an empty band over their titles. Rows are now 24
points, and `two_rows` spreads the two rows with equal room above, between and below them. The idea
of spreading the rows is Qulierm's, from #1751.

A gallery is as tall as its tiles or its column of three scroll buttons, and its tiles take that
height, so `gallery_rows` keeps the four in-ribbon galleries' columns at the old 20-point rows;
otherwise Table Styles' 3:2 tiles would stretch to 80 × 72 points.

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

* Ribbon: small icons at the size the icon set is drawn at, 20 points (#988)

The icons are drawn on a 20 × 20 grid (`icons/*.svg`) but the ribbon painted its small ones at 17
points, shrunk to 85 %, so they were small and a little soft beside the font box.

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

* Ribbon: large buttons as tall as the three rows, and no band over Layout › Paragraph or the galleries (#4017)

With 24-point rows the ribbon's body is 76 points, taller than a large button (a 32-point icon over two
reserved 16-point label lines, with its padding, 72), so a one-line label such as Dictate or Editor gained 4 points of empty
space under it. Large icons at 36 make large buttons 76 points, as tall as the three small rows, so every
label sits as far above its title as before.

Layout › Paragraph's Indent and Spacing headings now take the first small row and its four fields, 24
points high, the other two, so the fields line up with Page Setup's small buttons instead of leaving a band
under them. Galleries whose tiles would stretch out of shape (Style Sets, Table Styles, Equation ›
Symbols) keep their 20-point column of scroll buttons and sit in the middle of the body; Home's Styles
gallery, whose captioned tiles can grow, takes the body's height.

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

* Ribbon: field groups on the ribbon's grid (#4017)

Shape Format › Size and Chart Design and Diagram Design › Size hold two rows of fields and nothing else,
which sat at the top of the body with the third row's room empty over their titles (4 points more since
the rows grew). They now spread their two rows over the body as Home's Font and Paragraph do
(`two_rows`). Table Layout › Cell Size's Height and Width fields were 20 points beside 24-point
Distribute Rows and Distribute Columns, so their rows didn't line up; they are now as tall as the small
buttons, as every other field in the ribbon is.

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

* Ribbon: Diagram Design › Layouts as an in-ribbon gallery (#4017)

The Layouts group showed the layout picker's menu grid in the ribbon: all eight layouts in two rows of
large cards, which made the tab's ribbon 284 points tall on our renders, where Home's is 84. It is
now a ribbon gallery, as Design › Style Sets is: one row of previews in the layouts' 46:31 shape, the
scroll buttons and More, which opens every layout. The previews are drawn as before.

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

* Revert "Ribbon: small icons at the size the icon set is drawn at, 20 points (#988)"

The icon size goes to a pull request of its own (one issue per PR). Small icons are 17 points
again; large icons stay 36, so large buttons keep the three rows' height.

This reverts commit 2e3a0de401.

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

* Ribbon: say where the gallery rows' 20 points should come from

gallery_rows keeps the old ribbon's 20-point rows so a gallery's column of three scroll buttons fits its
60-point height, and centres the gallery on that assumption. A lean: comment points at the
craft-libs issue for taking both from the framework.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 00:52:43 +00:00
Terra854 0a7bf74427 Keep close prompts bound to their document windows (#8277)
* fix(ui): bind close prompts to their document windows

* fix(ui): report stale close cancellation without pending state
2026-12-03 00:52:37 +00:00
f3d88f5da3 perf(layout,ui-egui): memoize env_hash, drop debug page keys, and reuse Arc<Document> in WordPages (#7901) (#7911)
Co-authored-by: Martin Ball <martin.ball@ucscaregroup.co.uk>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 00:38:09 +00:00
autocraft-bot[bot] 87d5e537e2 In resolve_all (crates/engine/src/cmd/review/changes.rs), a paragraph is
In resolve_all (crates/engine/src/cmd/review/changes.rs), a paragraph is now trailing only when no block follows it in its container, instead of using !has_next_para, which is also true before a table. An empty revision paragraph between two tables is therefore not removed, and its mark is just cleared. I added the test reject_all_keeps_an_empty_inserted_paragraph_between_tables in crates/engine/src/cmd/tools/tests.rs, covering table, empty inserted paragraph, table, paragraph. fmt --check passed and clippy finished without errors. The engine compare tests were still running when the workspace backend dropped, so their result is unconfirmed.
2026-12-03 00:35:54 +00:00
autocraft-bot[bot] 175d2eabe6 The new test failed only on the merge with main. The test opened the Bul
The new test failed only on the merge with main. The test opened the Bullets menu by clicking the last button labelled exactly "Bullets". Main now names the split button's arrow "Bullets options", and `bullets_dropdown_renders_compact_bullet_tiles` already uses that name. So the click hit a different node, the menu never opened, and the assertion "Bullets shows ○" at tests.rs:967 failed. The font change itself was fine. I changed the test's lookup to "Bullets options" and updated its comment. Every assertion is unchanged. The test passes now. `cargo fmt --check` and `cargo clippy -p wordcraft-ui-egui --all-targets -- -D warnings` are clean. I did not run the rest of the ui-egui suite. I also removed the debug printing an earlier session had added.
2026-12-02 23:08:16 +00:00
David MannandClaude Opus 5.5 585cc90953 packaging(macos): ship wordcraft-cli inside WordCraft.app
ArtCraft Launcher offers an app to AI agents only when it finds <app>-cli
beside the app's executable, and wordcraft-cli mcp opens the app from there.
The stable bundle had only the app; the CLI zip still ships it on its own.
Part of #8415.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 23:12:23 +01:00
autocraft-bot[bot] 53cd405269 Part 1: tracked-changes protection now refuses review.acceptAndNext an
Part 1: tracked-changes protection now refuses `review.acceptAndNext` and `review.rejectAndNext`. I added both IDs to the `tracked` list in `greyed_out` in `crates/engine/src/cmd/protect.rs`. I also added both IDs to the command loop in `tracked_changes_protection_keeps_revisions` in `crates/engine/src/cmd/protect/tests.rs`, so the test requires them to be refused and the document to stay unchanged. `cargo fmt --check` and `cargo clippy --all-targets` are clean for `wordcraft-engine`. The `protect` lib tests (55) and `review` lib tests (58) pass. I did not run the engine crate's full test suite.
2026-12-02 21:56:14 +00:00
autocraft-bot[bot] 5991c5b7e4 Merge pull request #8409 2026-12-02 20:56:44 +00:00
autocraft-bot[bot] 7d0a1f897b Merge pull request #8371 2026-12-02 20:56:44 +00:00
autocraft-bot[bot] f1c93ad7c7 Merge pull request #8279 2026-12-02 20:56:44 +00:00
Martin Ball c17448f4d5 Merge remote-tracking branch 'origin/main' into HEAD 2026-12-02 20:56:44 +00:00
Lucas Batista Vargas 2f16864552 perf(render,layout): reuse render spares, shed oversized buffers, and cap LayoutCache (#7899) (#7909)
* perf(render,layout): reuse single-threaded spares, shed oversized buffers, and bound LayoutCache (#7899)

* perf(render): cap ContextPool spare count at 2 across all platforms

* perf(render,layout): address review feedback on ContextPool threshold and cache eviction test
2026-12-02 20:54:13 +00:00
autocraft-bot[bot] 902838c7b8 Merge pull request #6459 2026-12-02 20:54:13 +00:00
autocraft-bot[bot] 395eb4d8ff Merge pull request #8333 2026-12-02 20:54:13 +00:00
autocraft-bot[bot] b8535745a0 Merge pull request #6997 2026-12-02 20:54:13 +00:00
autocraft-bot[bot] e5bc372a0c Merge pull request #6091
With AutoCraft's conflict resolution 62c7baee.
2026-12-02 20:54:13 +00:00
autocraft-bot[bot] 16c803ecfd Merge pull request #6941
With AutoCraft's conflict resolution be5ef437.
2026-12-02 20:54:13 +00:00
autocraft-bot[bot] 206ed0fcd4 Merge pull request #6528 2026-12-02 20:54:13 +00:00
autocraft-bot[bot] 7220765c02 Merge pull request #8341 2026-12-02 20:54:13 +00:00
autocraft-bot[bot] 257bdec953 Merge pull request #8337 2026-12-02 20:54:13 +00:00
autocraft-bot[bot] ed757d0cdf Merge pull request #8322 2026-12-02 20:54:13 +00:00
autocraft-bot[bot] 1ab6d78010 Merge pull request #8271 2026-12-02 20:54:13 +00:00
autocraft-bot[bot] 7c6fbc0681 Merge pull request #7667 2026-12-02 20:54:13 +00:00
autocraft-bot[bot] 3afd70cf3d Merge pull request #7875 2026-12-02 20:54:13 +00:00
autocraft-bot[bot] b741bbac9a Merge pull request #3503 2026-12-02 20:54:13 +00:00
autocraft-bot[bot] fd948e2015 Merge pull request #8260 2026-12-02 20:54:13 +00:00
autocraft-bot[bot] 612e92e6c5 Merge pull request #8219 2026-12-02 20:54:13 +00:00
autocraft-bot[bot] 5ae937d8e3 Merge pull request #8216 2026-12-02 20:54:13 +00:00
autocraft-bot[bot] c07395d712 Merge pull request #8188 2026-12-02 20:54:13 +00:00
Lucas Batista Vargas 1b9b8b1bf3 perf(ui-egui): cache PageView body ranges per DocLayout in CanvasState (#8194) (#8222) 2026-12-02 20:54:07 +00:00
Lucas Batista Vargas ea5d48b18c perf(engine): drop stale-revision DocLayout from Session::layout cache (#8148) (#8149) 2026-12-02 20:54:02 +00:00
ZaxaerithandZaxaerith 03b54b043f fix(ui): remove duplicate default-app caption (#8285) (#8330)
Co-authored-by: Zaxaerith <189452125+Zaxaerith@users.noreply.github.com>
2026-12-02 20:53:56 +00:00
Zaxaerith e2588d8d35 test(widgets): verify recent fonts return after clearing search 2026-12-03 04:45:19 +08:00
Zaxaerith 026803c4bf fix(engine): make the typing PNG fixture available on wasm32 2026-12-03 04:42:34 +08:00
Zaxaerith 51ba3b8382 fix(options): explain software-disabled animations correctly 2026-12-03 04:26:29 +08:00
autocraft-bot[bot] 48e07fbcd1 Merge pull request #7930 2026-12-02 19:42:36 +00:00
autocraft-bot[bot] 72e54545d8 Merge pull request #8121 2026-12-02 19:42:36 +00:00
autocraft-bot[bot] 28d2dac6fd Merge pull request #7908 2026-12-02 19:42:36 +00:00
Martin BallandClaude Opus 5.5 209db57e2c Merge to New Document / Printer: the To: box gets its caption back (#7976) (#8287)
* Merge to New Document / Printer: the To: box gets its caption back (#7976)

The second record-range box drew no caption; its "To:" was only the
accessible name. Wrap it in `labelled`, as Find Recipient and Insert
Merge Field already are. The first box keeps the From: radio as its
caption.

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

* Merge to New Document / Printer: From and To boxes on one row (#7976)

The To: caption pushed its box right of the From box. Both boxes now
share a row, "[from] To: [to]", under the From: radio.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 19:42:36 +00:00
autocraft-bot[bot] 481eb1e79b Merge pull request #7876 2026-12-02 19:42:36 +00:00
autocraft-bot[bot] 4b5ad59b01 Merge pull request #7585 2026-12-02 19:42:36 +00:00
autocraft-bot[bot] f22123dbaf Merge pull request #7539 2026-12-02 19:42:36 +00:00
autocraft-bot[bot] df475fac83 Merge pull request #6986 2026-12-02 19:42:36 +00:00
Reuben Grinberg 1405e7e8cb Review: remove a trailing paragraph whose mark resolves to removal (#3750) 2026-12-02 12:49:32 -06:00
Mat Strange cf8b64ffae Copy: the clipboard takes a copy whole, or not at all
The copy went on the clipboard before its HTML and RTF flavours were
made, so a copy whose export failed left the new fragment on the
clipboard beside the previous copy's HTML and RTF: a later paste could
mix the two.

The flavours are made first and the clipboard takes the text, the
fragment and the flavours together, or keeps what it held.

An altChunk that cannot be read is now said so in the log, rather than
skipped in silence.
2026-12-02 16:49:31 +00:00
Mat Strange aea7330f43 #8370: the formats report a conversion they could not make
The HTML, Markdown, RTF and LaTeX exporters turned a failed conversion into
an empty string, and their importers turned one into an empty document: a
save wrote a file with nothing in it and said it had saved, and an open
showed a blank document and said nothing.

The conversion is the only thing that can fail there, and it is now
reported: the exporters and the importers return the error, and the
engine passes it on — the clipboard copy, the HTML paste, the Markdown
source view (which leaves the document as it is rather than emptying it),
the file open and the file save.

The RTF importer already reported it; the other three did not.
2026-12-02 15:37:39 +00:00
dfgodvan 951e6b230d Merge main into w1/multiple-of-tallest-run
# Conflicts:
#	crates/layout/src/para/lines.rs
#	crates/layout/src/tests.rs
#	docs/layout-parity.md
2026-12-02 16:55:02 +03:00
dfgodvan f55fabaac6 Merge main into w1/line-end-kern
# Conflicts:
#	crates/layout/src/tests.rs
#	docs/layout-parity.md
2026-12-02 16:54:16 +03:00
dfgodvan faa032ec12 Merge main into w1/times-twin-fallback-height
# Conflicts:
#	docs/layout-parity.md
2026-12-02 16:53:47 +03:00
dfgodvan 989a377de9 Merge main into w1/leading-past-footer
# Conflicts:
#	docs/layout-parity.md
2026-12-02 16:52:23 +03:00
dfgodvan b8362fc62d Merge main into w1/picture-whole-twips
# Conflicts:
#	docs/layout-parity.md
2026-12-02 16:51:35 +03:00
Max MittelstädtandGPT-6-Luna c14183a0a0 Clear drag state after completed clicks
Fixes #8324

Co-Authored-By: GPT-6-Luna <noreply@openai.com>
2026-12-02 13:26:37 +00:00
dfgodvan 78b0a6929c Layout: the right-tab rule applies to right tabs only, and not beside a float
A decimal tab keeps main's fit: its digits after the point run on to the right
of the stop, so taking text up to the stop let a number run past the margin.
Where a floating object narrows the line, text after a right tab keeps to the
narrowed edge instead of running into the object.
2026-12-02 16:05:51 +03:00
dfgodvan 870bec1839 Merge main into fix/right-tab-beyond-indent 2026-12-02 16:02:02 +03:00
dfgodvan e819a03435 Layout: the list-number kerning test loads the test fonts; Word for Mac in the comments
The test now uses the test fonts, whose kerning pairs make it fail without the
change whatever fonts the machine has. The comments name Word for Mac, where the
measurement was made, as the description does; the Kerning parity row mentions
list numbers.
2026-12-02 15:56:26 +03:00
dfgodvan 77c0a29922 Merge main into w1/list-number-no-kern
# Conflicts:
#	crates/layout/src/para/paragraph.rs
#	docs/layout-parity.md
2026-12-02 15:55:52 +03:00
dfgodvan cc438cb369 Layout: no break after a space before a word joiner or a zero-width space
UAX #14 never lets a word joiner (U+2060, U+FEFF) or a zero-width space
(U+200B) start a line (LB11, LB7). The parity entry now states the rule's
limits: whitespace after the space and kinsoku still keep the space.
2026-12-02 15:54:39 +03:00
dfgodvan 5a22d2d4ae Merge main into w1/break-after-any-space
# Conflicts:
#	docs/layout-parity.md
2026-12-02 15:54:17 +03:00
dfgodvan d66a7d3bf9 Layout: the layout cache follows a change of compatibility mode
Paragraph layout depends on the compatibility mode (widow control in table
cells before Word 2013 layout), so the mode is part of the cache environment.
2026-12-02 15:52:51 +03:00
dfgodvan 5efc89e5ea Tests: cells of a table without a style drop widow control before Word 2013 layout too
The cell layout gives every cell's paragraphs a cell text environment, an empty
one when the table has no style (boxes.rs), so the compatibility-mode rule
applies to tables without w:tblStyle as well.
2026-12-02 15:51:51 +03:00
dfgodvan 010134fb8e Merge main into fix/legacy-tables-at-page-foot
# Conflicts:
#	crates/layout/src/tests.rs
2026-12-02 15:51:46 +03:00
codeiouandClaude Code 08b8d71ece docs: distinguish deferred input replies from completed edits
A deferred control reply can arrive during the final input pass, before
that pass updates the document. Describe the observed deferral without
promising that the edit has already been applied. Keep the queued typing
example and tell clients to check the resulting state without replaying
an edit merely because its effect is not yet visible.

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

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-12-02 22:17:32 +11:00
Mat Strange 940b64273c test(engine): require both ends of tracked move 2026-12-02 11:09:36 +00:00
Mat Strange a1fa8b1a13 #8332: a failed command between a tracked cut and its paste leaves the move
The session cleared the pending tracked move before any mutating command
ran, so a command that failed took the move with it: the paste after it was
an ordinary deletion and insertion instead of a move.

The move is now put back when the command fails, the way the formatting
waiting at the caret already is.
2026-12-02 11:00:21 +00:00
Max MittelstädtandGPT-6-Luna d05c629fc0 Keep merged-cell text within the first page body
Fixes #7932

Co-Authored-By: GPT-6-Luna <noreply@openai.com>
2026-12-02 10:25:25 +00:00
Zaxaerith e8c3216cad macOS: sync bundle localizations with registered languages (#8305) 2026-12-02 17:37:59 +08:00
codeiouandClaude Opus 5.5 8027b35f8d Fonts: a bold or italic check box run keeps one face when a symbol font loads during its search (#7863)
A bold or italic run's fallback search read the face count again after looking up the chosen
family's style, and kept that newer count when nothing had loaded before the lookup. The lookup
loads nothing (the chosen face is loaded, so it picks among the family's loaded faces), so the
newer count could only take in a face another thread loaded meanwhile: a run of ballot boxes was
then cached with DejaVu Sans for a face list that had Apple Symbols, listed earlier, and the run
kept DejaVu Sans while each box took Apple Symbols. The search now keeps the count its face was
chosen from, as an upright run's does, so such an answer is returned but not cached. Other bold
and italic runs went through the same lines and keep their count too.

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 19:32:11 +11:00
autocraft-bot[bot] 4bac1b4da0 Merge main (647e7261) into the pull request 2026-12-02 07:39:07 +00:00
autocraft-bot[bot] e862c6ad51 Merge pull request #7880 2026-12-02 07:39:07 +00:00
autocraft-bot[bot] 3035dda6d4 Merge pull request #6936 2026-12-02 07:39:07 +00:00
autocraft-bot[bot] 6b0c47d2a8 Merge pull request #6523 2026-12-02 07:39:07 +00:00
autocraft-bot[bot] 1a8e4ac2d3 Merge pull request #6468 2026-12-02 07:39:07 +00:00
autocraft-bot[bot] 647e726179 Merge pull request #7647 2026-12-02 07:39:07 +00:00
autocraft-bot[bot] c2f7c65e9c Merge pull request #8248 2026-12-02 07:39:07 +00:00
autocraft-bot[bot] 8d9eb6fc0f Merge pull request #6832 2026-12-02 07:39:07 +00:00
autocraft-bot[bot] 93abd12f9f Merge pull request #6213 2026-12-02 07:39:07 +00:00
autocraft-bot[bot] f722a2f80b Merge pull request #5505 2026-12-02 07:39:07 +00:00
autocraft-bot[bot] 6b8f63e207 Merge pull request #7633 2026-12-02 07:39:07 +00:00
autocraft-bot[bot] 678e813ec4 Merge pull request #8218 2026-12-02 07:39:07 +00:00
autocraft-bot[bot] afba11d6e0 Merge pull request #6529 2026-12-02 07:39:07 +00:00
autocraft-bot[bot] 2b30b235d8 Merge pull request #7603 2026-12-02 07:39:07 +00:00
autocraft-bot[bot] 1f682738fd Merge pull request #8174 2026-12-02 07:39:07 +00:00
FredApps 836799463a Merge pull request #4169 from marcoarnulfo/fix/arrows-enter-equation
Equations: Left and Right step into an equation next to the caret, as in Word
2026-12-02 08:39:07 +01:00
autocraft-bot[bot] 423c58523d Merge pull request #7570 2026-12-02 07:39:07 +00:00
autocraft-bot[bot] e076e47529 Merge pull request #6942 2026-12-02 07:39:07 +00:00
autocraft-bot[bot] f87e9cd6ba Merge pull request #7555 2026-12-02 07:39:07 +00:00
FredApps e70879e085 Merge pull request #4055 from matstrange/fix/mailings-csv-limits
Mail merge: a recipient list over what it keeps is refused while it is read
2026-12-02 08:38:16 +01:00
FredApps f416b3f1a5 Merge branch 'main' into fix/arrows-enter-equation 2026-12-02 08:15:09 +01:00
FredApps 9af6bdea33 Merge branch 'main' into fix/mailings-csv-limits 2026-12-02 08:15:02 +01:00
FredApps 4cf4eacc91 Merge pull request #3181 from SlavenDj/fix/3126-empty-window
Offer Blank document, Browse… and Home in the empty window (#3126)
2026-12-02 08:14:20 +01:00
FredApps 733a410095 Merge pull request #2011 from justinjohn0306/codex/fix-1913-line-spacing
Design: apply paragraph spacing presets to built-in styles (#1913)
2026-12-02 08:13:42 +01:00
Max MittelstädtandGPT-6-Luna 17a13fd901 Place body text frames at page anchors
Fixes #6531

Co-Authored-By: GPT-6-Luna <noreply@openai.com>
2026-12-02 06:25:42 +00:00
FredApps 20fc916072 Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	ROADMAP.md
#	docs/typing-parity.md
2026-12-02 13:24:55 +07:00
FredApps 64ec14c3df Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	ROADMAP.md
2026-12-02 13:24:47 +07:00
FredApps 5c9f816ad2 Merge branch 'main' into fix/3126-empty-window 2026-12-02 07:21:59 +01:00
FredApps eff3740ec5 Merge branch 'main' into codex/fix-1913-line-spacing 2026-12-02 07:21:52 +01:00
FredApps c5375d8186 Merge pull request #2899 from maxm11/feat/docx-corpus-harness
M15 #1: opt-in DOCX corpus harness
2026-12-02 07:21:02 +01:00
FredApps 11871dc9a5 Merge pull request #4188 from RatkoR/fix/4126-enter-on-picture
A selected picture survives Enter and breaks (#4126)
2026-12-02 07:20:25 +01:00
FredApps 8e5200fc47 Merge pull request #2186 from D13GOOOO/rtl-numbers-latin
Right-to-left text: Latin text keeps its digits, spaces and punctuation in order (#2150)
2026-12-02 07:19:42 +01:00
FredApps 7a49244c7a Empty window test: check the page gets the keyboard after Blank document
As CodeRabbit noted, text.insert does not depend on focus, so the test
passed without focus_page_after_pass. Assert the canvas is focused and
type through the harness instead.
2026-12-02 12:40:44 +07:00
FredApps c0b8362187 Empty window: keep Home a quiet link-style button after the craft::ui port
The port to craft::ui made Home a regular button, though its comment
(and the original change) has it reading as a link beside Blank
document and Browse…. Use the ghost variant, as other quiet buttons do.
2026-12-02 12:40:01 +07:00
FredApps a65a49f9a2 docs: fix the #1913 history rows from the main merge
The progress-log row had a third cell in a two-column table, the
ui-parity rows sat above the table's separator, and two rows described
template UI that this PR does not add. Rows now sit in date order.
2026-12-02 12:38:52 +07:00
FredApps 05bfd76bcf Merge branch 'main' into fix/arrows-enter-equation 2026-12-02 06:25:42 +01:00
FredApps ff5aff859b Merge branch 'main' into fix/mailings-csv-limits 2026-12-02 06:25:35 +01:00
FredApps f6461d4f18 Merge branch 'main' into feat/docx-corpus-harness 2026-12-02 06:25:29 +01:00
FredApps 81d3713818 Merge branch 'main' into fix/4126-enter-on-picture 2026-12-02 06:25:22 +01:00
FredApps d41b7e38f4 Merge branch 'main' into rtl-numbers-latin 2026-12-02 06:25:16 +01:00
FredApps 6c53e35c16 Merge pull request #3972 from Silvertree2010/fix/3678-audit-minor-json-open-doesn-t-re
Reconcile inline objects with U+FFFC markers on .json open
2026-12-02 06:24:20 +01:00
FredApps b324cbab29 Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	crates/doc/src/tests.rs
2026-12-02 11:55:22 +07:00
FredApps b065d1a70e Merge branch 'main' into fix/3126-empty-window 2026-12-02 05:50:06 +01:00
FredApps bbf6ac60cb Merge branch 'main' into codex/fix-1913-line-spacing 2026-12-02 05:50:00 +01:00
FredApps d66724fba0 Merge branch 'main' into rtl-numbers-latin 2026-12-02 05:49:53 +01:00
FredApps 3cc3ef1d51 Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	ROADMAP.md
#	docs/typing-parity.md
2026-12-02 11:47:40 +07:00
FredApps 878f3ef2ca Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	ROADMAP.md
2026-12-02 11:47:33 +07:00
FredApps cc2c37232a Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	ROADMAP.md
2026-12-02 11:47:27 +07:00
FredApps 7cd6dcdbc2 Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	docs/typing-parity.md
2026-12-02 11:47:14 +07:00
FredApps 866b188e2a Merge pull request #4823 from OPUZZLES/fix/pdf-figure-object-lookups
PDF: reuse paragraph-prefix lookups for figure tags (#3614)
2026-12-02 05:26:11 +01:00
FredApps b472bdef73 Merge pull request #8179 from reubgr/fix/review-resolution-preserved-refs-8129
Review: Accept/Reject All keeps revision records still referenced by untouched stories (#8129)
2026-12-02 05:25:34 +01:00
FredApps e01bf4a57b Merge pull request #8175 from reubgr/fix/delta8-residue-7643
validate: OMML name list, JPEGTables splice + Tech Note #2 structure, TIFF depth pins (#7643)
2026-12-02 05:24:59 +01:00
FredApps 057a8b79b1 Merge pull request #3925 from Jayesh-Prajapati9/fix/3639-header-commands-own-section
#3639: Header and footer commands change the section of the header the caret is in
2026-12-02 05:24:22 +01:00
FredApps 3a93ffab6d Merge branch 'main' into fix/3126-empty-window
Resolved progress-doc conflicts: kept main's status headers and added this PR's revision-history rows.
2026-12-02 11:04:46 +07:00
FredApps f72124cfdd Merge branch 'main' into rtl-numbers-latin
Resolved progress-doc conflicts: kept main's status headers and added this PR's revision-history rows.
2026-12-02 11:04:42 +07:00
FredApps 3311690632 Merge branch 'main' into codex/fix-1913-line-spacing
Resolved docs/target-app-parity.md: kept main's table and re-applied this PR's #1913 note and its two revision-history rows.
2026-12-02 11:03:08 +07:00
FredApps 25f34eec75 Merge branch 'main' into fix/pdf-figure-object-lookups 2026-12-02 05:02:51 +01:00
FredApps b2a4699384 Merge branch 'main' into fix/review-resolution-preserved-refs-8129 2026-12-02 04:53:07 +01:00
FredApps d23ae8609b Merge branch 'main' into fix/delta8-residue-7643 2026-12-02 04:53:01 +01:00
FredApps 80f01dabb8 Merge branch 'main' into fix/3639-header-commands-own-section 2026-12-02 04:52:41 +01:00
autocraft-bot[bot] e9da627bfe Merge pull request #4405 2026-12-02 00:36:36 +00:00
autocraft-bot[bot] 6c93357f0e Merge pull request #3834 2026-12-02 00:36:36 +00:00
autocraft-bot[bot] 7b180bcf1e Merge pull request #4436 2026-12-02 00:36:36 +00:00
autocraft-bot[bot] 32d96170e1 Merge pull request #3228 2026-12-02 00:36:36 +00:00
autocraft-bot[bot] aa3e7b9d5f Merge pull request #3513 2026-12-02 00:36:36 +00:00
FredApps 359999c32e Merge pull request #8092 from reubgr/feat/doctype-measured-cells
validate: complete the measured grading of XML-DOCTYPE interim cells
2026-12-02 01:36:36 +01:00
FredApps 15fc342b11 Merge current main into WordCraft #8175 2026-12-02 01:26:40 +01:00
FredApps 93f8cefacf Merge branch 'main' into feat/doctype-measured-cells 2026-12-02 01:08:37 +01:00
Martin BallandClaude Opus 5.5 012afe2dcf Symbol: the Special Characters "Shortcut key:" header is not clipped (#7982) (#8226)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 23:50:30 +00:00
Martin BallandClaude Opus 5.5 6c7d31aa6f Customize Ribbon: the "Show" column header is not clipped (#7981) (#8212)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 23:50:23 +00:00
Martin BallandClaude Opus 5.5 830e629541 Equation tab: the Tools group keeps its labels (#7975) (#8198)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 23:50:17 +00:00
yoriswind 50c7b1963f fix(review): make resolve-and-advance actions bindable 2026-12-01 15:40:43 -08:00
FredApps c6b037d6c0 Merge branch 'main' into feat/doctype-measured-cells 2026-12-02 00:39:46 +01:00
yoriswind b4eff8d494 fix(organizer): group the file chooser with the template styles (#7980) 2026-12-01 15:01:52 -08:00
RickiNano 79b3b88edd References: Insert Index gives an index from a Word file its new settings (#8034)
An index Word wrote as a range field in the main text was refused by
Insert Index, so its new settings were dropped. It is now made a plain
field in its own paragraph first, as Update Index makes it, and then
takes the settings and is rebuilt like an index WordCraft inserted.
2026-12-01 21:24:50 +01:00
Martin BallandClaude Opus 5.5 8b5bfa78bf fix(options): show the Read Aloud speed with two decimals (#7987) (#8259)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 17:49:04 +00:00
Martin BallandClaude Opus 5.5 313e14885f fix(chrome): widen the command search drop-down (#7983) (#8258)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 17:48:56 +00:00
Martin BallandClaude Opus 5.5 9a8786a3ab fix(chrome): mute the AutoSave label while AutoSave is off (#7681) (#8257)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 17:48:47 +00:00
Martin BallandClaude Opus 5.5 4b5a96163c fix(dialogs): frame the Macros list (#8017) (#8256)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 17:48:39 +00:00
Martin BallandClaude Opus 5.5 5a68da541f fix(dialogs): frame the Bookmark list and put Cancel last (#7979) (#8255)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 17:48:31 +00:00
x-labb 3820b9b206 Canvas: clicking a picture selects it without scrolling the view (#5602) 2026-12-01 18:38:01 +01:00
FredApps f7e2e88133 Merge branch 'main' into feat/doctype-measured-cells 2026-12-01 18:33:02 +01:00
batistalucasv e874c67147 caret: Page Up/Down reach the story's ends on the first and last page (#8200) 2026-12-01 14:09:32 -03:00
reubgr 7dce30c8af validate: a stored nested zip as the final part no longer disputes the outer directory (#8128)
* fix(validate): ignore unreachable EOCDs inside verified entry payloads (#7035)

* test(validate): expect PASS for stored_nested_zip and guard payload reachability (#7035)

* fix(validate): restrict dispute clearance to final entry with verified local header (#7035)

* test(validate): regress non-final entry and inconsistent local header disputes (#7035)

* fix(validate): require central-last entry to be physically last for dispute clearance (#7035)

* test(validate): regress CD-last but physically non-last stored nested zip (#7035)

* fix(validate): start ZIP64 footer span at adjacent ZIP64 EOCD record (#7035)

* test(validate): regress straddling ZIP64 footer and embedded ZIP64 clearance (#7035)
2026-12-01 17:51:38 +01:00
BFlat b4efb2fef1 Merge pull request #8180 from shantanuo/codex/add-hindi-language
Add Hindi to Review language list
2026-12-01 22:18:53 +07:00
BFlat 30b8f025d2 Merge pull request #8252 from ruchirguitar/hi-interface
i18n: Hindi (hi) as an interface language
2026-12-01 22:18:09 +07:00
Martin BallandClaude Opus 5.5 27efb34a95 Repin craft-libs to d73e274a (egui 07c20531, winit 0dfcec0e) (#8250)
* chore(deps): repin craft-libs to d73e274a, egui to 07c20531, winit to 0dfcec0e

Moves every craft-libs rev (including craft-nightly and the craft-libs
patches) from 7097741460 to craft-libs main d73e274a, and the egui and
winit forks to the revs craft-libs builds with at that commit. Cargo.lock
holds one egui and one winit; only the affected git packages changed.

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

* fix(ui-egui): adapt to craft-libs d73e274a API

RibbonLook::body takes a RibbonBody (Band keeps the ruled fill), the
GalleryMore::Body closure takes a BodyCx, ToggleButtonOutput is read
through .edit.response, and DrawEnv has a mark field.

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

* test(ui-egui): follow craft-libs name and list changes

Tests that look controls up by access name or by list contents follow
intended craft-libs changes. No assertion is removed or weakened.

- Split arrows are named "<label> options" and a stacked label's line
  break reads as a space (craft-libs 487b29c55): Bullets arrow, Switch
  Windows arrow; the View ribbon's Web Layout and Print Layout buttons now
  share a name with the status bar toggles, so the toggle is picked by state.
- The table size picker names squares "<columns>x<rows> Table" (was
  "<rows> × <columns>").
- A dropdown list ends on its last whole row and scrolls the rest
  (craft-libs f2b9450d8): the font size list no longer holds 28 unscrolled,
  so the tests use 24, which is shown.

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

* fix(wordcraft): adapt the ui.json import to craft-libs LegacyFile

LegacyFile takes the old files as `paths` and its parse gets one slot per
path (bytes, absent or a read error). The ui.json import passes its one
path and a small wrapper over legacy_ui_json; behaviour is unchanged.

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

* fix(ui-egui): pass grid rows to TileGrid max_rows after the craft-libs repin

craft-libs a84275d0d/f6ae74bf4 make a grid's max_rows count visual rows, not
items, so the tile_rows_cap workaround (rows*columns items) now asked for up to
128 rows and the Symbols map grew to ~3600 px. Drop the workaround and pass the
row counts (Symbols 8, Insert Diagram 3) directly.

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

* fix(wordcraft-web): adapt the web host to craft-libs d73e274a

The web app still used the old craft-libs API, so it no longer compiled
(CodeRabbit on #8250; macOS Print / lint):
- LegacyFile now takes `paths` and a slot-based parse. The slot adapter
  moves from the desktop app into ui-egui as `legacy_ui_json_slots`, and
  both hosts use it.
- web-host's `Message::Open` name is now `Option<String>`; a missing name
  becomes `Document.docx` as a blank one did.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 14:50:18 +00:00
bflatastic 61c69fceca docs: the catalog range takes in Hindi's 2,800 entries 2026-12-01 21:16:41 +07:00
batistalucasv 605df8c165 Zotero: surface bridge call errors in status bar (#3589) 2026-12-01 09:24:33 -03:00
RickiNanoandFredApps 199162f96a #7818: Review › Delete: Delete All Comments in Document and Delete All Resolved Comments (#7836)
* #7818: Review › Delete: Delete All Comments in Document and Delete All Resolved Comments

Review › Comments › Delete becomes a split button whose menu has Delete,
Delete All Comments in Document (the existing review.deleteComment
{"all": true}) and Delete All Resolved Comments, a new
review.deleteComment {"resolved": true} that deletes each resolved
comment with its replies and keeps the open ones, in one undo step.

thread_of becomes threads_of, taking several roots and building the
reply map once, so deleting many resolved threads stays one pass.

* #7818: regenerate the parity checklist after merging main

main added the headless count; with this PR's two commands it is 512.

---------

Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-12-01 12:24:20 +01:00
ruchirguitar ea7322efac ROADMAP: Hindi coverage as i18n-report measures it 2026-12-01 16:48:27 +05:30
reubgrandMuse 3e64bba9bb validate: keep established TIFF cycle defects when a sibling hits the depth bound (#8186) (#8223)
* fix(validate): preserve established TIFF graph defects across traversal bounds (#8186)

* test(validate): probe adjacent TIFF cycle, malformed, and bound shapes (#8186)

* chore(validate): satisfy clippy::obfuscated_if_else in TIFF tests (#8186)

* fix(validate): preserve established TIFF edges across budget stops and charge examined directories (#8186)

* fix(validate): defer TIFF walk continuation past initial part assessments (#8186)

* fix(validate): disclose every affected TIFF and budget-stopped part in canonical order (#8186)

* test(validate): add discriminating tests for #8186 round-1 findings and box PausedWalk

* fix(validate): install cached TIFF chain edges as soon as chain role is established (#8186)

* fix(validate): confine multi-part decode-stop disclosure to TIFF parts (#8186)

* test(validate): add discriminating tests for #8186 round-2 findings

* chore(validate): satisfy clippy in TIFF chain-role helper and tests (#8186)

* test(validate): match all three TIFF admission outcomes in graph oracle (#8186)

Match Admission::Admitted, Admission::MalformedOrCyclic, and Admission::Limited explicitly in media_magic_tiff_admission_is_a_function_of_the_directory_graph instead of collapsing Limited and MalformedOrCyclic via matches!, and key the sampled report-level check to the same three-way outcome.

---------

Co-authored-by: Muse <muse@Mac-mini.local>
2026-12-01 11:45:11 +01:00
reubgr 5d93167fe0 Doc: collect text boxes inside nested shape groups (#8068) (#8158)
* fix(doc): collect text boxes inside nested shape groups (#8068)

Walk InlineObject::Group trees iteratively in member order in both
InlineObject::text_boxes and InlineObject::text_box_slots so text boxes
nested inside groups of groups are collected, kept alive by
Document::prune_text_boxes, and repointed consistently during fragment
adoption and comparison.

* test(doc,engine): cover nested-group text box collection, pruning and Session survival (#8068)

Add wordcraft-doc unit tests for nested-group text_boxes and text_box_slots
collection across depths 1..40, prune_text_boxes preservation with chain links
and unreachable boxes, and cyclic nested-group story termination. Add an
end-to-end wordcraft-engine Session test verifying nested-group text boxes
survive mutating commands and copy/paste adoption.

* test(doc): flatten text_box_slots iterator to satisfy clippy (#8068)
2026-12-01 11:42:20 +01:00
RickiNano 6659ce4adc #7443: Insert Citation cites the source it just edited, not the last one (#7965)
references.citation with a source and no tag now cites the tag that
source was added or edited under, instead of the last source in the
list. Manage Sources' add step moves into add_source, which returns
that tag.
2026-12-01 11:39:54 +01:00
RickiNanoandSilvertree2010 43632f571c #3670: Insert Index doesn't add a second index when the existing one is in a table or text box (#8036)
* #3670: Insert Index doesn't add a second index when the existing one is in a table or text box

Insert Index looked for the INDEX field only in top-level body paragraphs.
An index in a table cell, a text box, a header or a footer (as imported
documents can have it) was missed, so a second index went in at the caret,
and Update Index reported success without rebuilding it.

Both commands now refuse with a message saying where the index is, the way
an index can't be inserted outside the main text either. Rebuilding an
index where it sits is not supported.

Builds on #3961 by @Silvertree2010; this version also finds an index
held as a range field (as Word files hold it) or in a text box.

Co-authored-by: Silvertree2010 <133535268+Silvertree2010@users.noreply.github.com>

* #3670: Insert Index counts only the headers a page shows, and leaves a range-field index to Update Index

* #3670: refuse a range-field index that follows text, and prove Update Index rebuilds one that starts its paragraph

* #3670: refuse an index in a table or box even when the main text has one too

---------

Co-authored-by: Silvertree2010 <133535268+Silvertree2010@users.noreply.github.com>
2026-12-01 11:36:36 +01:00
Lucas Batista Vargas 0e3f5f3ea6 Linux: restore GNOME Wayland window controls without bundled fonts (#5814, #5375) (#6078)
* Linux: restore GNOME Wayland window controls without bundled fonts (#5814, #5375)

* Verify Linux target section for winit Wayland decorations in test

* test(linux): check forbidden font crates across entire Cargo.lock

* test(linux): check sctk-adwaita dependency path instead of workspace-wide Cargo.lock (#5814)
2026-12-01 11:30:13 +01:00
reubgr 3c8a1eeb2d Doc: next_shape_id walks nested groups and all stories (#8157) (#8169)
* fix(doc): inspect nested shape groups in Document::next_shape_id (#8157)

Walk InlineObject::Group trees iteratively with a worklist in
Document::next_shape_id so ShapeExtra::id values on shapes inside nested
groups are accounted for at any nesting depth without unbounded recursion.

* test(doc): cover nested-group, flat, ungrouped, and cyclic-story shape ID allocation (#8157)

Verify Document::next_shape_id accounts for shapes inside doubly-nested,
5-level, and 40-level groups across body and secondary stories, preserves
existing allocation for empty, ungrouped, flat-group, and u32::MAX cases,
and terminates cleanly on cyclic nested-group text-box story graphs.

* fix(doc): avoid reissuing u32::MAX in Document::next_shape_id (#8157)

Replace saturating increment with free_id in Document::next_shape_id so
that when u32::MAX is already in use (including inside nested groups),
allocation falls back to the smallest unused non-zero ID rather than
reissuing u32::MAX. Update the overflow assertion and add tests covering
the u32::MAX - 1 boundary and u32::MAX overflow fallback.

* fix(doc): walk note-separator stories in Document::next_shape_id (#8157)

Include footnote_separators and endnote_separators (separator,
continuation_separator, and continuation_notice) in Document::next_shape_id
so shape IDs living only in separator stories are never reissued, including
under nested groups, tables, and u32::MAX overflow fallback.
2026-12-01 11:27:03 +01:00
ruchirguitar 3b7779df34 craft-i18n.rev at 217f413: Hindi WordCraft catalog (craft-i18n #579)
Moves the pin and the flatpak manifest's craft-i18n commit together and
fills in the Hindi catalog's size (2,800 rows) in the docs.
2026-12-01 15:50:49 +05:30
RickiNano e7588ff931 #7874: Home › Borders with whole table cells selected borders the cells (#7946)
* #7874: Home › Borders with whole table cells selected borders the cells

Home › Paragraph › Borders always set paragraph borders, so with the
table (or rows, columns or a block of cells) selected, All Borders drew
a separate box around each paragraph instead of a grid on the cell
edges. With whole cells selected, para.borders now applies the kind to
the cells as one block: all borders every cell, outside the block's
edges, inside the lines between its cells, none clears every side, and
one side toggles along that edge. A caret or text selection still
borders the paragraphs.

* #7874: block borders reach the cells beyond the edge and rows with gridBefore

Review fixes for #7946. Each cell draws its own sides, so a line set on
the selected block's edge is now also set on the facing side of the cell
beyond it: No Border on a row no longer leaves the neighbouring rows'
lines showing. A row's first and last cells count as the block's outer
edge when the row skips grid columns (gridBefore/gridAfter), as the
layout draws them.

* #7874: Borders on whole cells judges the block's edges by the cells picked, and toggles a line the table style draws

A row that skips the selected grid columns (w:gridBefore) leaves a gap: the selected cells above
and below it now face it with an outer edge, so Outside draws those lines and Inside doesn't.

One side now toggles on the line the cells show, the table style's included: the layout's cell
border resolution is cell_borders in wordcraft-layout, and the first press on a Table Grid line
takes it off.

* #7874: Borders on whole cells looks up the selected cells by row, and toggles a line off only when it runs all along the edge

A line the cells beyond an edge draw counts as shown only when every one of them draws it, so a
line along part of a wide cell's edge is completed rather than taken off.

* #7874: Borders on whole cells resolves the table's style, borders and grid width once per press

wordcraft_layout::CellBorders resolves them for one table; cell_borders stays a wrapper.

* #7874: Borders on whole cells takes in all of a vertically merged cell

Selecting a cell merged over several rows from its first row selects only that row; the rest of
the merge now counts as selected, so No Border clears the whole cell's outline.

* #7874: Borders on whole cells counts a line beyond an edge as shown only where it spans the whole edge

A row below that skips columns (w:gridAfter) draws the facing line along part of the edge only;
the press now completes the line instead of taking it off.
2026-12-01 11:17:38 +01:00
Martin BallandClaude Opus 5.5 ba1ed225c0 Bookmark: the Sort by label is back (#7976) (#8196)
The Sort by radio group had no caption row after the craft-ui port; wrap it in captioned() as #8026 did for the other dialogs.


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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 11:13:54 +01:00
36e7ee7ade #6851: tracked changes are dated in local time, as Word reads w:date (#6876)
* #6851: date tracked changes in local time, as Word reads w:date

Word writes w:date as the local wall-clock time with a Z it doesn't mean,
and reads it back the same way. WordCraft stamped new tracked changes with
UTC, so Word showed them shifted by the author's offset from UTC.

Typing, deletions, moves, formatting changes and Compare's result now take
cmd::revision_date(): the local time from the existing local_offset_secs
helper, written with a Z. Comments keep their w16cex:dateUtc and are
unchanged.

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

* #6851: the local-time test accepts any second between its samples

Review on #6876: the tracked change may be stamped a second after the
first sample and before the second, so compare against the interval, in
order, rather than its two ends.

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

* #6851: check the stamp against each second's own local time

Review on #6876: across a backward daylight-saving change the local times
of the two samples no longer bound the stamp. Sample the UTC clock instead
and accept the local time of any second between the samples.

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

* #6851: the local-time test pins its zone and covers every revision

A test-only, per-thread zone for revision_date() lets tracked_changes_carry_the_local_time
stamp at UTC+8:45 on any runner. On CI's UTC runner a UTC stamp was also the local one, so
switching a call site back to now_iso() passed. The test now makes a revision through each
place that dates one: typing, a paragraph tool, formatting, AutoFormat's border line, a tracked
cut pasted as a move, and Compare.

* #6851: keep tracked change dates in UTC; convert w:date at the DOCX boundary

The document keeps the UTC instant, so revision grouping tells apart two
edits an hour apart in the repeated hour as daylight saving time ends.
Saving .docx/.docm/.dotx/.dotm or Word XML writes w:date as local
wall-clock time with a Z, as Word writes and reads it; opening them reads
it back to UTC. Tests set the clock and zone per thread.

* Dependencies: take craft-libs main at 8a5b916541

8a5b916541 is craft-libs#3220: craft-docx reads and writes w16du:dateUtc
on tracked changes and keeps it in the shared model's Revision, so two
changes with one local w:date stay two. #6876 (#6851) builds on it.

The egui and winit forks craft-libs builds with are unchanged
(b9770908e0, a517b3846e). Cargo.lock: the craft-libs sources move to the
new rev and craft-control-protocol, a craft-libs crate, is added.

* #6851: tracked changes keep their UTC time beside w:date

A revision now has date_utc, as comments do, read from and written to
w16du:dateUtc by craft-docx. Changes made here are stamped with both in
UTC, grouped by the UTC instant, and a Word save writes their w:date in
local wall-clock time, as Word does, with dateUtc beside it. A change read
from a file is written as read: open no longer guesses the zone a w:date
without dateUtc was written in. review.changes reports the UTC time when
it is known.

Two edits in the repeated hour reopen as two changes, and Reject on the
second leaves the first pending.

* Dependencies: section metadata test expects w16du in mc:Ignorable

craft-libs#3220 declares the w16du namespace in body parts and lists it
in mc:Ignorable, so readers that don't know it ignore it.

* #6851: rustfmt the test revisions

* #6851: docs describe dateUtc and dates written as read

* #6851: date a change in local time when it is made, not when it is saved

The save treated a revision whose w:date equals its dateUtc as made here
and moved its w:date to local time. A file written in UTC has the two
equal too, so saving it in another zone moved the time Word shows for an
edit nobody touched.

A change made here now gets its local w:date when it is made
(cmd::made_revision), with its UTC time in date_utc, and saves write
every revision as it is. Nothing is inferred from the dates.

* #6851: OpenDocument dates a tracked change by its UTC time

A change made here keeps Word's local wall-clock time in `date`, which
the ODF writer wrote verbatim as dc:date, an instant, so an edit at
08:33 UTC at UTC+8 was exported as 16:33 UTC. The ODT, OTT and Flat ODF
exports now date a change by its UTC time where it is known, and by
`date` otherwise.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Martin Ball <98639962+benandez@users.noreply.github.com>
2026-12-01 10:54:25 +01:00
Martin BallandClaude Opus 5.5 14112e7137 Title bar: the search box is a quiet field again (#7682) (#8197)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 01:15:08 +00:00
Reuben Grinberg 17c6d87f0d review: assert full document equality on second-pass idempotence test (#8129) 2026-11-30 22:44:04 +00:00
batistalucasv 8d7ed624ec Prefs: store recent files relative to the home directory (#8189) 2026-11-30 18:19:21 -03:00
fluorineandClaude Haiku 5.5 aeba356814 xtask: gate the stats test imports that only unix tests use
On Windows the one test that uses Counts and walk is compiled out, so
clippy -D warnings fails with unused imports.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-30 14:39:43 -04:00
ruchirguitar b4fffa91cc docs: the Hindi interface doesn't set the language of new documents 2026-11-30 20:07:21 +05:30
ruchirguitar 5ad1c48b3e i18n: add Hindi (hi) to the interface languages
Lists hi in LANGUAGES (editing_lang None: WordCraft doesn't proof Hindi
yet), adds its system-locale test row, and updates the localization
docs and progress log.
2026-11-30 20:04:05 +05:30
fluorine ce54605a04 Merge remote-tracking branch 'upstream/main' into fix-xtask-stats-test-import 2026-11-30 10:14:46 -04:00
fluorine 592d3cb902 Merge remote-tracking branch 'upstream/main' into cursor-arrow-off-paper 2026-11-30 10:14:41 -04:00
fluorine fd81fadba7 Merge remote-tracking branch 'upstream/main' into layout-cache-test-page-bound 2026-11-30 10:14:24 -04:00
Martin BallandClaude Opus 5.5 4daed0b5ad Undo History: the list keeps its rows while the popover fades out (#8141) (#8154)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:33:42 +00:00
Martin BallandClaude Opus 5.5 d22500664d View tab: Views and Zoom keep their labels at 1440 pt (#7985) (#8156)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:28:24 +00:00
Martin BallandClaude Opus 5.5 effb736735 File rail: the Back arrow reads in the rail's ink (#7707) (#8155)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:28:17 +00:00
Martin BallandClaude Opus 5.5 d7aac19341 docs: refresh roadmap and parity summary against the 28 Nov parity run (#8059)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:38:44 +00:00
Martin BallandClaude Opus 5.5 055a9065f5 docs(7822): the root window is never shown (amend ADR 0001) (#8110)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:38:37 +00:00
17ae08d4b8 Floating toolbar: a size typed into the Font Size box applies on Enter
Typing a size into the floating toolbar's Font Size box and pressing
Enter left the text at its old size. Only a pick from the list worked.
The box's text is rebuilt from the selection's size on every pass and
was bound write-through, so the next pass put the old size back before
Enter could commit the typed one.

The box now binds its text with EditPolicy::OnCommit, which keeps what
is typed in the box until it is committed. craft's text field also
commits when focus leaves it, so the code after the box now counts
only Enter or a pick from the list, as its comment says: a size left
in the box by a click elsewhere is not applied, as in v0.19.1. The
test from the previous commit passes.

Co-Authored-By: GPT-6.2 Astra <noreply@openai.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 20:26:29 +11:00
8edbfcdeef test(ui-egui): a size typed into the floating toolbar's size box applies on Enter
The test selects text and types 20, then 16.5, into the floating
toolbar's Font Size box with real pointer and key events. It checks
that typing alone changes nothing, that Enter applies the typed size and
that the selection stays. It fails without the fix in the next commit.

Co-Authored-By: GPT-6.2 Astra <noreply@openai.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 20:26:23 +11:00
0f30f776bb Home › Multilevel List: Change to Level reaches all nine levels
The Multilevel List drop-down offered Change to Level 1 to 5, so levels
6 to 9 could not be chosen from it. The engine's para.listLevel takes
all nine, and Bullets' Change List Level already offers them. The loop
now runs to 9.

Co-Authored-By: GPT-6.2 Astra <noreply@openai.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 20:25:44 +11:00
0c7ad0e0f0 Insert › Table and Symbol: typing after a pick on the grid goes into the page
Picking a size on Insert › Table's grid inserted the table and put the
caret in its first cell, but the keyboard stayed on the Table button,
so the next text typed was lost. Picking a symbol on Insert › Symbol's
grid lost the typing the same way. Each grid runs its command itself
and closes its menu with a plain close request, and a menu closed that
way hands focus back to its opener.

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

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

Co-Authored-By: GPT-6.2 Astra <noreply@openai.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 20:25:33 +11:00
Zaxaerith 19947b9170 fix(cli): honor repeated --save options in run (#8177) 2026-11-30 17:17:43 +08:00
Hagai Baram 5265924f29 Word Count: keep automation changes to includeTextBoxes while open (#8139) (#8150) 2026-11-30 09:17:26 +00:00
Lucas Batista Vargas 0f241aef67 Mini toolbar: restore live preview and current-choice mark for Automatic and No Color (#7956) (#7957) 2026-11-30 08:19:15 +00:00
MaheshDesu 6478152244 UI: the Caption preview is its own label, not a field prefix (#8042) (#8043) 2026-11-30 08:09:02 +00:00
shantanuo 1ec6f0bb58 Add Hindi to Review language list 2026-11-30 10:34:11 +05:30
batistalucasv 3de53ecf4e test(font_picker): verify all-fonts restoration and isolate catalog with Os::None 2026-11-30 01:57:41 -03:00
batistalucasv faec3ecbde fix(table_resize): scope ruler markers to caret_drag and focused row 2026-11-30 01:54:39 -03:00
batistalucasv d46ecf3ab1 test(icons): verify stroke clearance and rendered bounds for dictate icon 2026-11-30 01:43:28 -03:00
codeiouandClaude Opus 5.5 5945ca3cae Markup PDF test: fixed creation date, no flaky byte comparison (#8173)
markup_pdf_takes_the_track_changes_option_colours exports a document with no
creation date twice and compares the bytes. Each PDF is stamped with the
current time, to the second, so the comparison failed whenever a clock second
ticked over between the exports (the Ubuntu gate on #6741 and #8009). The test
document now has a fixed creation date, as #990 did for the native print test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 14:37:10 +11:00
Reuben Grinberg a8f1edb45c review: avoid per-block/object heap allocation in revision retention walk (#8129)
Dispatch paragraphs directly in collect_block and non-Group inline
objects directly in collect_object/remap_object, initializing iterative
stacks lazily with Vec::new() so heap allocation occurs only for tables
nested inside tables or non-empty groups nested inside groups. On the
common no-surviving-references fast path, retain_referenced_revisions
performs zero heap allocations for paragraphs, non-nested tables, and
non-nested inline objects while keeping every resolution output identical.
2026-11-30 03:24:23 +00:00
Reuben Grinberg a0d4edccd6 validate(scan): distinguish unresolved-namespace AlternateContent in F11 pairing note (#7643)
In note_scan_incomplete (crates/validate/src/scan.rs:1373), the F11
coverage note previously stated that the part 'skipped
mc:AlternateContent', which overclaimed when enter_alt matched an
AlternateContent element of unresolved namespace (scan.rs:1445) or an
empty AlternateContent tag (Event::Empty, scan.rs:1178).

Reword the note so every clause holds on every path reaching line 1373:
the part contains an element treated as mc:AlternateContent
(mc:AlternateContent or AlternateContent of unresolved namespace) whose
contents are not scanned for pairing, has pending
field/move/bookmark/comment pairing, and completion-dependent pairing
checks were not run.

Part of #7643 (F11 fix round 2).
2026-11-29 21:16:54 -06:00
Reuben Grinberg d0f25cd896 review: reach fixed point in one pass on malformed PropChange chains (#8129)
Stop descending into PropChange::old during revision collection when the
outer PropChange::rev is out of bounds, matching step_prop_change which
discards the outer PropChange and any buried indices together. This
ensures retain_referenced_revisions leaves only genuinely referenced
records in doc.revisions after a single Accept/Reject All pass.

Add regression tests covering an invalid outer formatting change burying
a valid inner index (both standalone and mixed with valid/nested chains)
and asserting full document equality on a second resolution pass.
2026-11-30 03:09:25 +00:00
Reuben Grinberg b743dbad0a validate(media): drop unused Debug derive on PrefixResume for observation gate
Part of #7643 (F9).
2026-11-29 20:20:34 -06:00
Reuben Grinberg 45956f85bd validate(scan): reword skipped AlternateContent pairing note without positional claim
note_scan_incomplete previously claimed that the part had 'open
field/move/bookmark/comment ranges across skipped mc:AlternateContent',
even though skipped_content and completion_dependent_pending establish
only that mc:AlternateContent was skipped somewhere in the part and
that some completion-dependent pairing remained pending at the end of
the scan (a skipped block can precede the only range start).

Reword the note to describe the skipped mc:AlternateContent, the
pending field/move/bookmark/comment pairing, and the withheld
completion-dependent pairing checks without making an unsupported
positional claim, and pin the completed-AlternateContent-before-start
case in scan unit tests.

Part of #7643 (F11).
2026-11-29 20:04:58 -06:00
Reuben Grinberg 1201692df6 validate(media): preserve JPEG prefix fill position and marker state on resume
When a 0xFF marker-fill run or straddling marker reached the JPEGTables
prefix boundary, walk_jpeg_markers rewound to marker_start before the
entire fill run, forcing every strip chunk to rescan the same prefix
bytes.

Record the boundary resume state (AtMarker, InFill, or AfterCode(u8))
in JpegHeaderScan so each chunk resumes at the consumed position
without rescanning prefix fill bytes, and pin the splice-boundary
fill/marker/SOF/SOS cases in media_workspace unit tests.

Part of #7643 (F9).
2026-11-29 20:03:28 -06:00
Reuben Grinberg 2f33435bb8 review: test surviving refs across stories and table-clear fast path (#8129) 2026-11-30 01:42:05 +00:00
Reuben Grinberg a03307d6b0 validate(media): enforce TIFF Tech Note #2 per-stream JPEGTables split
Keep spliced-stream JPEG workspace accounting unchanged so zune-jpeg's
memory stays accurately bounded, and add an independent per-stream
conformance check (media_workspace::tiff_jpeg_tables_conforming) for
ModernJPEG pages carrying JPEGTables (tag 347):
- JPEGTables must be an ITU-T T.81 Annex B.5 tables-only abbreviated
  stream (SOI, tables/misc segments only, EOI; no SOF, SOS, or
  straddling segments);
- each strip or tile must independently start with SOI and carry its
  own complete SOF frame header before SOS.

Non-conforming splits return AlternateAssessment::Unusable so a sole
SOF placed in tag 347 no longer earns a Warning grade while proper
splits continue to pass.

Part of #7643 (F9).
2026-11-29 19:38:29 -06:00
Reuben Grinberg 8b4335903a review: retain referenced revisions on Accept/Reject All (#8129)
Compact doc.revisions instead of unconditionally clearing it in
resolve_all, keeping entries still referenced by surviving stories or
metadata (such as Ruby or content-control run properties) and remapping
every surviving reference consistently. When no references survive,
clear doc.revisions directly as before.
2026-11-30 01:37:03 +00:00
Reuben Grinberg 929950acff validate(media): dereference Copy JpegHeaderScan instead of cloning 2026-11-29 18:27:29 -06:00
Reuben Grinberg 4868d7947d validate(media): pin TIFF peer-chain depth and SubIFD depth-bound handling
Pin verified TIFF 6.0 §2 and Adobe TIFF Technical Note #1 depth behaviour
in media_magic_tiff_depth_is_the_minimum_over_routes:
- a 12-page main next-IFD chain (> max_depth = 10) remains at depth 0
  and decodes cleanly to Warning;
- a valid IFD0 with a depth-6 SubIFD tree (> tiff_ifd::MAX_SUB_DEPTH = 4,
  <= max_depth = 10) decodes cleanly to Warning, while depth 11 stops at
  the validator depth bound as Incomplete without grading.

Part of #7643 (F8).
2026-11-29 18:26:04 -06:00
Reuben Grinberg 0d31f95102 validate(scan): include comment ranges in pairing coverage note wording
note_scan_incomplete emitted 'field/move/bookmark' in its three pairing
incompleteness notes, omitting 'comment' even though finish_completion,
completion_dependent_pending, and unresolved_pairing_pending all cover
four pairing families (FLD-UNBALANCED, STRUCT-MOVE-UNPAIRED,
BOOKMARK-UNPAIRED, and COMMENT-RANGE-UNPAIRED).

Update all three notes to 'field/move/bookmark/comment' and pin the
unresolved comment-range note with a unit test.

Part of #7643 (F11).
2026-11-29 18:24:42 -06:00
Reuben Grinberg 76ee611ed5 validate(media): splice TIFF JPEGTables into JPEG strip workspace check
TIFF Technical Note #2 defines JPEGTables (tag 347) as an ITU-T T.81
Annex B.5 abbreviated table-specification datastream (SOI..EOI), but
tiff 0.11 strips its last two bytes and prepends them to each ModernJPEG
strip/tile (after stripping the chunk's first two bytes) before handing
the spliced bytes straight to zune-jpeg.

media_workspace::jpeg_strip_decoder previously inspected each raw chunk
in isolation, missing SOF/SOS segments placed in JPEGTables or marker
framing that crosses the splice boundary. Extract tag 347 in
tiff_admission::jpeg_tables and walk the shared prefix once before
resuming on each strip's suffix in O(|prefix| + sum(|chunk_headers|))
time with no heap allocation.

Part of #7643 (F9).
2026-11-29 18:22:35 -06:00
Reuben Grinberg aa0a0b990a validate(scan): align OMML element name list to all 124 ECMA-376 §22.1.2 elements
Compare scan::OMML_NAMES against shared-math.xsd (ECMA-376 Part 1 §22.1.2,
extracted into model::ELEMENTS): four real OMML elements were missing
(defJc, deg, wrapIndent, wrapRight) and two non-schema names were
spuriously present (gc, wrap), yielding 122 instead of 124.

Replace the match list with a sorted 124-entry table pinned directly
against model::ELEMENTS, and verify that unresolved deg withholds
MATH-PLACEMENT while non-OMML gc and wrap do not.

Part of #7643.
2026-11-29 18:10:41 -06:00
Dylan M. Taylor aaaeff2b94 ci(nightly): enable automated daily schedule and Stage 2 signer dispatch (#8054) 2026-11-29 16:16:22 -05:00
Dylan M. Taylor e1f261501c ci(sonarcloud): give each main commit its own concurrency group (#8144) 2026-11-29 16:05:30 -05:00
Lucas Batista Vargas 837999196a Picture and Shape: restore unit hints on size fields (#7952) (#7953) 2026-11-29 20:42:14 +00:00
Lucas Batista Vargas 13f5e9702c Manage Styles: open on the caret's current style (#7950) (#7951) 2026-11-29 20:42:09 +00:00
codeiou 0eace8de49 Search: the title bar keeps its command index between passes (#7674) (#7881) 2026-11-29 20:42:04 +00:00
codeiou 63863ec62d Caret: a window in the background shows no caret and stops repainting for it (#7674) (#7882) 2026-11-29 20:41:59 +00:00
codeiou b4f0a3abad Track Changes Options: the By author swatch shows the author colours side by side again (#7671) (#8011) 2026-11-29 20:41:54 +00:00
MaheshDesu ff98927ea6 UI: the Format Painter icon keeps its full outline (#7683) (#8044) 2026-11-29 20:41:48 +00:00
Lucas Batista Vargas fff580d8f0 perf(engine,ui-egui): skip char scans in word count, memoize format::state, and cache ribbon pickers (#7903) (#7913) 2026-11-29 20:41:43 +00:00
Lucas Batista Vargas 4b3e5d52df perf(ui-egui): defer closed Undo history rows and QAT menu assembly until opened (#7902) (#7912) 2026-11-29 20:38:45 +00:00
Dylan M. Taylor 53bbaa8978 test(nightly): retain exact launcher query and profile coverage (#8136) 2026-11-29 15:22:43 -05:00
Lucas Batista Vargas 813f069712 Styles pane: do not apply a style on right-click (#7958) (#7959) 2026-11-29 20:17:36 +00:00
Lucas Batista Vargas 43c38dfb56 Word Count: preserve the "Count words in text boxes and notes" preference on open (#7941) (#7942) 2026-11-29 19:55:25 +00:00
Dylan M. Taylor 6d6ab5f4dc feat: wire craft-nightly for self-isolated nightly launches (#8126) 2026-11-29 13:48:48 -05:00
Rees 14111658d1 fix(layout): keep indented tables readable in Read Mode (#8063) 2026-11-29 16:16:44 +01:00
Rees 0c72c0a013 #3614: integrate current PDF tag order with figure lookups 2026-11-29 08:02:19 +01:00
Martin BallandClaude Opus 5.5 54f6709a97 UI port: Colors dialog shows no colour, not black, for an unknown Current (#7984) (#8048)
* fix(colors): Colors dialog shows no colour, not black, for an unknown Current; Current reads more targets (#7984)

Needs craft-libs ColorPickerDialog::no_current and the Colors: heading
(craft-libs branch fix/7984-colors-compare-none); waits for the pin to move.

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

* fix(colors): table shading Current skips cells a ragged table lacks (#7984)

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

* fix(colors): Current reads the run shading the command changes (#7984)

para.shading shades the selected text, not its paragraph, when the selection is text within one
paragraph. Current now reads the selected runs' shading (new "shading" key in format.state, None
when mixed or unset) under the engine's own shades_text rule, now pub. shape.effects Current reads
shapes only, as the command applies glow to shapes only.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 04:41:41 +00:00
Reuben Grinberg 12545dd771 validate: scope diagram definition external DOCTYPE tolerance to SYSTEM 2026-11-28 22:17:00 -06:00
Martin BallandClaude Opus 5.5 c6d71b829a fix(formats): an ODT list item's later paragraphs stay in the item (repin regression) (#8089)
craft-libs 9c27cebc14 reads an ODT list item's further paragraphs as unnumbered
paragraphs marked ParaProps.list_item. WordCraft's ParaProps had no such field,
so the bridge dropped it and HTML/Markdown export restarted numbering after the
item. Add the field, same type and serde name as craft-wordmodel's.


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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 03:43:20 +00:00
Martin BallandClaude Opus 5.5 af26131063 fix(dialogs): Borders and Shading draws its preview at sample size (#7977) (#8088)
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 03:42:47 +00:00
Dylan M. Taylor 9b13180006 fix(nightly): enable Linux package_formats (including Flatpak) in signing policy (#8091) 2026-11-28 22:42:19 -05:00
Martin BallandClaude Opus 5.5 2ca5bf5dfa fix(options): Initials shows its default-initials placeholder again (#8018) (#8081)
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 03:41:59 +00:00
Martin BallandClaude Opus 5.5 1f6cf16029 fix(docx): a text box in a hyperlinked nested group survives an edit (repin regression) (#8087)
craft-libs 6a46b44449 keeps a hyperlinked nested group as a nested
InlineObject::Group. WordCraft looks one level deep, so prune_text_boxes
dropped the nested box's story on the first edit. The bridge now lifts nested
members into the parent group, offsets composed, as the reader does for
unlinked groups.


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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 03:39:45 +00:00
Martin BallandClaude Opus 5.5 18bbf00090 UI port: Customize Keyboard categories, Customize Ribbon layout, command search locations (#7671) (#8024)
* fix(keyboard): Customize Keyboard lists the ribbon tabs as Categories, in a dialog of set size (#7971)

Catalog commands carry their English ribbon location as a menu path; Categories are
the ribbon tabs (from ribbon::TABS), Contextual Tabs, Other and All Commands.

Partial: the Commands list still gets no room until the craft-libs fix (a7d6dcfcbb on
fix/7971-keyboard-categories-height) is synced to main and WordCraft repins.

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

* fix(ribbon): Customize Ribbon and Quick Access panes share the width (#7981)

Tab names are no longer truncated and Up/Down no longer overlap the list.

Partial: the lists are still unframed (craft-libs List has no frame option).

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

* fix(search): command search shows each command's ribbon location (#7983)

Partial: the shortcut per row and the popup width are not done.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 03:25:47 +00:00
Reuben Grinberg 5e4243bf2a validate: update observation and entry-loss contracts for rels owner completeness 2026-11-28 21:07:50 -06:00
Reuben Grinberg d80fb49267 validate: require complete archive discovery in rels XML-DOCTYPE owner gate 2026-11-28 21:07:50 -06:00
Reuben Grinberg 93ce16e0f7 validate: reconcile DOCTYPE observation-contract prose with EVIDENCE.md batch-4 totals 2026-11-28 20:43:12 -06:00
Reuben Grinberg c70841a895 validate: record #7735 batch-4 PUBLIC DOCTYPE measurements in EVIDENCE.md 2026-11-28 20:30:17 -06:00
Reuben Grinberg a27d6de7e1 validate: record #7735 batch-3 PUBLIC DOCTYPE measurements in EVIDENCE.md 2026-11-28 20:21:15 -06:00
Reuben Grinberg bed86ba38e validate: scope classificationlabels and webextension external DOCTYPE to SYSTEM 2026-11-28 20:12:01 -06:00
Reuben Grinberg a16543415e validate: clarify tolerated consumer coverage in EVIDENCE.md 2026-11-28 18:48:02 -06:00
Reuben Grinberg 1cf8870549 validate: require uniquely resolved owner for rels XML-DOCTYPE evidence 2026-11-28 18:46:11 -06:00
Reuben Grinberg 0b37a15d5d validate: record #7735 batch measurements in EVIDENCE.md and add tests
Record batches 1, 2a, and 2b (issue #7735 comments 7243358292,
7245685323, and 7246172147) in corpus/EVIDENCE.md with Windows and
Word for the web outcomes, noting Mac legs still owed and keeping
interim labelling on unmeasured cells.

Add integration tests covering every newly adverse cell group (batch 1
part roles, batch 2a part roles, batch 2b diagramData, batch 2a
story-owner rels, and batch 2a external rels) and asserting unmoved
cells stay put (diagram definitions external, chart-rels ATTLIST,
footnotes-rels ATTLIST, main-document rels ATTLIST).
2026-11-28 18:19:15 -06:00
Reuben Grinberg 9c84f895cb validate: grade measured #7735 DOCTYPE relationships cells as Error/Observed
Move the relationships DOCTYPE cells measured adverse in issue #7735
batch 2a (comment 7245685323) to Error/Observed:
- story-owner rels (header, footer, endnotes, comments): ATTLIST and
  external-identifier forms (refused on Word for the web; union rule)
- package rels (_rels/.rels), main-document rels, customXml item rels:
  external-identifier form (refused on Windows and web)
- chart-owner rels, footnotes-owner rels: external-identifier form
  (refused on Word for the web; union rule)

Unchanged cells:
- package, customXml item, and chart rels ATTLIST remain Error/Observed
  as shipped from the 2026-11-22–23 isolated series
- footnotes rels internal forms remain tolerated Warning/ByConstruction
- main-document rels ATTLIST remains Warning/ByConstruction (not
  measured in batch 2a; historical dtd-attlist.docx excluded from matrix)

Update the XML-DOCTYPE observation contract summary and regenerate
observation-contracts.md.
2026-11-28 18:15:43 -06:00
Reuben Grinberg cc2a5161c7 validate: grade measured #7735 DOCTYPE part-role cells as Error/Observed
Move the ATTLIST and external-identifier DOCTYPE cells measured adverse
in issue #7735 batches 1, 2a, and 2b (comments 7243358292, 7245685323,
and 7246172147) to Error/Observed:
- batch 1: header, footer, footnotes, endnotes, comments, glossary,
  chart, customXml item, core-properties
- batch 2a: commentsExtended, commentsIds, people, classificationlabels,
  webextension (union rule: web refuses labels and webextension)
- batch 2b: diagramData

Diagram definition parts (layout, colors, quickStyle) in external form
remain Warning/ByConstruction (tolerated on Windows and web).
2026-11-28 18:13:26 -06:00
FredApps e7587b4b1b Merge origin/main into codex/fix-1913-line-spacing
# Conflicts:
#	ROADMAP.md
#	crates/engine/src/cmd/design.rs
#	crates/ui-egui/src/backstage.rs
#	crates/ui-egui/src/file_dialogs.rs
#	crates/ui-egui/src/i18n/bg.tsv
#	crates/ui-egui/src/i18n/cs.tsv
#	crates/ui-egui/src/i18n/de.tsv
#	crates/ui-egui/src/i18n/es.tsv
#	crates/ui-egui/src/i18n/et.tsv
#	crates/ui-egui/src/i18n/fr.tsv
#	crates/ui-egui/src/i18n/hr.tsv
#	crates/ui-egui/src/i18n/hu.tsv
#	crates/ui-egui/src/i18n/it.tsv
#	crates/ui-egui/src/i18n/ja.tsv
#	crates/ui-egui/src/i18n/ko.tsv
#	crates/ui-egui/src/i18n/pl.tsv
#	crates/ui-egui/src/i18n/pt-br.tsv
#	crates/ui-egui/src/i18n/ru.tsv
#	crates/ui-egui/src/i18n/sr-latn.tsv
#	crates/ui-egui/src/i18n/sr.tsv
#	crates/ui-egui/src/i18n/sv.tsv
#	crates/ui-egui/src/i18n/tr.tsv
#	crates/ui-egui/src/i18n/uk.tsv
#	crates/ui-egui/src/i18n/vi.tsv
#	crates/ui-egui/src/i18n/zh-hans.tsv
#	crates/ui-egui/src/i18n/zh-hant.tsv
#	docs/target-app-parity.md
#	docs/ui-parity.md
2026-11-28 07:28:58 +07:00
8286638f79 fix(ui-egui): gallery symbols draw in Inter again without the font pack
Without the optional craft-fonts pack, where no installed font has them,
Home › Bullets drew boxes for ○ ▪ ◆ ✓ and Insert › Symbol for ✓ ★ ♥;
under kittest's strict missing-glyph policy the first of them panicked.
Before #7101 the interface's first face was WordCraft's own Inter, which
has them. The shared stack leads with the suite's Inter, the same 4.001
release cut to Latin, Greek and Cyrillic, and ui_fonts added none of
WordCraft's own faces behind it.

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

Co-Authored-By: GPT-6.2 Astra <noreply@openai.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 10:24:21 +10:00
FredApps bb26821f2e Merge origin/main into fix/3639-header-commands-own-section 2026-11-28 06:58:33 +07:00
FredApps b0a5ff0469 Merge origin/main into fix/mailings-csv-limits 2026-11-28 06:40:31 +07:00
FredApps 6e67ac4552 Merge origin/main into fix/3126-empty-window 2026-11-28 06:15:12 +07:00
FredApps ebc9505a02 Make select_object crate-visible for Enter on a picture.
The #4126 port called select_object from insert_break in text/unicode.rs
through a pub(super) re-export, but the function itself was only
pub(super) in objects/select.rs, so clippy failed on the private re-export.
2026-11-28 05:44:39 +07:00
FredApps 5fda6e6696 Merge origin/main into fix/arrows-enter-equation 2026-11-28 05:23:53 +07:00
FredApps 148987d098 Merge origin/main into fix/4126-enter-on-picture 2026-11-28 05:22:47 +07:00
FredApps eeac0d3322 Merge origin/main into fix/turkish-change-case-dotted-i 2026-11-28 05:18:24 +07:00
FredApps cac0dd2ee0 Merge origin/main into fix/3750-paragraph-marks 2026-11-28 04:59:15 +07:00
FredApps 5290f3bb62 Merge origin/main into fix/date-picture-quoted-literals-and-bare-a 2026-11-28 04:55:58 +07:00
FredApps ff781c42d2 Fix merge conflict markers left in docs/gaps.md 2026-11-28 04:52:27 +07:00
FredApps 262a821ec7 Merge origin/main into feat/docx-corpus-harness 2026-11-28 04:51:57 +07:00
FredApps e802ec8f28 Merge origin/main into fix/pdf-figure-object-lookups 2026-11-28 04:50:57 +07:00
batistalucasv dd2d40a5f5 test(icons): verify dictate.svg viewBox, attribute boundary, and 16-22 pt rendering 2026-11-27 08:36:52 -03:00
Daniele Mori 3e5c6ce405 Gap 4 note: with exact spacing, lowering past the height doesn't move the baseline further
Lowering a picture up to its height can still move an exact-spacing line's
baseline; only lowering beyond it changes nothing more (#6091 review).
2026-11-27 11:43:49 +01:00
Daniele Mori 3fe111cc9f Lowered pictures: the comment and the gap note say what layout does now
measure()'s comment still said layout limits a lowered picture to its height;
the line's baseline (#5796 review).
2026-11-27 11:43:39 +01:00
codeiouandClaude Opus 5.5 8aa24886da Fonts: a bold or italic check box draws every state in one face (#7863)
With a listed symbol family whose bold or italic face lacks one of the three ballot boxes, bold ☐
and ☑ came from that face and ☒ from the regular one, so a bold check box still changed font when
it was ticked. A ballot box now takes the family's bold or italic face only when that face has all
three, as the regular face does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 19:56:33 +10:00
codeiouandClaude Opus 5.5 2114b003ef Fonts: a check box keeps one face when a symbol font loads during its fallback search (#7863)
The ballot-box choice read the face count after its search, so an answer found while another
thread loaded a listed family the search had already passed was cached for the new count: ☐ kept
the later face while ☑ and ☒ took the earlier one. The count is now read before the search, as
the fallback caches need, so such an answer is returned but not cached.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 19:55:53 +10:00
codeiouandClaude Opus 5.5 c70411808d Fonts: a check box's ticked and unticked symbols come from one face when its font isn't installed (#7863)
A ballot box (U+2610 to U+2612) the run's face lacks now takes the first of the
symbol faces (word::SYMBOL: Apple Symbols, Segoe UI Symbol, DejaVu Sans, Noto
Sans Symbols, Noto Sans Symbols 2...) that has all three, before the UI
fallback, as an uncovered black circle takes Times New Roman. Source Sans 3,
the UI fallback, has the unchecked box (with a drop shadow) and the ticked one
but not the crossed one, so a check box whose font (MS Gothic by default) isn't
installed changed font when it was ticked. A run of only ballot boxes (graphic
text) takes the same face.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 19:55:53 +10:00
codeiouandClaude Opus 5.5 e129211603 Comments pane: long comments and replies wrap in their fields (#7906)
Since the port to the craft framework both fields in the Comments pane
were TextField::lines(1).max_lines(COMMENT_ROWS). A craft field is
multi-line only when lines is above one, and max_lines applies only to
a multi-line field, so every comment, reply and reply being written sat
on one line, cut off at the card's edge.

Both fields now start at two lines, the fewest a wrapping field has, and
grow with their text up to the ten-line cap, then scroll (#3382). They
also take the card's width, as they did before the port: a multi-line
field counts its lines at the width it is offered, so one drawn at its
own, narrower length came out lines short of its text.

Comment edits are unchanged: typing stays a draft and leaving the
field writes it once. Premature and duplicate reply posting is #7907,
fixed separately. As in any multi-line field, Enter starts a new line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 19:37:25 +10:00
batistalucasv 91a52f278c test(widgets): restore the_typed_list_shows_on_the_frame_of_the_keystroke test (#7317) 2026-11-27 01:51:22 -03:00
batistalucasv 80c5151ab3 Address review feedback: drop unrelated backstage.rs region change (#4981) 2026-11-27 01:18:07 -03:00
batistalucasv b4b41e038d Use full app harness and press helper in hyperlink shortcut test (#7317) 2026-11-27 01:04:43 -03:00
batistalucasv 6637fb7bbf Merge remote-tracking branch 'upstream/main' into test/7317-hyperlink-shortcut-focuses 2026-11-27 01:00:33 -03:00
batistalucasv 5e8c7cb7cb Address review feedback: drop racy CHOSEN tail check in settings_dir test (#7317) 2026-11-27 00:48:27 -03:00
batistalucasv ee05e88fa0 Address review feedback on dictate icon test (#7450) 2026-11-27 00:27:40 -03:00
batistalucasv 81aae389b3 Icons: adjust Dictate microphone icon geometry to prevent capsule cutting across U-stand (#7450) 2026-11-27 00:25:15 -03:00
Martin BallandClaude Opus 5.5 8803a95a2d #7171: Print settings buttons stay clear of the scroll bar and the preview
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 02:18:15 +00:00
batistalucasv 2c08518c6f perf(ui-egui): extend perf_probe with synthetic workload, RSS/HWM memory, and DrainRenderer (#7898) 2026-11-26 21:50:05 -03:00
Martin Ball 4a4b37c255 Merge main into #7555 (resolve test-file conflict, keeping both sides) 2026-11-26 23:29:50 +00:00
codeiouandClaude Opus 5.5 adef1253bb Docs: the control protocol lists the methods and parameters the channel takes since #7101
The craft framework port (#7101) moved synthetic input and dialog answers to craft-automation, but docs/control-protocol.md kept the old names: ui.press, ui.drag and ui.text reply "unknown command", and cmd, the wheel units point, line and page, and phase are refused. The Methods table now gives the methods and parameters main answers and adds the ones it lacked. It also corrects the screenshot reply (base64), the input reply (null once the input is processed), the 30 s idle close, the ui.language values and the ui.paneDock panes. docs/typing-parity.md's How to compare now names ui.type, and the control module's docs no longer say that a screenshot replies with png. A test sends every method in the table through the control handler and fails on one the channel doesn't answer; it reads the doc line by line, so a checkout with CRLF line endings passes too.

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 07:55:54 +10:00
jayzed80 16ec8d91ce Merge remote-tracking branch 'upstream/main' into HEAD
# Conflicts:
#	crates/ui-egui/src/printing.rs
#	crates/ui-egui/tests/it/native_print.rs
2026-11-26 18:47:03 +00:00
jayzed80 be2d9021bf Merge remote-tracking branch 'upstream/main' into HEAD
# Conflicts:
#	crates/ui-egui/src/app/commands.rs
2026-11-26 18:46:56 +00:00
codeiouandClaude Opus 5.5 6078524793 Content controls: a chosen entry or date takes the control's formatting
An entry chosen from a drop-down list or combo box, or a date set in a
date picker, in place of the control's placeholder kept the
placeholder's formatting minus its style: in a form whose placeholders
are grey and boxed, the values stayed grey and boxed, on the page and in
the saved file. Text typed over the placeholder has taken the control's
own run properties (w:sdtPr/w:rPr, ECMA-376 §17.5.2.27) since #3116.

The typing path's rule moves, unchanged, into replacement_props, and
Choose List Item, Set Date and Toggle Check Box use it too (a file can
mark a check box as showing its placeholder). A control that already
holds a value keeps that value's formatting, as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 01:45:54 +10:00
codeiouandClaude Opus 5.5 3f9fc816bf Fonts: a combining mark its letter's font lacks is drawn with the letter in a face that has both (#7865)
A combining mark the face of its letter couldn't draw was shaped in that face anyway and
drawn as the face's missing-glyph box (∞ with U+0338 in Source Serif 4, or in Carlito for a
Calibri run), and strict export refused the file. segment_keys now keeps a mark with its
letter only while that face draws it, or composes the pair (= with U+0338 is ≠). Otherwise
the letter and its marks go together to a face that draws them all, as CSS Fonts 4 §5.3
(cluster matching) describes. With no such face, a mark in left-to-right text that isn't
complex script is drawn on its own from a face that has it; in right-to-left and
complex-script text it stays with its letter, so harakat are never split from their letter.
A cluster is matched once, at its first mark the face lacks, so a long run of marks lays out
in linear time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 01:37:35 +10:00
batistalucasv d729387c8c test(ui-egui): restore closing_the_backstage_ends_its_keytips (#4981)
Port and restore lost regression test closing_the_backstage_ends_its_keytips
under #7317 (originally tracking #4981, data-loss category).

When Backstage opened post-#7101, keytips ceased execution because keytips::show
was previously nested within ribbon_slot. Because AppShell skips the ribbon slots
while Backstage is active, Keytips component state remained frozen across frames.
When Backstage subsequently closed, Keytips resumed in Phase::Commands, leaving
keytips active and swallowing subsequent canvas keystrokes (such as C closing the document).

This change:
1. Lifts Keytips invocation out of ribbon_slot and into WordApp::show_overlays,
   preserving a stable component root across ribbon, Backstage, and chrome modes.
2. Caches RibbonOutput in WordApp across passes, passing empty output when Backstage is open.
3. Fixes Backstage inspected region Id to match crate::keytips::backstage_region().
4. Tracks Backstage keytip exit via wc_backstage_keytips_active, ensuring Keytips
   resets to Phase::Off immediately when Backstage is closed.
2026-11-26 11:50:35 -03:00
codeiouandClaude Opus 5.5 c7b21e5d02 Content controls: the page keeps the keyboard when a list closes or a check box is ticked (#7862)
A content control's list or date button and its check boxes sensed only
clicks. craft's press focus takes such a press as one that acts without
taking focus, which moves focus off a focused text part to its pane; the
page has none, so the press left nothing focused. The list then had no stop
to give focus back to: after a pick or Escape, and after a tick, the access
tree's focus was the window, not the document.

Both parts now sense KEEP_FOCUS, as craft's own buttons that act for a
focused field do (the combo box arrow, the date picker button). The press
leaves the page focused, and a list or calendar opened from it gives the
focus back to the page when it closes.

Tests: closing_the_list_gives_the_keyboard_back_to_the_page (Escape and a
pick) and ticking_a_check_box_leaves_the_keyboard_with_the_page check the
framework's focus and the access tree's; both fail without the change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 00:40:44 +10:00
batistalucasv 273d2ed225 test(control-key): restore test for settings_dir_is_the_apps_folder (#7317) 2026-11-26 10:21:40 -03:00
dotCooCoo bdf3c54189 i18n audit: check egui's warning only in builds that draw it
egui draws its PERF WARNING text only when built with debug_assertions, so the test asserts its presence only in those builds.
2026-11-26 00:12:56 -08:00
batistalucasv 6a445b341a test(table_resize): address review feedback and combine #7586 2026-11-25 14:49:00 -03:00
batistalucasv 958dd78ceb test(ui-egui): speed up hyperlink_shortcut_focuses_address_and_preserves_document 2026-11-25 12:48:06 -03:00
Fluorine 0b7bdee856 Format layout cache regression test 2026-11-25 04:34:40 -04:00
Mauro MazzieriandClaude Opus 5.5 8be58e3a21 #2221: merge main
Resolves the conflict with #7746 in apps/wordcraft/src/main.rs: main's
services(.., nightly) call, then this change's block unchanged. Merged without
a maintainer's request because the pull request could not be merged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 09:29:47 +01:00
Kevin Joseph 8654ed1319 Merge remote-tracking branch 'origin/main' into fix/footnote-continued-bottom
# Conflicts:
#	docs/layout-parity.md
2026-11-24 09:46:34 +01:00
Joseph Anglada 8e7fca10b4 Ignore egui performance warnings in i18n audit 2026-11-23 19:51:17 -04:00
Fluorine b83864e0f4 Merge remote-tracking branch 'upstream/main' into HEAD 2026-11-23 18:27:17 -04:00
fluorineandClaude Haiku 5.5 e39281dce7 xtask: import the stats walk test helpers only where the unix-only test uses them
On Windows the unix-only test was compiled out, so its imports were unused and cargo xtask ci failed at clippy.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-23 15:47:00 -04:00
Fluorine 60ec8580cd Merge commit '7fd0136bc8e643b08977b8692eb9867c992472ea' into sync-pr-6213 2026-11-23 13:51:41 -04:00
Joseph Anglada ac306cf704 Fix rustfmt in off-paper cursor test 2026-11-23 11:15:35 -04:00
fluorineandClaude Haiku 5.5 0ac9cbfba9 Merge main into cursor-arrow-off-paper
The UI port (#7101) moved the press and cursor code into canvas/input.rs and removed ibeam.rs. The cursor fix now lives in PageTextTool::cursor. The test harness for the grey-area test is the shared one, which installs the app's command set.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-23 10:18:15 -04:00
dotCooCoo 488f75b6e0 Merge main into fix/i18n-audit-egui-warning 2026-11-23 06:07:40 -08:00
dfgodvan d45c07368f Layout: a picture alone in multiple spacing fits at the page foot by itself; a list label adds no leading below it
Merge main. Its rule for the leading below a picture alone on its line,
(m - 1) x the natural height of the picture run's font, matches Word for
Mac 16.93, so this branch's rule from the paragraph mark's font is dropped
and `line_spacing_does_not_scale_pictures` is main's again.

Kept: at the foot of a page such a line stays as soon as the picture fits
above the bottom margin; the spacing and the font's descent run into it.
Word, a 56.7pt picture in 1.5-spaced 12pt text: stays with 57-59pt of
room, which main moved on.

Fixed: a list label's font no longer adds to that leading. Word, a 144pt
picture at 1.25 spacing: 3.60pt below it without a label and with a 24pt
one, where main gave 6.90pt.
2026-11-23 13:56:06 +03:00
Mauro Mazzieri dd3d3040ac #2221: a window drawn in software stops the animations that follow the system 2026-11-23 11:46:39 +01:00
dfgodvan ed0fe0d980 Merge main into fix/kept-paragraph-space-after-before-table 2026-11-23 13:09:17 +03:00
dotCooCoo 03da178335 i18n: the interface audit skips egui's debug PERF WARNING
In debug builds egui draws "egui PERF WARNING: request_discard has been
called N frames in a row" over the app when a frame takes extra passes
three frames running. untranslated_interface_text read that line as
interface text and failed on it after some Home tab clicks, on both the
macOS and Windows gate legs, for pull requests that do not touch the
interface.

The audit's text collectors (frames and frame_at) now leave out text
that starts with "egui PERF WARNING:". A new test makes egui draw the
warning and checks that the audit does not collect it.
2026-11-22 22:48:20 -08:00
batistalucasv 8ee16cc876 test(table_resize): restore alt_column_widths_are_in_the_regions_unit test (#7317) 2026-11-23 01:03:35 -03:00
ljkx 7777eba6e4 Merge remote-tracking branch 'origin/main' into fix/createdate-keeps-date
# Conflicts:
#	docs/layout-parity.md
2026-11-23 03:04:48 +01:00
batistalucasv b1958ac483 test(ui-egui): restore hyperlink_shortcut_focuses_address_and_preserves_document test (#1610) (#7317) 2026-11-22 21:56:38 -03:00
pakiat dfbeffd34a Merge commit 'c369c3a20befef8742f8913128cacd79002435d6' into m/6941
# Conflicts:
#	docs/layout-parity.md
2026-11-23 07:41:25 +07:00
midasmatterhorn 4722d7d2fe A Top-and-Bottom object in a paragraph's space before pushes it down
Exclusions were relative to the first line's top and dropped when they
ended above it, so an object wholly inside the paragraph's space
before never moved the paragraph; and when an object reached into the
first line, the line moved to the object's bottom without the space
before being laid out again under it. Exclusion filtering keeps
Top-and-Bottom areas above the first line now, and the line breaker
looks one space before above its top for them and starts the line
below the object plus the space before. Objects in the previous
paragraph's space after stay where they were.
2026-11-22 00:02:35 +03:00
midasmatterhorn 81a367be13 German date fields use German month and weekday names
date_names mapped only Portuguese, so a de-DE DATE field rendered
English months and weekdays and defaulted to M/d/yyyy. German joins
the table (de-DE, de-AT, de-CH): full names, Word's short forms for
MMM and ddd (Mrz, the two-letter day forms), and dd.MM.yyyy when a
field carries no picture. The short names are explicit per-language
arrays now, so Portuguese and English keep exactly the first-three-
letter forms they had.
2026-11-21 23:24:12 +03:00
Mauro MazzieriandClaude Opus 5.5 989fa17544 Merge main into claude/continuous-section-first-page-header (#5543)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 18:52:40 +01:00
pakiatandClaude Opus 5.5 eccf146bca Merge Formatting keeps the emphasis a character style gives, not a paragraph style's
Measured in Word for Windows (Paste with Merge Formatting, PasteAndFormat
20): bold, italic, underline and strikethrough from the source's
character style are kept as direct formatting, for Latin and for Thai in a
w:cs run; a paragraph style's are dropped. Merge Formatting now judges a
run's emphasis by its own formatting over its character style chain, and
still not by the paragraph style.

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 06:40:13 +07:00
Michael Higgins ce2f7789f4 Merge storytold/wordcraft main into fix/6516-toggle-first-character 2026-11-20 17:05:13 -05:00
Michael Higgins 539d9ce9d6 Merge storytold/wordcraft main into fix/6517-typographic-apostrophe-word 2026-11-20 17:05:09 -05:00
Michael Higgins ccf6340262 Merge storytold/wordcraft main into fix/6517-typographic-apostrophe-word 2026-11-20 09:45:38 -05:00
FredApps b8c2fa4962 Merge main into Latin text ordering in RTL paragraphs 2026-11-20 09:30:39 +01:00
Rees 7dbf9050e6 #3614: reconcile PDF figure lookups with current main 2026-11-20 06:12:23 +01:00
dfgodvan 41f4118d0e Merge branch 'main' into w1/break-after-any-space 2026-11-19 23:23:59 +03:00
dfgodvan 41e2164cd0 Merge branch 'main' into w1/list-number-no-kern 2026-11-19 23:22:36 +03:00
dfgodvan 273451b528 Merge main into fix/kept-paragraph-space-after-before-table 2026-11-19 23:21:17 +03:00
dfgodvan 861bed3fdd Merge main into fix/legacy-tables-at-page-foot 2026-11-19 23:17:29 +03:00
dfgodvan 31aa5a1b00 Merge main into fix/kept-paragraph-before-table-start 2026-11-19 23:15:53 +03:00
jayzed80 6010893891 Merge branch 'agyreview/6446' into HEAD
# Conflicts:
#	crates/ui-egui/src/app/commands.rs
2026-11-19 16:25:25 +00:00
jayzed80 8427de0edb Address review: require explicit path for copies and compare host copy basename (#6131) 2026-11-19 16:14:05 +00:00
jayzed80 1789fd7b4d #6463: an all-blank row keeps its TR and cells in a tagged table 2026-11-19 16:07:59 +00:00
jayzed80 83676d584a Merge remote-tracking branch 'upstream/main' into fix/pdf-table-tags-6463 2026-11-19 15:49:47 +00:00
jayzed80 ec29711caf Merge branch 'agyreview/6628' into HEAD
# Conflicts:
#	docs/layout-parity.md
2026-11-19 10:25:31 +00:00
jayzed80 2bce6ed613 Docs: qualify wrapped-tab float-skip parity entry with 50-span limit (#6577) 2026-11-19 10:09:54 +00:00
jayzed80 b922877d1f Docs: the automatic-space row names the snapToChars grid that drops it (#6584) 2026-11-19 04:31:04 +00:00
jayzed80 03b20a6ca9 #6577: limit the clear-of-float tab skip to stops past the right indent
A left tab whose stop is inside the right indent but past a span narrowed
by a float could take the new skip too, moving its text to a line clear of
the object. The guard now also requires the stop to be past the paragraph's
right text edge, which is the scope the change describes.

Test: a_left_tab_inside_the_right_indent_beside_a_float_keeps_its_line.
The parity row no longer claims the Word comparison was made.
2026-11-19 03:54:39 +00:00
jayzed80 e27a3bbdfc Merge upstream/main into fix/tab-past-indent-float-6577 2026-11-19 03:40:46 +00:00
jayzed80 c93359d997 Merge remote-tracking branch 'upstream/main' into fix/export-copy-6131
# Conflicts:
#	crates/engine/src/cmd/file.rs
#	crates/engine/src/tests.rs
#	crates/ui-egui/src/app/commands.rs
#	crates/ui-egui/src/file_dialogs.rs
2026-11-19 00:11:41 +00:00
jayzed80 0ef496019a Merge remote-tracking branch 'upstream/main' into fix/odt-tall-header-5806
# Conflicts:
#	crates/formats/src/odt/import.rs
#	crates/formats/src/odt/tests_more/headers.rs
2026-11-18 22:51:11 +00:00
jayzed80 2d3e10a693 Merge remote-tracking branch 'upstream/main' into fix/doc-grid-lines-and-chars-6584
# Conflicts:
#	crates/layout/src/tests/autospace.rs
#	docs/layout-parity.md
2026-11-18 21:59:29 +00:00
jayzed80 2e9699c519 Merge remote-tracking branch 'upstream/main' into HEAD
# Conflicts:
#	docs/layout-parity.md
2026-11-18 21:30:04 +00:00
pakiat 514a95b80f Merge commit '6ef13b2cc8a60e6391d7a5b92459ec47598d58a9' into m/6941
# Conflicts:
#	docs/gaps.md
2026-11-18 22:32:58 +07:00
Kevin Joseph 4afcb2812f docs: widow/orphan control in a split footnote, and the page's first note that gives it up 2026-11-18 15:58:28 +01:00
Kevin Joseph 834c8054cf Footnotes: the beneath-text test asserts the separator's gap; docs say the bottom margin is for page-bottom notes 2026-11-18 15:48:40 +01:00
Kevin Joseph 540bd57931 Layout: a page of continued notes is aligned once, before its notes go on it
A centred or bottom-aligned section whose last note continued over pages of notes alone moved
each such page down again when the next one started, its notes past the bottom margin.
finish_pages now finishes every page through finish_page, which aligns it and then leaves it
top-aligned. Tests: the bottom-margin test also runs with widow control and checks every note
line is placed once; a note beneath the text stays under it when it continues.
2026-11-18 14:22:41 +01:00
Kevin Joseph 11790205d1 Merge remote-tracking branch 'origin/main' into fix/footnote-continued-bottom
# Conflicts:
#	docs/layout-parity.md
2026-11-18 14:04:31 +01:00
dotCooCoo 741d74b3fa Charts: number formats keep a trailing space that is part of the code
clean_fmt trimmed every space at the end of an axis or series number
format, so "0_ " was stored as "0_". In a number format, `_`, `*` and
`\` take the next character as their operand, and a space inside quotes
is literal text, so those trailing spaces are part of the code. They now
stay; other spaces at the ends and control characters are still removed.
This is the same change as craft-libs' wordmodel clean_fmt in
storytold/craft-libs#2180.
2026-11-18 01:08:34 -08:00
dotCooCoo b73210feeb DOCX: a frame shape in a note separator opens as a rectangle
A footnote or endnote separator is now converted through the same block
mapping as the body, so a picture frame shape in a separator opens as a
rectangle. Before, the file failed to open with "unknown variant `frame`".
2026-11-17 22:46:40 -08:00
jayzed80 0837c9dac5 #6837: native print asks the printer for the document's own paper
With No Scaling, the print job carried no media option, so the spooler
used its default paper and an A5 document printed on A4. Send the PWG
media name of the first printed sheet when it is a Layout > Size paper;
a Scale to paper size choice still wins.
2026-11-18 03:24:07 +00:00
FredApps b92b7a40ad Merge remote-tracking branch 'origin/main' into fix/fit-one-page-freebsd
Signed-off-by: FredApps <FredApps@users.noreply.github.com>

# Conflicts:
#	crates/engine/src/tests/fit_one_page.rs
2026-11-18 09:51:35 +07:00
pakiat 01b9ce4b81 Merge commit '22a73d9f2d10de6ee52780ab4a6019b864d9c598' into m/6941
# Conflicts:
#	docs/gaps.md
2026-11-18 06:09:07 +07:00
Diego Guerini 90a6722453 Merge remote-tracking branch 'upstream/main' into rtl-numbers-latin
# Conflicts:
#	ROADMAP.md
#	crates/layout/src/para.rs
#	docs/gaps.md
#	docs/layout-parity.md
#	docs/target-app-parity.md
2026-11-17 19:03:09 +01:00
Martin Ball af9dca95de Merge branch 'main' into fix/right-tab-beyond-indent 2026-11-17 16:59:34 +01:00
Mauro MazzieriandClaude Opus 5.5 6eb03bf4ea Merge storytold/wordcraft main
Resolves the docs/layout-parity.md status line and revision history.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JesQG7ckr7g2qSfBwGkTqM
2026-11-17 15:50:22 +00:00
Michael Higgins 9d005a6a40 Merge branch 'fix/6516-toggle-first-character' of https://github.com/Higgs32584/wordcraft into fix/6516-toggle-first-character 2026-11-17 09:58:23 -05:00
dotCooCoo 0bef53685f Mail merge: note that an ODS float merges its value, not its formatted text 2026-11-17 06:41:27 -08:00
Michael Higgins f0b5298dc4 Merge storytold/wordcraft main into fix/6517-typographic-apostrophe-word 2026-11-17 09:35:35 -05:00
Michael Higgins 95d1c1b4be Merge storytold/wordcraft main into fix/6516-toggle-first-character 2026-11-17 09:35:27 -05:00
pakiatandClaude Opus 5.5 b946229d38 Tables: a right-to-left table keeps its cell margins on the sides they name
Measured in Word for Windows 16.0.20527 (modes 14 and 15): in a
w:bidiVisual table a cell's w:left margin stays on its left and w:right on
its right, the cell's (w:tcMar) and the table's (w:tblCellMar) alike, and
w:start/w:end the same. Only the cell's left and right borders are drawn
mirrored. WordCraft mirrored the margins as well, so text in a cell with
unequal margins started 6 to 18 pt off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 21:20:23 +07:00
fluorine 5c9c343e46 Layout cache test: the hit bound allows for kept headings that fall to the next page 2026-11-17 09:47:40 -04:00
dotCooCoo b664721fb1 Mail merge: test that an ODS date with two zones reads its text
An OpenDocument date cell whose office:date-value ends in both an
offset and Z, in either order, reads as the cell's text through
read_rows. A date with one offset still reads its value.
2026-11-17 05:06:52 -08:00
dotCooCoo 1abb47e788 Mail merge: a date value with two timezone suffixes is rejected
A time that ends in both an offset and Z (13:45:00+02:00Z) now falls
back to the cell text instead of reading as 13:45. A zone offset must
be two-digit hh:mm, so +2:00 also falls back. The table test unwraps
craft_ods::testing::spreadsheet, which returns a Result since the
craft-libs update on main.
2026-11-17 05:00:50 -08:00
Martin Ball 9e8732bd85 Merge branch 'main' into fix/turned-text-at-least-rows 2026-11-17 13:44:00 +01:00
Martin Ball c210ef5093 Merge branch 'main' into toc-insert-caret-position 2026-11-17 13:43:28 +01:00
Martin Ball 2c7df2fb96 Merge branch 'main' into fix/ods-typed-values 2026-11-17 13:43:03 +01:00
Martin Ball 4c0b520a53 Merge branch 'main' into cursor-arrow-off-paper 2026-11-17 13:42:52 +01:00
Martin Ball 370489a59b Merge branch 'main' into fix/frames-in-cells 2026-11-17 12:33:37 +01:00
Martin Ball 783d2ce93e Merge branch 'main' into w1/break-after-any-space 2026-11-17 11:54:33 +01:00
Martin Ball f2c9880298 Merge branch 'main' into w1/list-number-no-kern 2026-11-17 11:36:41 +01:00
Martin Ball 1392290eec Merge branch 'main' into fix/right-tab-beyond-indent 2026-11-17 08:53:46 +01:00
Martin Ball fd7461b295 Merge branch 'main' into toc-insert-caret-position 2026-11-17 08:40:05 +01:00
Martin Ball afaea9484c Merge branch 'main' into fix/ods-typed-values 2026-11-17 08:26:51 +01:00
Martin Ball b2964c2c1c Merge branch 'main' into fix/frames-in-cells 2026-11-17 07:54:18 +01:00
Martin Ball 6f7b6f2d87 Merge branch 'main' into w1/break-after-any-space 2026-11-17 07:41:38 +01:00
Martin Ball 609aa80e5e Merge branch 'main' into fix/6516-toggle-first-character 2026-11-17 07:25:19 +01:00
Martin Ball cdec6b459f Merge branch 'main' into w1/list-number-no-kern 2026-11-17 07:23:13 +01:00
Martin Ball 3310e9f5ee Merge branch 'main' into fix/right-tab-beyond-indent 2026-11-17 05:33:56 +01:00
Martin Ball b1e6d1fa22 Merge branch 'main' into toc-insert-caret-position 2026-11-17 05:32:28 +01:00
ljkx 554a7d689e #6331: CREATEDATE reads a creation date without seconds
W3CDTF allows hh:mm without seconds (2019-05-05T12:00Z), which
parse_from_rfc3339 refuses, so such a file kept its cached result.
created_at now reads that form too, with Z or an offset.
2026-11-17 04:32:55 +01:00
ljkx 2c32076416 #6331: layout-parity status line and revision row for CREATEDATE at the top 2026-11-17 04:32:54 +01:00
ljkx 19b8dfece6 Merge remote-tracking branch 'upstream/main' into fix/createdate-keeps-date 2026-11-17 04:32:14 +01:00
Reuben Grinberg 0b1117c87f Merge remote-tracking branch 'upstream/main' into HEAD 2026-11-16 21:19:57 -06:00
Reuben Grinberg 110852a379 docs: gaps.md — record the terminal-paragraph compare limitation (#3750) 2026-11-16 20:34:10 -06:00
Reuben Grinberg 17b26e39cc Compare: rename the section reject pin to match its assertion; add the accept-side pin (#3750) 2026-11-16 20:34:10 -06:00
NetterSilverandClaude Sonnet 5.5 5653188ede test: budget the steps of reconcile_objects in the marker regression test
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 03:01:12 +01:00
Michael Higgins 82567c2c61 Merge storytold/wordcraft main into fix/6517-typographic-apostrophe-word 2026-11-16 08:50:04 -05:00
Michael Higgins 376a714e73 Merge storytold/wordcraft main into fix/6516-toggle-first-character 2026-11-16 08:50:01 -05:00
FredApps 37caf16978 Tests: two Fit One Page tests find where the document spills
A plain document asks for Aptos, which no test machine has, so its
sans stand-in differs between machines: DejaVu Sans on FreeBSD is
larger than the Linux runners' font. With fixed line counts the step
and budget tests overflowed by more than the fit may recover there,
and have failed every FreeBSD night since they were added. They now
take the most lines that fit and move the last paragraph to page 2
with space before it, so the overflow is under half a point anywhere.
2026-11-15 23:07:00 +01:00
dotCooCoo 9a81b9a88d Mail merge: an ODS zone offset past 14:00 falls back to the cell text
A date or time zone offset is at most 14:00, as XML Schema allows, so `2024-03-05+14:01` and `13:45:00-15:00` keep the cell's text, and `+14:00` still reads.
2026-11-14 13:42:45 -08:00
dotCooCoo 100dfb3c42 Mail merge: ODS dates keep a zone-suffixed date, and leap seconds and an empty T fall back
A date alone may carry a Z or +hh:mm zone, which is left out. A leap second (23:59:60) and a duration with nothing after T (P1DT) are not times, so the cell's text is used.
2026-11-14 13:28:01 -08:00
dotCooCoo e88b44df12 Mail merge: OpenDocument cells read their typed values
An OpenDocument recipient list showed each cell's displayed text
whenever it had any, so dates, times, floats and booleans came out in
the file's locale format, and a covered cell showed its hidden text.

Floats and booleans read their values again, dates and times read as
ISO 8601 (a duration's days counted as hours), strings, percentages
and currencies keep their text, and a covered cell is blank. A value
that is not a valid date, time or duration falls back to the text.
2026-11-14 13:12:47 -08:00
dfgodvan a03571dea8 Line breaks: a line may break after any space, before closing punctuation or after an opening bracket, as in Word
UAX #14 keeps a space with the closing punctuation or bracket after it (LB13:
"x :=", "false );") and an opening bracket with the space after it (LB14:
"( word"), so the word before the space went to the next line with it. Word
breaks at the space whatever follows it.

Tests: a_line_breaks_after_a_space_before_closing_punctuation,
a_line_breaks_after_the_space_of_an_opening_bracket (both fail before this
change).
2026-11-14 19:16:11 +03:00
dfgodvan bc0c9e4da5 Lists: a list number is never kerned, as in Word
A list number took the kerning of its paragraph mark or level. Word never kerns
it: "11)" in Times New Roman 12 pt with kerning on is 16 pt wide in Word, not
the 15.55 pt of the kerned digits, so it passes a hanging indent the kerned one
would fit in and the text moves on to the next tab stop.

Test: a_list_number_is_never_kerned (fails before this change).
2026-11-14 19:16:10 +03:00
jayzed80 8ac3002653 Layout: a linesAndChars document grid keeps automatic spacing, as Word has it (#6584)
Only snapToChars drops the automatic space between Asian text and Latin text or digits; Word lays out linesAndChars exactly as a line grid for it.
2026-11-14 06:53:45 +00:00
jayzed80 7f8283a77f Layout: a left tab past the right indent beside a float moves clear of it (#6577)
A left tab whose stop is past the right indent wraps to start the next
line. When that line was the span on a floating object's far side, the
tab took no room there and its text started beside the object. Like
Word, the tab now goes on to the first line clear of the object, where
its text starts at the indent.

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

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

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 10:48:08 -05:00
Reuben Grinberg 0345dd28f3 Compare: mark_block doc — the section-carrying case is fixed on main (#5734), not a limitation 2026-11-13 08:54:06 -06:00
Reuben Grinberg 959bc54505 rustfmt: collapse the flipped pin assertion onto one line 2026-11-12 17:01:18 -06:00
Reuben Grinberg 791e144fd7 Compare: flip the inserted-section pin to the fixed behaviour (#5667, fixed on main by #5734) 2026-11-12 17:01:18 -06:00
Reuben Grinberg 6ce224d4b3 Compare: keep another author's deletion stamp on whole-marked paragraphs
Address benandez's review: the del closure in mark_block now uses get_or_insert so a paragraph already carrying another author's tracked deletion keeps that author's revision on its runs and its mark; the ins closure deliberately keeps overwriting (the revised side is a raw clone whose revision indices are never relinked — see the comment; that sourcing is the #5571 root cause). p.touch() after mutating an empty paragraph's mark. Characterization tests pin the terminal-paragraph limitation and the section-break resolve limitation (the resolve fix is filed separately).
2026-11-12 17:01:18 -06:00
Reuben Grinberg 20b8ce57a8 Compare: mark a whole inserted/deleted paragraph's mark (#3750) 2026-11-12 17:01:18 -06:00
dfgodvan f4862c6b0e Line spacing: a multiple adds a multiple of the tallest run, not of a mixed line
A line mixing fonts is as tall as the tallest ascent over the deepest descent of its runs, more
than any one run's own height. At multiple spacing Word adds (m - 1) x the tallest run's own
height to it, not (m - 1) x the mixed line's: 10pt Times New Roman with a 10pt Courier New run
steps 18.09pt at 1.5 spacing and 23.84pt at double in Word for Windows, where multiplying the
12.34pt line gives 18.51 and 24.68; in Word for Mac the 12.24pt line steps 17.97 and 23.69pt
(12.24 + 0.5 x 11.49 and + 11.49, Times New Roman being the taller run). The paragraph mark's
font doesn't matter.

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

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

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

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

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

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

Test: a_word_broken_by_letters_ends_without_its_kerning_pair (fails before this change).
2026-11-12 23:46:48 +03:00
dfgodvan 40810c50de Layout: an inline picture is as high as its whole twips, as in Word
Word keeps a picture's height in whole twips and drops the rest of the EMUs: 2661310 EMU
(209.552pt) is drawn 209.55pt high, and at the foot of a page only that has to fit above the
bottom margin. Word for Mac: a picture of 14170.998 twips stays where one of 14171 twips moves
on, at single and 1.5 spacing.

Test: a_picture_is_as_high_as_its_whole_twips_and_fits_by_them_at_the_page_bottom (fails
before this change).
2026-11-12 23:42:32 +03:00
dfgodvan 979077101f Layout: tables at the foot of a page before Word 2013 layout
Measured in Word for Mac with synthetic documents in compatibility modes 12
and 14 (and a document that doesn't state one): a row split across pages
divides its cells' text at any line, with no widow/orphan control in the
cells; the repeated header rows stay alone at the foot of a page when no line
of the first row fits under them; and a paragraph kept with the table keeps
with the header rows only (and the border below them, as placing them needs).
Mode 15 (Word 2013 layout) is as before.
2026-11-12 23:22:02 +03:00
dfgodvan 3d04c471a4 Layout: a paragraph kept with a table counts its space after
The table starts below the space after the paragraph before it, so a
paragraph kept with a table needs that space too, as Word has it: with 12 pt
after a caption, Word moves the caption with the table once the header row and
the start of the first row don't fit under the caption and its space after
(measured in Word for Mac, compatibility modes 12 and 15).
2026-11-12 23:21:55 +03:00
jayzed80 9f34d3790e ODT: a header as tall as the page leaves the text room (#5806)
A header's fo:min-height raised to the page height made the text's top
margin the bottom of the page, so each page drew one line off the paper
and the rest of the body was lost from the render and PDF. Header and
footer bands now grow the margins only while the text keeps half an
inch, as Page Setup's margins must; the smaller band is kept whole.
2026-11-12 20:19:30 +00:00
dfgodvan 69578bbc6f Layout: a kept paragraph fits by itself where its last line's text does
Keep with next moves a paragraph only when it fits on the page by itself, and
that check took its whole height, while placing the lines lets the last
line's extra leading (multiple spacing above single) run into the bottom
margin. A double-spaced caption whose text ends above the margin then stayed
alone at the foot of the page, its table on the next. Word moves it with the
table (measured in Word for Mac: Times New Roman 12 pt, double spacing, the
caption 0, 4 and 8 pt below 52 exactly 12 pt lines; not kept, it stays on
page 1). The check now uses the fit the lines are placed with (`fit_height`).
2026-11-12 23:18:00 +03:00
dfgodvan ee424da341 Layout: a row starts whole only where the border below it fits too, as placing it needs
row_can_start took a row as fitting where its height did, while place_table
also wants the border below it (the row's edge). A first row that can't split
then looked as if it started under a kept caption that it actually left
alone at the foot of the page. The whole-row check and the start estimate
include the edge.
2026-11-12 23:16:57 +03:00
dfgodvan fe1cecbb90 Layout: a paragraph kept with a table needs its header rows and the start of its first row
Keep with next asked a table that follows for a flat 24 pt. Word keeps the
paragraph (a table caption, typically) with the table's repeated header rows
and the start of its first row: when they don't fit under it, the paragraph
goes over with the table instead of staying alone at the foot of the page.
The first row need not fit whole; the least room it can start in is enough
(two lines of a cell's text with widow/orphan control, compatibility mode 15).

table_start_need lays the table out and finds that room with row_can_start.
The look-ahead restores the list and equation counters, so numbered items in
the table's cells are counted once.
2026-11-12 23:16:57 +03:00
dfgodvan c120c09423 Layout: a right tab past the right indent takes its text up to the stop, as in Word
A TOC entry in Word's TOC styles has a right indent and a right tab with a dot leader at
the margin, past that indent. Word keeps the page number on the entry's line whenever it
fits between the text and the stop, so the number ends past the indent. WordCraft checked
the first character after the tab against the right indent (the tab has no room yet), and
moved the tab and its number to the next line when the text ended less than a digit short
of the indent.

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

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JesQG7ckr7g2qSfBwGkTqM
2026-11-11 16:44:02 +00:00
fluorine 021269b675 Cursor test: set the Ctrl modifier and check the unit selection starts 2026-11-11 11:10:11 -04:00
fluorine b395c45437 Canvas: classify a press by its own position and gate unit drags on it
A press and a move in one frame no longer let the move decide whether the press began on the paper. A unit selection that began in the grey keeps the arrow.
2026-11-11 10:57:15 -04:00
fluorineandClaude Sonnet 5.5 68c5dfe8c7 Canvas: remember where a press began so scrolling cannot change the pointer
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 10:34:47 -04:00
NetterSilverandClaude Sonnet 5.5 1b8934c823 fix: reconcile unmatched U+FFFC markers in one linear pass (no cap)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 01:18:16 +01:00
NetterSilverandClaude Opus 5.5 519ddb612b Reconcile inline objects with U+FFFC markers on .json open
Fixes #3678

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 01:09:47 +01:00
Fluorine eac757af34 Keep off-paper drag cursor as arrow 2026-11-10 19:07:59 -04:00
fluorineandClaude Sonnet 5.5 3c159e2331 Canvas: keep the arrow off the paper, show the text pointer only over a page
The grey around and between pages and the rulers showed the I-beam although no text
can be typed there. They keep the arrow now; a drag begun on the page keeps its I-beam.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-10 16:04:10 -04:00
Max Murphy f211d2914a M15 #1: list every docx-corpus option in xtask help; record the harness in gap #1
The top-level help listed only --dir and --out, hiding --all-pages,
--timeout and --cli. The ranked gap #1 row still said the DOCX fidelity
corpus was not started; it now records that the runner is complete while
the real-world corpus and the Word comparison remain, so the gap stays
open. Status lines and revision histories follow the repo convention.

Signed-off-by: Max Murphy <maxmrphy@gmail.com>
2026-11-10 20:22:30 +01:00
Max Murphy 2b99488c4b Merge remote-tracking branch 'origin/main' into feat/docx-corpus-harness
Signed-off-by: Max Murphy <maxmrphy@gmail.com>
2026-11-10 20:22:30 +01:00
Kevin Joseph 6997afcc34 Word for Mac 16.114.4 is the version these were measured in, not 16.113.4
The commit messages before this one name 16.113.4 too; the measurements were made in the Word
for Mac installed here, which reports 16.114.4.
2026-11-09 16:11:28 +01:00
Mauro Mazzieri d3096ed0fb Merge remote-tracking branch 'origin/main' into claude/continuous-section-first-page-header
# Conflicts:
#	crates/layout/src/table_flow.rs
#	docs/layout-parity.md
2026-11-09 15:48:45 +01:00
Kevin Joseph 0074cb6ac6 Layout: orphan control in a footnote split across pages
Rather than leave a note paragraph's first line alone at the bottom of a page, Word for Mac
16.113.4 moves the line holding the reference on to the next page with it. WordCraft kept the
line and one note line on the page. The least of a note that stays with its reference is now
two lines of a paragraph with widow/orphan control (or the paragraph whole); the page's first
note still splits where it must rather than overrun the page.

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

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

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

Tests: a_footnote_continuing_on_the_next_page_ends_on_the_bottom_margin and
widow_control_leaves_two_lines_of_a_split_footnote_on_the_next_page, each failing without its
half of the fix.
2026-11-09 13:30:03 +01:00
Michael c15eb8077a Merge branch 'main' of https://github.com/storytold/wordcraft into toc-insert-caret-position
# Conflicts:
#	crates/engine/src/cmd/references/tests.rs
2026-11-08 10:59:45 +08:00
Michael d572fff4cb Merge branch 'main' of https://github.com/storytold/wordcraft into toc-insert-caret-position
# Conflicts:
#	crates/engine/src/cmd/references/tests.rs
2026-11-08 09:11:43 +08:00
Michael ad721fc2b5 Merge remote-tracking branch 'upstream/main' into toc-insert-caret-position 2026-11-06 08:44:51 +08:00
MichaelandClaude Opus 5.5 1a86fd08fe TOC: the caret after the table sits past the next heading's bookmark
Review follow-up. When the paragraph after the table is a heading, the rebuilt entries give it a
`_Toc` bookmark at offset zero, so the caret placed at offset zero sat before the bookmark and
Delete removed it instead of the heading's first character, leaving the entry without its target.
The caret now goes past the markers the paragraph starts with.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 07:20:05 +08:00
MichaelandClaude Opus 5.5 0d4717cea6 TOC: the caret goes after a table replaced above a section break; page numbers count the added paragraph
Review follow-up. Replacing Word's TOC whose title sits above a section break returned before the
caret was placed, so a caret in the title stayed there and typing changed the title; that branch
now places it after the table too. When a table follows the TOC, the paragraph added for the
caret came after the entries were paginated; the entries are now rebuilt once it is there (with
the tabs and leader they now have), so their page numbers count it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 07:08:23 +08:00
Michael 60a150ab5b Merge branch 'main' of https://github.com/storytold/wordcraft into toc-insert-caret-position
# Conflicts:
#	crates/engine/src/cmd/references/tests.rs
2026-11-05 06:57:47 +08:00
dfgodvan 431251e139 Layout: drop a needless conversion in the picture line test (clippy) 2026-11-03 21:29:01 +03:00
dfgodvan 5cac512cfa Layout: rustfmt the picture line test 2026-11-03 21:29:01 +03:00
dfgodvan ace8f18c5a Layout: a picture line in multiple spacing takes the leading of its text, or of the paragraph mark alone
Measured in Word for Mac 16.93 (a 2cm picture, 1.15/2/3 spacing, Times New Roman and Arial
text, 8-20pt runs and marks): under a picture taller than the text Word puts the text's
descent plus (m - 1) x its natural height, and on a line of only pictures (m - 1) x the
paragraph mark's natural height, with no descent floor and never from the picture's own run.
The engine matches Word within 0.6pt in all 36 cases and keeps every page break.
2026-11-03 21:29:01 +03:00
dfgodvan c7bb6f6da2 Layout: a picture line in multiple spacing takes the text's leading and fits at the page foot like Word
Under multiple spacing above single, Word puts the text's extra leading,
(m - 1) x its natural height, below an inline picture taller than the text
instead of the descent, and lets a page's last line run that leading into the
bottom margin as it does for text: only the picture has to fit.

Measured in Word for Windows (compatibility mode 15) on a 64-page document
with 1.5-spaced 12pt text (natural 12.59pt, descent 2.63pt): a 472pt picture
stayed on its page with 1.7pt to spare above the bottom margin, and the lines
after 438pt and 616pt pictures started 6.3pt below them. WordCraft needed the
picture plus the descent to fit, moved the picture to the next page and ended
with 65 pages; it now lays the document out on 64, the pictures on Word's pages.

The descent stays the floor, so single and slightly-above-single spacing
(1.08, 1.15) keep their line heights.
2026-11-03 21:29:01 +03:00
Mauro MazzieriandClaude Opus 5.5 dc515b6128 Different first page: no first-page header on a continuous section's second page
A page is its section's first page, the one a different first page's header and footer go on,
only if the section begins on it. A page's section is the one at its top, so a section that
starts continuously part-way down a page was taken to begin on the next page, which then showed
the section's first-page header. Word shows the earlier section's header on the page where the
section starts and the section's default header from the next page on: the first-page header of
such a section is never seen (checked in Word for Windows 365 on a synthetic file).

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 10:36:33 +01:00
Max Murphy c2e4a05df1 M15 #1: rebuild wordcraft-cli before every DOCX corpus run
Signed-off-by: Max Murphy <maxmrphy@gmail.com>
2026-11-02 22:38:29 +01:00
Max Murphy 77060f63ab M15 #1: put --release after the cargo build subcommand
Signed-off-by: Max Murphy <maxmrphy@gmail.com>
2026-11-02 22:38:29 +01:00
Max Murphy cee47681a3 M15 #1: add opt-in DOCX corpus harness
Adds cargo xtask docx-corpus: every .docx under a local corpus is opened and inspected, rendered to PNG (page 1 or all pages), saved to a temporary copy, reopened and compared by plain text and page count. Each stage runs in a bounded child wordcraft-cli process, failures are classified, and one bad file never stops the run.

The JSON report is sorted and timestamp-free, with a Markdown summary and rendered pages beside it. Missing and empty corpora exit successfully. The harness is local-only: /corpus stays git-ignored, only corpus/docx/README.md is tracked, and no Word-produced file or Word-vs-WordCraft visual comparison is added.
2026-11-02 22:38:29 +01:00
Florent Siegenthaler 47039c163f Info.plist: say where the language list comes from, and that AppKit follows the macOS language 2026-10-30 21:18:40 +01:00
Florent Siegenthaler b585ac4493 Merge remote-tracking branch 'origin/main' into macos-dialog-localizations 2026-10-30 21:18:26 +01:00
OPUZZLES 34b9e6aacc #3614: reconcile PDF figure lookups with main 2026-10-30 18:20:09 +01:00
Marco Arnulfo ce1f7ecb63 Equations: Left and Right open the equation through edit_at, not a JSON round trip (#4138) 2026-10-30 03:14:45 +01:00
Marco Arnulfo 57427c7b98 Equations: progress docs for Left and Right next to an equation (#4138) 2026-10-30 03:11:45 +01:00
Marco Arnulfo dfb1341d72 Equations: Left and Right next to an equation pinned through the keyboard path, also between two equations (#4138) 2026-10-30 03:11:40 +01:00
Marco Arnulfo 32922ec9a4 Equations: typing parity documents Left and Right next to an equation (#4138) 2026-10-30 03:05:47 +01:00
Marco Arnulfo 7cfa807dc3 Equations: Left and Right step into an equation next to the caret, as in Word (fixes #4138) 2026-10-30 03:00:31 +01:00
Mat Strange aec899bbee A table that can't hold the list refuses it, not cuts it
Insert › Table › Spreadsheet Table made a table of the rows
`insert.table` inserts — at most a thousand — and then wrote the
parsed records into it. A longer list lost everything above that,
quietly, and the command said it had worked.

The list is now held to what the table can take: its columns, and its
rows. One over either is refused with a message that says which. The
row count the table command clamps to is now a named constant
(`insert::MAX_TABLE_ROWS`), so the two read the same number.

The record limit of a recipient list is a separate matter, and
#1927 changes that line: it makes the reader keep one record past the
limit so the list can be told it is too long, rather than cut.
2026-10-29 14:00:49 +00:00
Mat Strange 0f84914edc #4053: A recipient list over what it keeps is refused while it is read
The CSV reader had no field cap: every comma became a String, so a
38 MB file of commas was forty million of them — a gigabyte of memory
for a list that came back empty. The field cap that did exist was
applied afterwards, to a list that had already been built, and every
record of a wide header is padded to its width, so 605 KB of CSV grew
to 4.7 GB.

The reader now keeps its limits while it reads: at most 1,000 columns
in a record, 2,000,000 cells (the records times the widest record,
which is what a list costs once every record is padded to the header's
width) and 64 MiB of cell text. A list over them is refused with a
message that says which limit it is over, rather than built and cut.

Those are the numbers the spreadsheet path already keeps
(crates/formats/src/sheet.rs), so a list read as a CSV and the same
list read as a workbook are held to one budget.

Measured through the file route (wordcraft-cli), before and after:

  40,000,000 commas (38 MB): 1,003 MB → 128 MB, refused
  1,000 columns over 100,000 records (605 KB): 4,610 MB → 13 MB, refused
  100,000 records of 10 columns: 0.16 s, the same peak memory, before
  and after

The reader keeps the separator detection main has (the separator is
counted outside quotes) and the record limit of 100,000 is untouched:
that line is #1927's, and it changes the same function.

The spreadsheet path and the typed `rows` list are untouched, and a
list is still stored twice and cloned on every filter; those are the
auditor's #3616, which stays open.
2026-10-29 14:00:45 +00:00
OPUZZLES 6b3555e831 M12: assert PDF figure roles and selected page order (#3614) 2026-10-29 10:03:58 +01:00
OPUZZLES 0e96d0abd0 M12: reuse PDF figure object lookups (#3614) 2026-10-29 09:34:06 +01:00
MichaelandClaude Sonnet 5.5 07544f5078 Merge upstream main into toc-insert-caret-position
references.rs was split into references/; the caret-placement change and its
tests move to references/toc.rs and references/tests.rs.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 09:41:53 +08:00
Florent Siegenthaler af4608d7f0 Declare the UI languages to AppKit so the open and save panels are translated 2026-10-26 09:24:47 +01:00
Jayesh Prajapati 082d47c8a2 Merge branch 'main' of https://github.com/storytold/wordcraft into fix/3639-header-commands-own-section
# Conflicts:
#	ROADMAP.md
#	docs/ui-parity.md
2026-10-26 10:03:24 +05:30
Jayesh Prajapati c70807b8a9 Merge branch 'main' of https://github.com/storytold/wordcraft into fix/3639-header-commands-own-section
# Conflicts:
#	ROADMAP.md
#	docs/ui-parity.md
2026-10-26 08:14:22 +05:30
ratkoandClaude Opus 5.5 dd7b12f504 A selected picture survives Enter and breaks (#4126)
Enter on a selected picture or shape deleted it, like selected text.
In Word for Mac, Enter does nothing there, inline or floating, however
many times it is pressed. Shift+Enter and a page break go in front of
the picture and keep it selected, so it moves down a line or to the
next page; a column break does the same. A break on a picture inside a
Picture content control goes in front of the control, and the picture
stays selected.

A selected text box is unchanged: in the app, Enter puts the caret in
its text.

Tested by the developer in the app.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 08:54:25 +01:00
Diego GueriniandClaude Opus 5.5 e525617d55 Merge upstream/main into rtl-numbers-latin
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 08:03:45 +01:00
Diego GueriniandClaude Opus 5.5 98bbdb506e Merge upstream/main into rtl-numbers-latin
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 21:02:21 +02:00
Diego GueriniandClaude Opus 5.5 b2c985ba06 Merge upstream/main into rtl-numbers-latin
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 16:04:12 +02:00
Jayesh Prajapati 0db3ce644a Merge branch 'main' of https://github.com/storytold/wordcraft into fix/3639-header-commands-own-section
# Conflicts:
#	ROADMAP.md
#	docs/ui-parity.md
2026-10-24 11:03:07 +05:30
Jayesh Prajapati 96eddcfe69 #3639: Header and footer commands use the section of the caret's page in a linked header 2026-10-24 11:02:42 +05:30
Diego GueriniandClaude Opus 5.5 633f5bc212 Merge upstream/main into rtl-numbers-latin
#2150 review: docs/layout-parity.md keeps one bidirectional row (the updated one, where main has it).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 21:02:45 +02:00
Jayesh Prajapati 85ad49db32 #3639: Edit Header/Footer from a header opens the one the section is linked to
With no page given and the caret in a header or footer, Edit Footer took
only the caret's section's own footer, so a section linked to the
previous one got a new footer of its own and lost the link. It now walks
back to the footer the section shows, as layout does.
2026-10-23 18:17:16 +05:30
Jayesh Prajapati 7c1792867d #3639: Header and footer commands change the section of the header the caret is in
With the caret in a header or footer, Link to Previous, Header/Footer
Position, Insert Header/Footer, Edit Header/Footer and Page Borders read
the header's paragraph index as a body paragraph index, so section 2's
header changed section 1. They now find the caret's section with
section_index_of_focus, as Page Setup already does (#2072).
2026-10-23 13:44:17 +05:30
Divyanshu Gupta 6e783bdc6e fix(engine): preserve AutoCorrect İ lowering for non-Turkic languages
Keep AutoCorrect's specific mapping of İ -> i for non-Turkic languages while allowing Change Case to use Unicode-default lowering, and add regression tests for English two-initial-capitals and caps-lock.
2026-10-22 00:43:17 +05:30
Divyanshu Gupta c2cb17cb36 fix(engine): support quoted literals and preserve bare 'a' in date pictures
In format_date_parts, strip single quotes around literal text sections, preserve bare 'a'/'A' characters instead of treating them as AM/PM tokens, and zero-pad 12-hour clock hours when 'hh' is specified.

Closes #3488
2026-10-22 00:19:56 +05:30
Divyanshu Gupta aea58b38b8 fix(engine): apply Turkic case mapping in Change Case for Turkish, Azerbaijani, and Crimean Tatar
In Change Case, resolve the effective run language and apply language-aware casing for Turkish, Azerbaijani, and Crimean Tatar (mapping i <-> İ and ı <-> I). Non-Turkic languages continue to use default Unicode casing.

Closes #3479
2026-10-21 23:49:45 +05:30
Diego GueriniandClaude Sonnet 5.5 ad4d2dfec0 Merge upstream/main into rtl-numbers-latin
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 09:54:54 +02:00
MichaelandClaude Sonnet 5 c08be77357 TOC: check the block after the table is a paragraph, not just present
CodeRabbit found a real edge case: when a table of contents already has
entries, is immediately followed by a table (nothing paragraph-shaped in
between), and gets replaced in place by a settings change, the "does a
block already exist after the table" check used Option::is_none, so it
reused that existing block's path as the caret's position regardless of
its type - landing the selection at the table's own top-level path.
clamp_selection then silently snaps that invalid position back to the
nearest *preceding* paragraph, i.e. back inside the table's own entries,
reproducing a milder form of the very bug this PR fixes.

Check the block is actually a paragraph before reusing it; insert one
otherwise, same as when nothing is there at all.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-20 13:02:31 +08:00
MichaelandClaude Sonnet 5 a552c4bdda TOC: leave the caret after the table, not inside its own title
insert_toc builds the title paragraph, the field, and the entries, but
never moves the selection afterward — whatever it was before the command
(the document's original, now-displaced paragraph) stays put, which after
a brand-new TOC on an otherwise-empty document is offset 0 of the
TOCHeading paragraph itself, right before "Contents".

Confirmed against real Word (16.0.20527.20054): Insert > Table of Contents
leaves the caret in a fresh paragraph right after the table, ready to keep
typing. Anyone following that same natural workflow in WordCraft today -
insert a TOC placeholder, write headings and body text, call Update Table
once done - ends up typing inside the TOC's own title paragraph instead,
and the later Update Table call then splices "Contents" out of its own
paragraph and onto whatever body paragraph happened to end up right before
the entries, leaving the title blank.

Move the selection to a paragraph right after the table once it's built
(reusing one that's already there, or adding an empty one if the table
ends the document), matching Word's placement and keeping the title and
entries intact however the user continues from there.

Fixes #3227.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-20 12:50:47 +08:00
SlavenDj 913d9fa5ab Offer Blank document, Browse… and Home in the empty window (#3126)
With no document open (Esc on the Start screen, File › Close) the page area
was blank while the ribbon was greyed out, so the only way back to the
Start screen was the account button. It now says no document is open and
offers Blank document, Browse… and Home; Home returns to the Start screen
without creating a document, and Blank document opens one ready for
typing.
2026-10-19 23:43:49 +02:00
Diego GueriniandClaude Opus 5.5 0d75ca3bf6 #2150: gap #16 and the progress log record Latin text kept in order in right-to-left lines
CodeRabbit: `docs/gaps.md` still listed the right-to-left gap without this change and
`ROADMAP.md` had no progress entry. Both are added, with their status lines and revision
histories.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 07:25:54 +02:00
Diego GueriniandClaude Opus 5.5 71d341fcfb #2150: a combining mark between a right-to-left letter and Latin text keeps its letter's level
CodeRabbit: with no space between them, an Arabic or Persian letter's combining mark (NSM) began
the segment the Latin span is found in, so the span gave it the Latin level and the mark was
shaped apart from its letter. The marks the span starts with are left at their own level.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 23:25:30 +02:00
Diego Guerini 3bf1a0a81c Merge remote-tracking branch 'upstream/main' into rtl-numbers-latin
# Conflicts:
#	docs/layout-parity.md
#	docs/target-app-parity.md
2026-10-18 23:15:43 +02:00
Diego Guerini 6e8820dc5d Merge remote-tracking branch 'upstream/main' into rtl-numbers-latin
# Conflicts:
#	docs/layout-parity.md
2026-10-18 16:09:02 +02:00
Diego GueriniandClaude Opus 5.5 213b75ce02 #2150: a combining mark ending the right-to-left word keeps its level
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 12:37:08 +02:00
Diego Guerini 8883429285 Merge remote-tracking branch 'upstream/main' into rtl-numbers-latin
# Conflicts:
#	docs/layout-parity.md
#	docs/target-app-parity.md
2026-10-18 11:26:24 +02:00
Diego GueriniandClaude Opus 5.5 62bf70beb3 #2150: neutrals inside an explicit embedding keep the embedding's level
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 11:25:41 +02:00
Diego Guerini b0a2b71cbe Merge remote-tracking branch 'upstream/main' into rtl-numbers-latin
# Conflicts:
#	docs/layout-parity.md
2026-10-18 10:29:35 +02:00
justinjohn0306andClaude Opus 5.5 1d890c0932 #1913: translate "Browse templates…" in every interface catalog
The i18n audit failed on the new Backstage button.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 16:41:47 +05:30
justinjohn0306 3d3e7ac5ef Merge commit 'eae2421' into HEAD 2026-10-16 16:37:24 +05:30
justinjohn0306 73f0701255 #1913: expose spacing templates in Backstage 2026-10-16 13:43:51 +05:30
Diego GueriniandClaude Opus 5.5 1f2510ddda #2150: Latin text keeps its digits, spaces and punctuation in order in right-to-left text
UAX #9 alone showed "2-naphthol" after a Persian word as "naphthol-2" in a
right-to-left paragraph (the hyphen went with the Persian text) and "11
Windows" for "Windows 11", and in a left-to-right paragraph the digit after
Arabic letters became an Arabic number placed before the Persian word.

bidi_levels now keeps Latin text together: from the word with the first
left-to-right letter to the word with the last letter or digit after it,
without crossing a right-to-left letter, a tab or an explicit embedding mark,
everything takes the letters' level, except sentence punctuation at either
end. The spaces and punctuation between it and the right-to-left text take
the paragraph's level (rule N2). Numbers alone and text across tabs are left
to UAX #9.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 20:48:33 +02:00
justinjohn0306 734dedde28 #1913: apply paragraph spacing presets to styles 2026-10-15 12:12:27 +05:30
313 changed files with 27078 additions and 3140 deletions
+12 -2
View File
@@ -83,7 +83,9 @@
}
},
"max_artifact_bytes": 2147483648,
"automatic_signer_actors": [],
"automatic_signer_actors": [
"github-actions[bot]"
],
"platforms": {
"windows-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
@@ -95,7 +97,15 @@
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
"trust": {
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
}
},
"package_formats": [
"appimage",
"arch",
"deb",
"flatpak",
"oci",
"rpm"
]
},
"macos-aarch64": {
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
+2 -2
View File
@@ -11,9 +11,9 @@ permissions: {}
jobs:
dispatch:
# SOURCE PREPARATION: literal off until immutable shared tooling and policy qualification.
# Automatic Stage 2 signer dispatch for completed scheduled nightly producer runs.
if: >-
false && github.repository == 'storytold/wordcraft' &&
github.repository == 'storytold/wordcraft' &&
github.event_name == 'workflow_run'
runs-on: ubuntu-latest
timeout-minutes: 5
+3 -2
View File
@@ -1,8 +1,9 @@
name: WordCraft unsigned nightly
# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet.
# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it).
# Automated daily unsigned nightly build at 07:00 UTC plus supervised manual runs.
on:
schedule:
- cron: '0 7 * * *'
workflow_dispatch:
permissions:
+1 -1
View File
@@ -10,7 +10,7 @@ permissions:
contents: read
concurrency:
group: sonarcloud-${{ github.ref }}
group: ${{ github.ref == 'refs/heads/main' && format('sonarcloud-main-{0}', github.sha) || format('sonarcloud-{0}', github.ref) }}
# A push to main is the run that publishes coverage; superseded runs there would never finish.
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
+4 -1
View File
@@ -2,7 +2,10 @@
plan/
/target
/dist
/corpus
/corpus/*
!/corpus/docx/
/corpus/docx/*
!/corpus/docx/README.md
/log
.DS_Store
/.claude/
+1
View File
@@ -258,6 +258,7 @@ The UI icons are SVG files in `crates/ui-egui/icons/`, one row each below. Gener
| `crates/ui-egui/icons/pageNumber.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/pageWidth.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/painter.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/painter-fill.svg` | WordCraft contributors | original: the Format Painter's yellow bar, split out as the fill drawn under `painter.svg` | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/paraSpacing.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/pastCitation.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/paste.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
Generated
+173 -148
View File
File diff suppressed because it is too large Load Diff
+54 -53
View File
@@ -37,21 +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 = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
wordcraft-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 = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
craft = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0", default-features = false }
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0", default-features = false }
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
# foundation
kurbo = { version = "0.13", features = ["serde"] }
@@ -84,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 = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0", default-features = false, features = ["write"] }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0", default-features = false, features = ["write"] }
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0", features = ["doc"] }
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0", features = ["text"] }
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0", features = ["flow"] }
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0", features = ["detect"] }
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0", features = ["doc"] }
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0", features = ["text"] }
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0", features = ["flow"] }
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0", features = ["detect"] }
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
# 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"
@@ -173,27 +174,27 @@ debug = 0
# The framework's patches, which Cargo does not carry over to dependents: its vendored crates from craft-libs,
# and the egui and winit forks it builds with.
[patch.crates-io]
krilla = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
hayro = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
emath = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
hayro = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
emath = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
egui = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
winit = { git = "https://github.com/storytold/winit.git", rev = "3fd7ae64762f82a73b78bd24f453f82c4291067d" }
+31
View File
@@ -188,3 +188,34 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Linux Wayland window decorations
-------------------------------
sctk-adwaita 0.10.1 (https://github.com/PolyMeilex/sctk-adwaita,
commit d5f343c45c04d4a026db57f76760819b7325db00) is used by winit on Linux
for vector window controls. Its title-font features are disabled: no Cantarell
font is embedded by this dependency and no font file is added to this repo.
sctk-adwaita's MIT licence:
MIT License
Copyright (c) 2022 Bartłomiej Maryńczak
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+21 -3
View File
File diff suppressed because one or more lines are too long
+12 -2
View File
@@ -36,9 +36,11 @@ USAGE:
page can't be drawn or a picture is missing or undecodable
(report on stderr, as for convert --strict)
wordcraft-cli run [--file F | --template T] [--script FILE|-] [--cmd 'id={json}' …]
[--save OUT] [--page N] [--scale S] [--print] [--author NAME]
[--save OUT …] [--page N] [--scale S] [--print] [--author NAME]
run commands headlessly, then save (--author names
who tracked changes and comments are by).
Repeat --save OUT to write multiple outputs in order,
after any outputs from --script.
PNG saves use --page (1-based, default 1) and --scale (default 2).
--script runs a JSON file (- is stdin) first:
{\"file\"?, \"template\"?, \"commands\": [{\"command\": id,
@@ -632,6 +634,13 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
}
}
validate_options("run", &rest, RUN_OPTIONS)?;
let mut cli_outputs = Vec::new();
for (i, arg) in rest.iter().enumerate() {
if arg == "--save" {
let path = rest.get(i + 1).filter(|value| !value.is_empty() && !value.starts_with("--")).ok_or("run: --save requires a path")?;
cli_outputs.push(path.clone());
}
}
let page = parse_page_arg("run", &rest)?;
let scale = parse_scale_arg("run", &rest)?;
let password = password_from(&rest)?;
@@ -680,7 +689,7 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
i += 1;
}
}
let outputs: Vec<String> = script.iter().flat_map(|c| c.save.iter().cloned()).chain(arg_value(&rest, "--save")).collect();
let outputs: Vec<String> = script.iter().flat_map(|c| c.save.iter().cloned()).chain(cli_outputs).collect();
// Check every output can be made before writing any, so a bad one leaves no half-done job.
for out in &outputs {
let parent = Path::new(out).parent().filter(|p| !p.as_os_str().is_empty());
@@ -1048,6 +1057,7 @@ fn launcher_profile_flag(args: &[OsString]) -> bool {
}
fn main() -> ExitCode {
wordcraft_engine::malloc_tuning::apply();
let args: Vec<OsString> = std::env::args_os().skip(1).collect();
if launcher_profile_flag(&args) {
eprintln!("wordcraft-cli: --launch-profile and --profile-root are the desktop app's Nightly bootstrap, not a CLI option");
+58
View File
@@ -564,6 +564,64 @@ fn script_builds_a_document_and_saves_docx_and_pdf_relative_to_the_script() {
assert!(json.contains("Hello script") && json.contains("\"bold\":true"));
}
#[test]
fn run_saves_each_cli_output_and_still_accepts_a_single_save() {
let dir = script_dir("cli-saves");
let input = dir.join("in.docx");
let docx = dir.join("out.docx");
let pdf = dir.join("out.pdf");
run(&args(&["run", "--template", "sample", "--save", &input.to_string_lossy()])).unwrap();
run(&args(&["run", "--file", &input.to_string_lossy(), "--save", &docx.to_string_lossy(), "--save", &pdf.to_string_lossy()])).unwrap();
assert_eq!(listed_text(&open(&docx, None).unwrap().doc).unwrap(), listed_text(&open(&input, None).unwrap().doc).unwrap());
assert!(std::fs::read(pdf).unwrap().starts_with(b"%PDF"));
}
#[test]
fn run_saves_script_and_cli_outputs() {
let dir = script_dir("mixed-saves");
let script = write_script(&dir, r#"{"commands":["caret.docEnd"],"save":["script.txt","script.docx"]}"#);
let first = dir.join("cli.txt");
let second = dir.join("cli.docx");
run(&args(&["run", "--save", &first.to_string_lossy(), "--script", &script, "--save", &second.to_string_lossy()])).unwrap();
for path in [dir.join("script.txt"), dir.join("script.docx"), first, second] {
assert!(path.is_file(), "{} was not written", path.display());
}
}
#[test]
fn run_rejects_a_missing_second_save_path_before_writing() {
let dir = script_dir("missing-save");
let first = dir.join("first.docx");
let first_path = first.to_string_lossy();
for tail in [vec!["--save"], vec!["--save", "--print"], vec!["--save", ""]] {
let mut argv: Vec<&str> = vec!["run", "--save", &first_path];
argv.extend(tail);
assert_eq!(run(&args(&argv)), Err("run: --save requires a path".into()));
assert!(!first.exists());
}
}
#[test]
fn run_preflights_script_and_cli_outputs_in_order_before_writing() {
let dir = script_dir("preflight-saves");
let first = dir.join("first.docx");
let invalid = dir.join("missing/later.docx");
let last = dir.join("missing-too/last.docx");
let mut script = write_script(&dir, r#"{"commands":["caret.docEnd"],"save":["missing-script/script.docx"]}"#);
let first_path = first.to_string_lossy();
let invalid_path = invalid.to_string_lossy();
let last_path = last.to_string_lossy();
let argv = |script: &str| args(&["run", "--save", &first_path, "--save", &invalid_path, "--script", script, "--save", &last_path]);
let err = run(&argv(&script)).unwrap_err().to_string();
assert!(err.contains("script.docx"), "{err}");
assert!(!first.exists());
script = write_script(&dir, r#"{"commands":["caret.docEnd"],"save":["script.docx"]}"#);
let err = run(&argv(&script)).unwrap_err().to_string();
assert!(err.contains("later.docx"), "{err}");
assert!(!first.exists() && !dir.join("script.docx").exists());
}
#[test]
fn script_with_a_bad_output_writes_no_output() {
let dir = script_dir("badout");
+2
View File
@@ -3,6 +3,8 @@ mod closed_stdout;
mod convert_fields;
mod convert_region;
mod help;
#[cfg(all(target_os = "linux", target_env = "gnu"))]
mod malloc_tuning;
mod mcp_roots;
#[cfg(all(unix, not(target_os = "macos")))]
mod non_utf8_args;
@@ -0,0 +1,78 @@
//! The CLI binary re-executes itself on Linux glibc with `MALLOC_TRIM_THRESHOLD_` fixed so freed
//! page/render buffers are returned to the OS while respecting caller-supplied values.
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicUsize, Ordering};
use wordcraft_engine::malloc_tuning::{TRIM_THRESHOLD, TRIM_THRESHOLD_VAR};
struct TempDirs(PathBuf);
impl TempDirs {
fn new(tag: &str) -> Self {
static NEXT: AtomicUsize = AtomicUsize::new(0);
let root = loop {
let n = NEXT.fetch_add(1, Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!("wc-cli-malloc-{tag}-{}-{n}", std::process::id()));
match std::fs::create_dir(&dir) {
Ok(()) => break dir,
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
Err(e) => panic!("temp dir {}: {e}", dir.display()),
}
};
std::fs::create_dir_all(root.join("in")).unwrap();
std::fs::create_dir_all(root.join("out")).unwrap();
Self(root)
}
}
impl Drop for TempDirs {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn s(p: &Path) -> String {
p.to_string_lossy().into_owned()
}
fn mcp_environ(tag: &str, set: Option<&str>) -> Vec<String> {
let dirs = TempDirs::new(tag);
let mut cmd = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"));
for var in [TRIM_THRESHOLD_VAR, "MALLOC_MMAP_THRESHOLD_", "MALLOC_TOP_PAD_", "MALLOC_MMAP_MAX_", "MALLOC_ARENA_MAX", "GLIBC_TUNABLES"] {
cmd.env_remove(var);
}
if let Some(v) = set {
cmd.env(TRIM_THRESHOLD_VAR, v);
}
let mut child = cmd
.args(["mcp", "--automation-read-root", &s(&dirs.0.join("in")), "--automation-write-root", &s(&dirs.0.join("out"))])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.unwrap();
let mut stdin = child.stdin.take().unwrap();
writeln!(stdin, r#"{{"jsonrpc":"2.0","id":1,"method":"ping"}}"#).unwrap();
let mut reply = String::new();
BufReader::new(child.stdout.take().unwrap()).read_line(&mut reply).unwrap();
assert!(reply.contains(r#""id":1"#), "mcp answered after re-exec: {reply}");
let environ = std::fs::read(format!("/proc/{}/environ", child.id())).unwrap();
drop(stdin);
assert!(child.wait().unwrap().success());
environ.split(|&b| b == 0).map(|e| String::from_utf8_lossy(e).into_owned()).collect()
}
#[test]
fn sets_the_trim_threshold() {
let env = mcp_environ("default", None);
assert!(env.contains(&format!("{TRIM_THRESHOLD_VAR}={TRIM_THRESHOLD}")), "{env:?}");
}
#[test]
fn keeps_a_value_the_user_set() {
let env = mcp_environ("explicit", Some("999999"));
assert!(env.contains(&format!("{TRIM_THRESHOLD_VAR}=999999")), "{env:?}");
}
+2 -2
View File
@@ -110,7 +110,7 @@ impl Bridge {
fn listen(&self, intake: IntakeSender) {
self.host.listen(move |message| {
if let Message::Open { name, data } = message {
deliver_open(&intake, &name, &data);
deliver_open(&intake, name.as_deref().unwrap_or("document"), &data);
}
});
}
@@ -119,7 +119,7 @@ impl Bridge {
/// The file an open message carries, queued for the next frame like a dropped file. A host's file
/// is untrusted input: an oversized one is refused before it is copied into the app's memory (the
/// data's own length, not the host's claim). The crate has cleaned the name (and cut it to 255
/// characters); a blank one comes as `document` and becomes `Document.docx`.
/// characters); a missing one comes as `None` and becomes `Document.docx`.
fn deliver_open(intake: &IntakeSender, name: &str, data: &FileData) {
let name = if name == "document" { DEFAULT_NAME } else { name }.to_string();
let FileData::Bytes(array) = data else {
+2 -2
View File
@@ -13,14 +13,14 @@ pub fn open() -> (SharedSettings<Prefs>, craft::settings::LoadReport) {
use std::time::Duration;
use craft::settings::{LegacyFile, LocalStorageFiles, Location, OpenOptions, SettingsStore};
use wordcraft_ui_egui::prefs::legacy_ui_json;
use wordcraft_ui_egui::prefs::legacy_ui_json_slots;
/// Largest stored value read back (`localStorage` holds about 5 MB per site).
const MAX_STORED: usize = 4 << 20;
let options = OpenOptions::new(Location::Dir("wordcraft".into()))
.files(Arc::new(LocalStorageFiles::new(MAX_STORED)))
.debounce(Duration::ZERO)
.legacy(vec![LegacyFile { path: "wordcraft.ui".into(), parse: legacy_ui_json }]);
.legacy(vec![LegacyFile { paths: vec!["wordcraft.ui".into()], parse: legacy_ui_json_slots }]);
let (store, report) = SettingsStore::open_with(options);
(SharedSettings::new(store), report)
}
+12 -1
View File
@@ -43,6 +43,7 @@ craft = { workspace = true, features = [
"platform-appearance",
"platform-clipboard-system",
] }
craft-nightly = { workspace = true }
[dev-dependencies]
# Temporary settings folders for the `prefs` tests.
@@ -59,14 +60,24 @@ winresource = "0.1"
# kAEOpenDocuments Apple event, which winit doesn't handle (#27).
craft = { workspace = true, features = ["platform-apple-events", "menu"] }
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
[target.'cfg(all(unix, not(any(target_os = "macos", target_os = "linux"))))'.dependencies]
winit = { version = "0.30", default-features = false, features = ["x11"] }
[target.'cfg(target_os = "linux")'.dependencies]
# Retain X11 fallback; draw Wayland client-side controls without bundled title fonts.
winit = { version = "0.30", default-features = false, features = ["x11", "wayland-csd-adwaita-notitle"] }
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
# Check that the libraries winit's X11 backend opens are installed before choosing XWayland (see
# `x11_libraries` in main.rs). Both are already in the build through winit's `x11` feature, at
# these versions and with this feature.
x11-dl = "2.21"
xkbcommon-dl = { version = "0.4.2", features = ["x11"] }
# Name the window supplied by eframe's attachment hook on targets that otherwise use winit indirectly.
[target.'cfg(any(target_os = "macos", windows))'.dependencies]
winit = { version = "0.30", default-features = false }
[target.'cfg(windows)'.dependencies]
# The update helper: a copy of this program started with `--finish-update`
# (`craft::update::self_update::finish`).
+19 -25
View File
@@ -1,23 +1,11 @@
//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build.
use crate::launch_profile::Profile;
use std::ffi::OsString;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BuildFlavor {
Stable,
NightlyV1,
}
pub use craft_nightly::BuildFlavor;
pub const COMPILED: BuildFlavor = if cfg!(wordcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> {
match (flavor, profile.is_nightly()) {
(BuildFlavor::NightlyV1, false) => Err("Open WordCraft Nightly from ArtCraft Launcher".into()),
(BuildFlavor::Stable, true) => Err("This is a stable WordCraft build; nightly-v1 requires the nightly build".into()),
_ => Ok(()),
}
}
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
desktop_session && flavor == BuildFlavor::NightlyV1
}
@@ -37,7 +25,10 @@ pub fn version_query(args: &[OsString]) -> bool {
#[cfg(test)]
mod tests {
use super::*;
use super::{BuildFlavor, needs_native_error, version, version_query};
use craft_nightly::{Profile, ProfileError, StartupOptions, canonical_profile_root, parse_startup};
use std::ffi::OsString;
#[test]
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
@@ -47,19 +38,22 @@ mod tests {
}
#[test]
fn nightly_build_without_a_profile_is_refused_before_startup() {
let started = std::cell::Cell::new(false);
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
assert!(!started.get());
fn direct_nightly_launch_self_isolates_into_canonical_profile_root() {
let spec = crate::profile_root::spec();
let expected_root = canonical_profile_root(spec.app_id).unwrap();
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, [OsString::from("letter.docx")], &StartupOptions::new()).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(expected_root));
assert_eq!(launch.passthrough_args, vec![OsString::from("letter.docx")]);
}
#[test]
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
fn stable_build_refuses_nightly_launch_flags() {
let spec = crate::profile_root::spec();
let args = craft_nightly::launch_arguments(std::path::Path::new(crate::launch_profile::launcher_root()), &[]);
let err = parse_startup(BuildFlavor::Stable, &spec, args, &StartupOptions::new()).unwrap_err();
assert!(matches!(err, ProfileError::NightlyFlagsInStableBuild));
}
#[test]
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
assert_eq!(version(BuildFlavor::Stable, "0.18.1"), "0.18.1");
+87
View File
@@ -0,0 +1,87 @@
//! Native parent windows for document-owned file pickers in windowless mode.
use std::collections::HashMap;
use std::num::NonZeroU64;
use std::sync::{Arc, Mutex, Weak};
use craft::dialogs::service::FilePanels;
use craft::platform::open::IntakeSender;
use craft::ui::dialog::DialogHost;
use eframe::{ViewportHooks, ViewportWindowKey};
use egui::{Context, RawInput, ViewportId};
use winit::window::Window;
use wordcraft_ui_egui::file_dialogs::{NativeWindowLookup, OwnerPanels, ParentLease};
use crate::drop_intake::ChildDrops;
/// The latest successful attachment for each viewport. The registry does not keep windows alive.
#[derive(Clone, Default)]
pub(crate) struct DocumentWindows(Arc<Mutex<HashMap<ViewportId, (ViewportWindowKey, Weak<Window>)>>>);
impl DocumentWindows {
pub(crate) fn hooks(&self, drops: IntakeSender) -> Arc<dyn ViewportHooks> {
Arc::new(DocumentHooks { windows: self.clone(), drops: ChildDrops(drops) })
}
}
struct DocumentHooks {
windows: DocumentWindows,
drops: ChildDrops,
}
impl ViewportHooks for DocumentHooks {
fn window_attached(&self, key: ViewportWindowKey, window: Weak<Window>) {
let mut attached = self.windows.0.lock().unwrap_or_else(|e| e.into_inner());
attached.insert(key.viewport_id(), (key, window));
}
fn window_detached(&self, key: ViewportWindowKey) {
let mut attached = self.windows.0.lock().unwrap_or_else(|e| e.into_inner());
if attached.get(&key.viewport_id()).is_some_and(|(current, _)| *current == key) {
attached.remove(&key.viewport_id());
}
}
fn raw_input(&self, ctx: &Context, raw: &mut RawInput) {
self.drops.raw_input(ctx, raw);
}
}
impl NativeWindowLookup for DocumentWindows {
fn incarnation(&self, viewport: ViewportId) -> Option<NonZeroU64> {
let attached = self.0.lock().unwrap_or_else(|e| e.into_inner());
let (key, weak) = attached.get(&viewport)?;
(weak.strong_count() > 0).then(|| key.incarnation())
}
}
impl OwnerPanels for DocumentWindows {
fn pump_parented(
&mut self,
viewport: ViewportId,
incarnation: NonZeroU64,
panels: &mut FilePanels,
host: &mut DialogHost,
) -> Option<ParentLease> {
// Upgrade only the exact live incarnation, on the event-loop thread. Never hold the
// registry lock across the pump (macOS can enter native dialog code here).
let parent = {
let attached = self.0.lock().unwrap_or_else(|e| e.into_inner());
let (key, weak) = attached.get(&viewport)?;
if key.incarnation() != incarnation {
return None;
}
weak.upgrade()?
};
panels.pump_with(host, Some(parent.as_ref()));
// rfd can use the copied handles on a later worker callback. The router retains this
// lease through backend completion even if the initiating document detached meanwhile.
Some(ParentLease::new(parent))
}
fn pump_unparented(&mut self, panels: &mut FilePanels, host: &mut DialogHost) {
// The router allows this only for an explicitly in-app request or an already launched
// operation with an empty native queue. It cannot open an unowned system dialog here.
panels.pump_with::<eframe::Frame>(host, None);
}
}
+111
View File
@@ -0,0 +1,111 @@
//! Route desktop drop events to WordCraft's existing file intake.
use std::path::Path;
use std::sync::Arc;
use craft::platform::open::{DroppedFile, IntakeSender};
use eframe::ViewportHooks;
use egui::{Context, RawInput, ViewportId};
/// The ordinary app input hook leaves files in `raw` for the runtime's own reading.
pub(crate) fn forward_app_input(sender: &IntakeSender, raw: &RawInput) {
sender.dropped(
raw.dropped_files
.iter()
.map(|file| {
dropped_path(file.path()).unwrap_or_else(|| DroppedFile { path: None, name: String::new(), bytes: file.bytes().ok().map(Arc::from) })
})
.collect(),
);
}
fn dropped_path(path: &Path) -> Option<DroppedFile> {
if path.as_os_str().is_empty() {
return None;
}
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
Some(DroppedFile { path: Some(path.to_path_buf()), name, bytes: None })
}
/// Immediate child input in the windowless trial.
pub(crate) struct ChildDrops(pub(crate) IntakeSender);
impl ViewportHooks for ChildDrops {
fn raw_input(&self, _ctx: &Context, raw: &mut RawInput) {
// Immediate viewports skip App::raw_input_hook. The regular ROOT input still goes there.
// Consume this child batch so no later hook or pass feeds it again. Native OS drops carry
// paths: pass those through without reading the files on the event loop.
if raw.viewport_id != ViewportId::ROOT && !raw.dropped_files.is_empty() {
self.0.dropped(raw.dropped_files.drain(..).filter_map(|file| dropped_path(file.path())).collect());
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
use craft::host::Wake;
use craft::platform::open::{FileIntake, Intake};
#[derive(Debug)]
struct NativeDrop(PathBuf);
impl egui::DroppedFile for NativeDrop {
fn path(&self) -> &Path {
&self.0
}
fn bytes(&self) -> Result<Vec<u8>, String> {
panic!("the raw-input hook must not read native dropped files");
}
}
fn raw_drops(viewport_id: ViewportId, paths: &[PathBuf]) -> RawInput {
RawInput {
viewport_id,
dropped_files: paths.iter().map(|path| Arc::new(NativeDrop(path.clone())) as egui::DroppedFileHandle).collect(),
..Default::default()
}
}
#[test]
fn child_drop_enters_intake_once_in_drop_order() {
let (intake, sender) = FileIntake::new(Wake::none());
let hooks = ChildDrops(sender.clone());
let ctx = Context::default();
let child = ViewportId::from_hash_of("document");
let paths = [std::env::temp_dir().join("second.docx"), std::env::temp_dir().join("first.docx")];
let mut raw = raw_drops(child, &paths);
// The immediate child goes through the viewport hook, not the App hook.
hooks.raw_input(&ctx, &mut raw);
let batches = intake.take();
let [Intake::Dropped { files }] = batches.as_slice() else { panic!("expected one child drop batch, got {batches:?}") };
assert!(files.iter().map(|file| file.path.as_ref()).eq(paths.iter().map(Some)));
// A replay of this input, or another input path seeing it, cannot send it again.
hooks.raw_input(&ctx, &mut raw);
forward_app_input(&sender, &raw);
assert!(intake.take().is_empty());
}
#[test]
fn root_drop_still_reaches_intake_only_from_app_input() {
let (intake, sender) = FileIntake::new(Wake::none());
let hooks = ChildDrops(sender.clone());
let ctx = Context::default();
let path = std::env::temp_dir().join("document.docx");
let mut raw = raw_drops(ViewportId::ROOT, std::slice::from_ref(&path));
// Pinned eframe calls both hooks on ROOT, in this order.
hooks.raw_input(&ctx, &mut raw);
assert!(intake.take().is_empty());
forward_app_input(&sender, &raw);
let batches = intake.take();
let [Intake::Dropped { files }] = batches.as_slice() else { panic!("expected one root drop batch, got {batches:?}") };
assert!(matches!(files.as_slice(), [file] if file.path.as_ref() == Some(&path)));
assert!(matches!(raw.dropped_files.as_slice(), [file] if file.path() == path.as_path()));
}
}
+105 -164
View File
@@ -1,174 +1,132 @@
//! Launcher-owned nightly-v1 bootstrap. Selected before logging, preferences, fonts or saved state.
//! Stable launches retain their original arguments and directory policy. No environment mutation.
//! Nightly-v1 bootstrap backed by `craft-nightly`. Selected before logging, preferences, fonts or
//! saved state. Stable launches retain their original arguments and directory policy.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use std::sync::OnceLock;
use std::ffi::{OsStr, OsString};
pub const VERSION: &str = "nightly-v1";
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Profile {
Stable,
NightlyV1(PathBuf),
}
impl Profile {
pub fn is_nightly(&self) -> bool {
matches!(self, Self::NightlyV1(_))
}
pub fn root(&self) -> Option<&Path> {
match self {
Self::Stable => None,
Self::NightlyV1(root) => Some(root),
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct Launch {
pub profile: Profile,
pub args: Vec<OsString>,
}
static PROFILE: OnceLock<Profile> = OnceLock::new();
pub use craft_nightly::Profile;
/// Returns the active launch profile for this process, defaulting to [`Profile::Stable`] before
/// `craft_nightly::prepare_launch` installs one.
pub fn current() -> &'static Profile {
PROFILE.get().unwrap_or(&Profile::Stable)
static STABLE: Profile = Profile::Stable;
craft_nightly::current().unwrap_or(&STABLE)
}
pub fn install(profile: Profile) -> Result<(), String> {
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into())
fn is_nightly_flag_token(arg: &OsStr) -> bool {
arg.to_str().is_some_and(|s| {
s == craft_nightly::LAUNCH_PROFILE_FLAG
|| s == craft_nightly::PROFILE_ROOT_FLAG
|| s.starts_with("--launch-profile=")
|| s.starts_with("--profile-root=")
})
}
/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is
/// a file, even when it looks like a profile flag. No filesystem or startup hook runs here.
pub fn parse(args: Vec<OsString>) -> Result<Launch, String> {
let mut selector = None;
let mut root = None;
let mut other = Vec::new();
let mut files = Vec::new();
let mut iter = args.iter();
let mut delimiter = false;
while let Some(arg) = iter.next() {
if arg == "--" {
delimiter = true;
files.extend(iter.cloned());
break;
}
if arg == "--launch-profile" || arg == "--profile-root" {
let slot = if arg == "--launch-profile" { &mut selector } else { &mut root };
if slot.is_some() {
return Err("the profile selector and root must each occur exactly once".into());
}
let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?;
if value.to_string_lossy().starts_with("--") {
return Err("the profile selector/root needs a value".into());
}
*slot = Some(value.clone());
} else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") {
return Err("the nightly protocol requires separate literal selector/root argument tokens".into());
} else {
other.push(arg.clone());
}
}
match (selector, root) {
(None, None) => Ok(Launch { profile: Profile::Stable, args }),
(Some(version), Some(root)) if version == VERSION => {
if !delimiter || !other.is_empty() {
return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into());
}
let root = PathBuf::from(root);
if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) {
return Err("the nightly profile root must be absolute and contain no parent traversal".into());
}
Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() })
}
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()),
_ => Err("--launch-profile and --profile-root must be supplied together".into()),
}
}
/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`),
/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never
/// validated or touched, and `-- --version` stays a file name.
pub fn version_query(args: &[OsString]) -> bool {
let Some((last, pair)) = args.split_last() else { return false };
if last != "--version" && last != "-V" {
/// Returns `true` when `args` starts with nightly launch protocol flags followed by `--`.
/// `craft_nightly::parse_startup` consumes that `--`; preserving it lets `main.rs`'s
/// `split_at_delimiter` treat every argument after `--` as a document path.
pub fn had_launcher_separator(args: &[OsString]) -> bool {
if !args.first().is_some_and(|arg| is_nightly_flag_token(arg)) {
return false;
}
let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect();
matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1)
let mut idx = 0;
while let Some(arg) = args.get(idx) {
if arg == "--" {
return true;
}
if arg == craft_nightly::LAUNCH_PROFILE_FLAG || arg == craft_nightly::PROFILE_ROOT_FLAG {
idx += 2;
} else if arg.to_str().is_some_and(|s| s.starts_with("--launch-profile=") || s.starts_with("--profile-root=")) {
idx += 1;
} else {
break;
}
}
false
}
/// Validation finishes before the caller's first startup effect. Stable never calls the nightly
/// root validator, so its old settings-folder resolution stays unchanged.
pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result<PathBuf, String>) -> Result<Launch, String> {
if let Profile::NightlyV1(root) = &launch.profile {
launch.profile = Profile::NightlyV1(validate(root)?);
}
Ok(launch)
/// Re-attaches the `--` separator when `craft_nightly` stripped one from an explicit launcher
/// header, leaving direct-launch arguments untouched.
pub fn passthrough_args(args: Vec<OsString>, had_separator: bool) -> Vec<OsString> {
if had_separator { std::iter::once(OsString::from("--")).chain(args).collect() } else { args }
}
/// The root the Launcher hands a nightly on this platform, in that platform's own spelling: `C:\NightlyData\profiles\wordcraft`
/// on Windows, `/nightly-data/profiles/wordcraft` elsewhere. A test that fixtures the hand-off uses this rather than a
/// literal, because a root literal in the other platform's spelling is not absolute here and `parse` refuses it (#7849).
/// literal, because a root literal in the other platform's spelling is not absolute here and validation refuses it (#7849).
#[cfg(test)]
pub(crate) fn launcher_root() -> &'static str {
if cfg!(windows) { r"C:\NightlyData\profiles\wordcraft" } else { "/nightly-data/profiles/wordcraft" }
}
/// Resolve the selected private root before the caller's first startup effect.
pub fn validate_root(root: &Path) -> Result<PathBuf, String> {
crate::profile_root::validate(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref(), crate::profile_root::probe_writable)
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
use super::{had_launcher_separator, launcher_root, passthrough_args};
use craft_nightly::{
BuildFlavor, NIGHTLY_V1_CONTRACT, Profile, ProfileError, StartupOptions, canonical_profile_root, parse_startup, validate_and_prepare_root,
};
use std::ffi::OsString;
use std::path::PathBuf;
fn args(values: &[&str]) -> Vec<OsString> {
values.iter().map(OsString::from).collect()
}
fn absolute() -> &'static str {
super::launcher_root()
launcher_root()
}
fn nightly() -> Vec<OsString> {
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"])
}
#[test]
fn stable_arguments_and_directory_policy_are_unchanged() {
let spec = crate::profile_root::spec();
for argv in [args(&[]), args(&["--control", "7981", "a.docx"]), args(&["--", "--launch-profile", "file.docx"])] {
let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap();
assert_eq!(launch, Launch { profile: Profile::Stable, args: argv });
let had_sep = had_launcher_separator(&argv);
assert!(!had_sep);
let launch = parse_startup(BuildFlavor::Stable, &spec, argv.clone(), &StartupOptions::new()).unwrap();
assert_eq!(launch.profile, Profile::Stable);
assert_eq!(passthrough_args(launch.passthrough_args, had_sep), argv);
}
}
#[test]
fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() {
let mut argv = nightly();
argv.extend(args(&["--profile-root", "letter with spaces.docx"]));
let launch = parse(argv).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
assert_eq!(launch.args, args(&["--", "--profile-root", "letter with spaces.docx"]));
fn direct_nightly_launch_resolves_canonical_root_and_preserves_user_arguments() {
let spec = crate::profile_root::spec();
let expected_root = canonical_profile_root(spec.app_id).unwrap();
let argv = args(&["--sample", "letter.docx"]);
let had_sep = had_launcher_separator(&argv);
assert!(!had_sep);
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::new()).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(expected_root));
assert_eq!(passthrough_args(launch.passthrough_args, had_sep), argv);
}
#[test]
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() {
let spec = crate::profile_root::spec();
let mut argv = nightly();
argv.extend(args(&["--profile-root", "letter with spaces.docx"]));
let had_sep = had_launcher_separator(&argv);
assert!(had_sep);
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new()).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
assert_eq!(passthrough_args(launch.passthrough_args, had_sep), args(&["--", "--profile-root", "letter with spaces.docx"]));
}
#[test]
fn missing_duplicate_and_unknown_profile_arguments_are_refused() {
let spec = crate::profile_root::spec();
for argv in [
args(&["--launch-profile", VERSION]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT]),
args(&["--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--sample", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", "", "--"]),
] {
assert!(parse(argv).is_err());
assert!(parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new()).is_err());
}
}
@@ -177,53 +135,36 @@ mod tests {
/// instead of run against a directory this platform never meant.
#[test]
fn a_root_absolute_only_in_the_other_platforms_spelling_is_refused() {
let spec = crate::profile_root::spec();
let foreign = if cfg!(windows) { "/nightly-data/profiles/wordcraft" } else { r"C:\NightlyData\profiles\wordcraft" };
let argv = args(&["--launch-profile", VERSION, "--profile-root", foreign, "--"]);
assert!(parse(argv).is_err(), "the other platform's root spelling must not stand in: {foreign}");
let err = validate_and_prepare_root(std::path::Path::new(foreign), &spec).unwrap_err();
assert!(matches!(err, ProfileError::RelativeProfileRoot(_)), "the other platform's root spelling must not stand in: {foreign}");
}
#[test]
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION];
fn launcher_and_plain_version_queries_are_recognized() {
let spec = crate::profile_root::spec();
let pair = &["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute()];
let reversed = &["--profile-root", absolute(), "--launch-profile", NIGHTLY_V1_CONTRACT];
for flag in ["--version", "-V"] {
let plain = parse_startup(BuildFlavor::NightlyV1, &spec, args(&[flag]), &StartupOptions::new()).unwrap();
assert!(plain.is_version_query());
for form in [pair, reversed] {
let mut argv = args(form);
argv.push(flag.into());
assert!(version_query(&argv), "{argv:?}");
let direct = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::new()).unwrap();
assert!(direct.is_version_query());
argv.push("letter with spaces.docx".into());
let with_document = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new()).unwrap();
assert!(!with_document.is_version_query());
assert_eq!(with_document.passthrough_args, args(&[flag, "letter with spaces.docx"]));
let mut with_sep = args(form);
with_sep.push("--".into());
with_sep.push(flag.into());
let separated = parse_startup(BuildFlavor::NightlyV1, &spec, with_sep, &StartupOptions::new()).unwrap();
assert!(separated.is_version_query());
}
}
for argv in [
args(&["--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--sample", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]),
args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]),
args(&["--launch-profile", VERSION, "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]),
] {
assert!(!version_query(&argv), "{argv:?}");
}
// Outside the query the strict protocol still refuses the version flag.
assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err());
}
#[test]
fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() {
let reached = Cell::new(false);
let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true));
assert!(result.is_err());
assert!(!reached.get());
}
#[test]
fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() {
let checked = PathBuf::from(absolute()).join("checked");
let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap();
assert_eq!(launch.profile.root(), Some(checked.as_path()));
assert!(launch.profile.is_nightly());
}
}
+268 -195
View File
@@ -19,6 +19,8 @@ mod build_channel;
mod build_flavor;
mod control_server;
mod default_apps;
mod document_panels;
mod drop_intake;
mod launch_profile;
#[cfg(target_os = "macos")]
mod native_menu;
@@ -27,6 +29,7 @@ mod prefs;
mod process_identity;
mod profile_root;
mod region;
mod startup_mode;
use std::path::PathBuf;
use std::sync::{Arc, Mutex, OnceLock};
@@ -40,12 +43,12 @@ use craft::platform::appearance::SystemReader;
use craft::platform::clipboard::{Clipboard, ClipboardImage, SystemClipboard};
use craft::platform::default_app::{DefaultApp, DefaultAppError};
use craft::platform::logs::{self, LogNames, crash};
use craft::platform::open::{DroppedFile, FileIntake, IntakeSender};
use craft::platform::open::{FileIntake, IntakeSender};
use craft::print::spool::Spool;
use craft::settings::SharedSettings;
use craft::ui::InstallSpec;
use craft::ui::runtime::windows::{WindowAction, WindowHost};
use craft::ui::shell::embed;
use craft::ui::shell::embed::{self, CloseDecision};
use craft::window::restore::{self, Store};
use craft::window::system::SystemWindows;
use wordcraft_engine::Session;
@@ -60,6 +63,8 @@ struct App {
native_menu: Option<craft::menu::NativeMenu>,
/// The native panels behind the file service the app reaches through `Host::files`.
panels: FilePanels,
/// Native parent windows for the owned picker route, populated only in windowless mode.
document_windows: document_panels::DocumentWindows,
/// Feeds the files dropped on the window into the app's intake (`Services::intake`), the one
/// queue the OS's requests are read from.
drops: IntakeSender,
@@ -86,19 +91,35 @@ impl App {
/// One frame's logic: what the OS asked, the app, its file dialogs, then the root window's close
/// path. Without `frame` (a test over no window) the dialogs have no parent window.
fn logic_pass(&mut self, ctx: &egui::Context, frame: Option<&eframe::Frame>) {
// Validate native incarnations before WordApp logic can settle an available answer.
// A final Quit from a previous pass takes priority over launching any new pick.
if self.app.quit_requested {
self.app.quiesce_native_file_panels();
}
self.app.pump_owned_picks(ctx, &mut self.document_windows);
self.app.logic(ctx);
#[cfg(target_os = "macos")]
if let Some(menu) = &mut self.native_menu {
native_menu::update(menu, &mut self.app, ctx);
}
self.panels.pump_with(self.app.dialog_host_mut(), frame);
// A quit that waits for nothing (the documents are answered for) closes the root window.
if self.app.quit_requested && !self.app.printing.busy() {
// Once the document guards have settled Quit, not even this pass's last pump can open
// another picker. Keep the event loop and display alive for handles already in use.
if self.app.quit_requested {
self.app.quiesce_native_file_panels();
}
self.pump_file_panels(ctx, frame);
if self.app.quit_requested && !self.app.printing.busy() && !self.app.native_file_panels_open() {
WindowHost::of(ctx).act(egui::ViewportId::ROOT, WindowAction::Close);
}
// The decision holds the close while a Save Changes prompt is open; a closure over
// `close_requested` would ask again on every frame of the prompt.
embed::logic(ctx, || self.app.close_decision());
// A platform close can be accepted without setting quit_requested (e.g. no unsaved work).
// Shut off new launches only when that final close is accepted, not before a Save prompt.
embed::logic(ctx, || {
let decision = self.app.close_decision();
if matches!(decision, CloseDecision::Close) {
self.app.quiesce_native_file_panels();
}
decision
});
}
/// One pass of the root window's UI.
@@ -107,7 +128,12 @@ impl App {
embed::before_ui(ui.ctx(), frame);
}
self.app.ui(ui);
self.pump_file_panels(ui.ctx(), frame);
}
fn pump_file_panels(&mut self, ctx: &egui::Context, frame: Option<&eframe::Frame>) {
self.panels.pump_with(self.app.dialog_host_mut(), frame);
self.app.pump_owned_picks(ctx, &mut self.document_windows);
}
/// Everything that must happen before the process ends, whichever way the window closes.
@@ -134,11 +160,7 @@ impl eframe::App for App {
/// Hands the app what the runtime gathered since the last frame (fired commands) and the
/// runtime the input the app gives back, before any pass of the frame runs.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
// Once per frame, before any pass; the files stay in `raw` for the runtime's own reading.
let files = dropped_files(raw);
if !files.is_empty() {
self.drops.dropped(files);
}
drop_intake::forward_app_input(&self.drops, raw);
self.before_input(ctx);
}
fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
@@ -152,21 +174,6 @@ impl eframe::App for App {
}
}
/// The files dropped in this frame's input, as the intake carries them: a file with a path by its
/// path, a file without one by its bytes.
fn dropped_files(raw: &egui::RawInput) -> Vec<DroppedFile> {
raw.dropped_files
.iter()
.map(|file| {
let path = Some(file.path().to_path_buf()).filter(|p| !p.as_os_str().is_empty());
let name = path.as_ref().and_then(|p| p.file_name()).map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
// A file without a path (the web) carries its bytes; one that cannot be read is dropped as empty.
let bytes = if path.is_none() { file.bytes().ok().map(std::sync::Arc::from) } else { None };
DroppedFile { path, name, bytes }
})
.collect()
}
/// Whether the window runs through XWayland (X11) rather than native Wayland, and the log line
/// saying why. `WORDCRAFT_WAYLAND` wins (`0`, `false`, `no` or `off` asks for X11, any other value
/// for Wayland), then File › Options › Advanced › Linux display server (#2184). Automatic is X11
@@ -415,34 +422,40 @@ fn report_launch_profile_error(error: &str) {
/// Select the immutable launch profile before any startup service or side effect.
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
// The trusted Launcher protocol is decided before logging, crash handling, the update helper,
// The launch profile is decided before logging, crash handling, the update helper,
// fonts, preferences or the settings folder.
let argv: Vec<_> = std::env::args_os().skip(1).collect();
// Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
// --version`: answered before root validation, process identity, IPC or any window.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv))
{
// Plain `--version` / `-V` on nightly: answered before root resolution, validation,
// process identity, IPC or any window.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && build_flavor::version_query(&argv) {
let line = build_flavor::version(build_flavor::COMPILED, env!("WORDCRAFT_BUILT_VERSION"));
let _ = std::io::Write::write_all(&mut std::io::stdout(), format!("{line}\n").as_bytes());
return None;
}
let early = launch_profile::parse(argv)
.and_then(|launch| {
build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?;
initialize_nightly_process_identity().map_err(|error| error.to_string())?;
Ok(launch)
})
.and_then(|launch| launch_profile::prepare(launch, launch_profile::validate_root))
let had_separator = launch_profile::had_launcher_separator(&argv);
let early = craft_nightly::prepare_launch(build_flavor::COMPILED, &profile_root::spec(), argv, &craft_nightly::StartupOptions::new())
.unwrap_or_else(|error| {
report_launch_profile_error(&error);
report_launch_profile_error(&error.to_string());
std::process::exit(2)
});
// Launcher `--launch-profile nightly-v1 --profile-root <dir> [--] --version` / `-V`:
// `craft_nightly::prepare_launch` skips root validation and profile installation for
// version queries, so answer and exit before any startup side effect.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && early.is_version_query() {
let line = build_flavor::version(build_flavor::COMPILED, env!("WORDCRAFT_BUILT_VERSION"));
let _ = std::io::Write::write_all(&mut std::io::stdout(), format!("{line}\n").as_bytes());
return None;
}
if let Err(error) = initialize_nightly_process_identity() {
report_launch_profile_error(&error.to_string());
std::process::exit(2);
}
let identity = if early.profile.is_nightly() {
wordcraft_ui_egui::os_window::LaunchIdentity::NightlyV1
} else {
wordcraft_ui_egui::os_window::LaunchIdentity::Stable
};
if let Err(error) = launch_profile::install(early.profile).and_then(|()| wordcraft_ui_egui::os_window::select_identity(identity)) {
if let Err(error) = wordcraft_ui_egui::os_window::select_identity(identity) {
report_launch_profile_error(&error);
std::process::exit(2);
}
@@ -454,7 +467,7 @@ fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
report_launch_profile_error(&error);
std::process::exit(2);
}
Some(early.args)
Some(launch_profile::passthrough_args(early.passthrough_args, had_separator))
}
/// Parses the command line, installs logging and the panic hook, restores preferences and window
@@ -486,6 +499,9 @@ fn main() -> eframe::Result {
let updates_unsafe = start_over_failed.is_some();
#[cfg(not(target_os = "linux"))]
let updates_unsafe = false;
// Before any thread or logger starts: re-exec on Linux glibc with MALLOC_TRIM_THRESHOLD_
// fixed so large freed document/render buffers return to the OS.
wordcraft_engine::malloc_tuning::apply();
// First, so the panic hook (set once, by this call; the later one only gives it the crash-log
// folder) and every start-up warning are recorded.
let logger = logs::install(LogNames::new("wordcraft"));
@@ -607,25 +623,17 @@ fn main() -> eframe::Result {
Some(_) => wordcraft_ui_egui::os_window::app_id().to_string(),
None => std::env::var("FLATPAK_ID").ok().filter(|id| !id.is_empty()).unwrap_or_else(|| wordcraft_ui_egui::os_window::APP_ID.to_string()),
};
let mut options = eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_title(wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity()))
.with_app_id(app_id)
.with_inner_size([1440.0, 920.0])
.with_min_inner_size(wordcraft_ui_egui::window_geometry::MIN_SIZE)
.with_drag_and_drop(true)
.with_fullsize_content_view(true)
.with_titlebar_shown(false)
.with_title_shown(false),
..Default::default()
};
let mut viewport = egui::ViewportBuilder::default()
.with_title(wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity()))
.with_app_id(app_id)
.with_inner_size([1440.0, 920.0])
.with_min_inner_size(wordcraft_ui_egui::window_geometry::MIN_SIZE)
.with_drag_and_drop(true)
.with_fullsize_content_view(true)
.with_titlebar_shown(false)
.with_title_shown(false);
if let Some(icon) = app_icon() {
options.viewport = options.viewport.with_icon(icon);
}
// Before eframe creates the wgpu instance: the backends, power preference, shader compiler and
// the GPU that drives the screen (#603, #2652, #5199).
if let eframe::egui_wgpu::WgpuSetup::CreateNew(setup) = &mut options.wgpu_options.wgpu_setup {
craft::gpu::configure(setup);
viewport = viewport.with_icon(icon);
}
prefs::load_user_fonts();
// Where the root window was last, kept beside the settings; in memory when preferences are off.
@@ -644,16 +652,18 @@ fn main() -> eframe::Result {
let display_server = settings.lock().get().display_server;
let (x11, why) = uses_x11(display_server, |name| std::env::var_os(name), x11_libraries);
log::info!("{why}");
if x11 {
options.event_loop_builder = Some(Box::new(|b| {
use winit::platform::x11::EventLoopBuilderExtX11;
b.with_x11();
}));
}
x11
};
#[cfg(not(all(unix, not(target_os = "macos"))))]
let x11 = false;
// The windowless root by default; windowed when rolled back, or when winit will open X11 or
// XWayland, which its bootstrap doesn't support (`startup_mode`).
#[cfg(all(unix, not(target_os = "macos")))]
let winit_x11 = startup_mode::winit_picks_x11(x11, |name| std::env::var_os(name));
#[cfg(not(all(unix, not(target_os = "macos"))))]
let winit_x11 = false;
let first_mode = startup_mode::first_mode(std::env::var_os(startup_mode::ROLLBACK_VAR).as_deref(), winit_x11);
log::info!("root: {first_mode:?} first");
// What the OS asks of a running app arrives here; its wake repaints once the window exists.
let repaint: Arc<OnceLock<egui::Context>> = Arc::new(OnceLock::new());
let (intake, sender) = FileIntake::new(Wake::new({
@@ -664,9 +674,39 @@ fn main() -> eframe::Result {
}
}
}));
let drops = intake.sender();
// Each start's options, from scratch: a fallback start gets the plain windowed ones.
let hook_drops = drops.clone();
let document_windows = document_panels::DocumentWindows::default();
let hook_windows = document_windows.clone();
let native_options = move |mode: eframe::RootViewportMode| {
let mut options = eframe::NativeOptions {
root_viewport_mode: mode,
// A refused start must return here, on the thread whose event loop the fallback reuses.
run_and_return: true,
viewport: viewport.clone(),
..Default::default()
};
// Before eframe creates the wgpu instance: the backends, power preference, shader compiler
// and the GPU that drives the screen (#603, #2652, #5199).
if let eframe::egui_wgpu::WgpuSetup::CreateNew(setup) = &mut options.wgpu_options.wgpu_setup {
craft::gpu::configure(setup);
}
// Read only when the first start builds the event loop; a fallback reuses that loop.
#[cfg(all(unix, not(target_os = "macos")))]
if x11 {
options.event_loop_builder = Some(Box::new(|b| {
use winit::platform::x11::EventLoopBuilderExtX11;
b.with_x11();
}));
}
if mode == eframe::RootViewportMode::Windowless {
options.viewport_hooks = Some(hook_windows.hooks(hook_drops.clone()));
}
options
};
// Registered before the event loop starts, so it catches the Finder event that launched us as
// well as later ones. Lives until the event loop returns.
let drops = intake.sender();
#[cfg(target_os = "macos")]
let _apple_events = craft::platform::open::apple_events::install(sender);
#[cfg(not(target_os = "macos"))]
@@ -696,138 +736,161 @@ fn main() -> eframe::Result {
let noticed_for_exit = unclean_notice_shown.clone();
let noticed_in_window = unclean_notice_shown.clone();
let exit_settings = settings.clone();
let result = eframe::run_native(
wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity()),
options,
Box::new(move |cc| {
let ctx = cc.egui_ctx.clone();
let _ = repaint.set(ctx.clone());
let wake = {
let ctx = ctx.clone();
move || ctx.request_repaint()
};
// The interface language: the saved choice, else the system's.
let lang = wordcraft_ui_egui::i18n::Lang::from_pref(&settings.lock().get().language);
let (file_service, panels) = FileService::new(Wake::new(wake.clone()));
let host = Arc::new(
Host::builder(wordcraft_ui_egui::APP)
.i18n(wordcraft_ui_egui::i18n::catalogs())
.files(Arc::new(file_service))
.settings(Arc::new(settings.clone()))
.lang(lang.craft_lang())
.build(),
);
let shell = ShellInfo::current().backend(if x11 { Backend::X11 } else { Backend::from_env() });
let spec = InstallSpec::new(shell, Arc::new(SystemWindows))
.app_id(wordcraft_ui_egui::os_window::app_id())
.system(SystemReader::start(wake))
.clipboard(Clipboard::new(SystemClipboard::new().decoder(decode_png)))
.placement(placement);
// PLAN: assumed `wordcraft_ui_egui::ui_fonts` re-exports sh.A10's `app::fonts::ui_fonts` (`mod app` is private; app-hub/shell-w11).
embed::install(&ctx, spec, &wordcraft_ui_egui::ui_fonts(lang)).map_err(|e| format!("the runtime could not be installed: {e}"))?;
// The system region picks the new document's paper, the units and the decimal
// separator (#838).
let region = region::system();
let doc = if sample { wordcraft_engine::sample::sample_document() } else { wordcraft_engine::blank_document(&region) };
let mut session = Session::new(doc);
session.system_region = region;
// The custom dictionary's words (#40) count as loaded settings.
if prefs::enabled()
&& let Some(path) = prefs::user_dict_path()
{
prefs::load_user_dictionary(&mut session, &settings, path);
// Everything a start hands the app, used by the one creator that runs (`startup_mode::run`).
let create_app = move |cc: &eframe::CreationContext<'_>,
mode: eframe::RootViewportMode|
-> Result<Box<dyn eframe::App>, Box<dyn std::error::Error + Send + Sync>> {
let ctx = cc.egui_ctx.clone();
let _ = repaint.set(ctx.clone());
let wake = {
let ctx = ctx.clone();
move || ctx.request_repaint()
};
// The interface language: the saved choice, else the system's.
let lang = wordcraft_ui_egui::i18n::Lang::from_pref(&settings.lock().get().language);
let (file_service, panels) = FileService::new(Wake::new(wake.clone()));
let host = Arc::new(
Host::builder(wordcraft_ui_egui::APP)
.i18n(wordcraft_ui_egui::i18n::catalogs())
.files(Arc::new(file_service))
.settings(Arc::new(settings.clone()))
.lang(lang.craft_lang())
.build(),
);
let shell = ShellInfo::current().backend(if x11 { Backend::X11 } else { Backend::from_env() });
let spec = InstallSpec::new(shell, Arc::new(SystemWindows))
.app_id(wordcraft_ui_egui::os_window::app_id())
.system(SystemReader::start(wake))
.clipboard(Clipboard::new(SystemClipboard::new().decoder(decode_png)))
.placement(placement);
// PLAN: assumed `wordcraft_ui_egui::ui_fonts` re-exports sh.A10's `app::fonts::ui_fonts` (`mod app` is private; app-hub/shell-w11).
embed::install(&ctx, spec, &wordcraft_ui_egui::ui_fonts(lang)).map_err(|e| format!("the runtime could not be installed: {e}"))?;
// The system region picks the new document's paper, the units and the decimal
// separator (#838).
let region = region::system();
let doc = if sample { wordcraft_engine::sample::sample_document() } else { wordcraft_engine::blank_document(&region) };
let mut session = Session::new(doc);
session.system_region = region;
// The custom dictionary's words (#40) count as loaded settings.
if prefs::enabled()
&& let Some(path) = prefs::user_dict_path()
{
prefs::load_user_dictionary(&mut session, &settings, path);
}
let spool = Spool::new(host.jobs_shared().clone());
let mut app = WordApp::new(session, services(spool.clone(), intake, nightly)).with_host(host).with_settings(settings.clone());
let windowless = mode == eframe::RootViewportMode::Windowless;
app.enable_windowless_trial(windowless);
if windowless {
app.set_native_window_lookup(Some(Arc::new(document_windows.clone())));
}
// Drawn by the processor (WARP, llvmpipe; #2221), animations that follow the system stop.
if let Some(state) = &cc.wgpu_render_state {
let info = state.adapter.get_info();
let software = info.device_type == eframe::wgpu::DeviceType::Cpu;
if software {
log::warn!("graphics: drawing in software on {} ({:?}): animations that follow the system are off", info.name, info.backend);
}
let spool = Spool::new(host.jobs_shared().clone());
let mut app = WordApp::new(session, services(spool.clone(), intake, nightly)).with_host(host).with_settings(settings.clone());
// PLAN: writer note 9 puts `with_settings` after `with_control`; it comes first here because
// the region check below reads the saved region the settings apply.
if std::env::var("WORDCRAFT_FILE_DIALOG").is_ok_and(|v| v.trim().eq_ignore_ascii_case("builtin")) {
app = app.with_fallback_chooser(true);
app.set_software_drawing(software);
}
// PLAN: writer note 9 puts `with_settings` after `with_control`; it comes first here because
// the region check below reads the saved region the settings apply.
if std::env::var("WORDCRAFT_FILE_DIALOG").is_ok_and(|v| v.trim().eq_ignore_ascii_case("builtin")) {
app = app.with_fallback_chooser(true);
}
if nightly {
// The Launcher installs Nightly; Help › Check for Updates says so instead.
app.use_launcher_updates();
} else {
app.set_startup_update_check(true);
// After the preferences, so the reason it gives is in the interface language.
if updates_unsafe {
app.disable_self_update();
}
if nightly {
// The Launcher installs Nightly; Help › Check for Updates says so instead.
app.use_launcher_updates();
} else {
app.set_startup_update_check(true);
// After the preferences, so the reason it gives is in the interface language.
if updates_unsafe {
app.disable_self_update();
}
}
// Language packs from the suite's font store; an Install click is the person's own.
// Nightly keeps its own store in the profile, so a pack installed there is not a
// change to the stable apps' shared fonts.
match launch_profile::current().root() {
Some(root) => wordcraft_engine::packs::use_font_store_in(root.join("FontStore"), true),
None => {
wordcraft_engine::packs::use_font_store(true);
}
// Language packs from the suite's font store; an Install click is the person's own.
// Nightly keeps its own store in the profile, so a pack installed there is not a
// change to the stable apps' shared fonts.
match launch_profile::current().root() {
Some(root) => wordcraft_engine::packs::use_font_store_in(root.join("FontStore"), true),
None => {
wordcraft_engine::packs::use_font_store(true);
}
}
// A region chosen in File › Options replaces the system's for the first blank
// document too (#838).
if !sample && app.session.prefs.region.is_some() {
let doc = app.session.blank_document();
app.replace_startup_document(doc);
}
app.tell_about_font_downloads();
if prefs::enabled()
&& let Some(dir) = wordcraft_control_key::settings_dir()
{
let ctx = ctx.clone();
if let Err(e) = app.session.enable_recovery(dir.join("recovery"), Arc::new(move || ctx.request_repaint())) {
log::warn!("local recovery unavailable: {e}");
}
// A region chosen in File › Options replaces the system's for the first blank
// document too (#838).
if !sample && app.session.prefs.region.is_some() {
let doc = app.session.blank_document();
app.replace_startup_document(doc);
}
let mut control_server = None;
if !nightly
&& let Some(port) = control.port
&& let Some((rx, started)) = control_server::start(&control, port, WindowHost::of(&ctx), wordcraft_control_key::settings_dir().as_deref())
{
app = app.with_control(ControlChannel::new(rx));
control_server = Some(started);
}
// Nothing to open (no files, no sample, no control channel driving the editor): start
// on File › Home, as Word does (#766), unless the Start screen option is off. Files
// the OS hands over later open on top of it and close it.
if files.is_empty() && other_files.is_empty() && !sample && control.port.is_none() {
app.start_screen();
}
// A Word template named here starts a new document based on it (#3433).
for f in files {
if let Err(e) = app.open_from_platform(&f, None) {
app.report_open_failure(&f, &e);
}
app.tell_about_font_downloads();
if prefs::enabled()
&& let Some(dir) = wordcraft_control_key::settings_dir()
{
let ctx = ctx.clone();
if let Err(e) = app.session.enable_recovery(dir.join("recovery"), Arc::new(move || ctx.request_repaint())) {
log::warn!("local recovery unavailable: {e}");
}
}
let mut control_server = None;
if !nightly
&& let Some(port) = control.port
&& let Some((rx, started)) =
control_server::start(&control, port, WindowHost::of(&ctx), wordcraft_control_key::settings_dir().as_deref())
{
app = app.with_control(ControlChannel::new(rx));
control_server = Some(started);
}
// Nothing to open (no files, no sample, no control channel driving the editor): start
// on File › Home, as Word does (#766), unless the Start screen option is off. Files
// the OS hands over later open on top of it and close it.
if files.is_empty() && other_files.is_empty() && !sample && control.port.is_none() {
app.start_screen();
}
// A Word template named here starts a new document based on it (#3433).
for f in files {
if let Err(e) = app.open_from_platform(&f, None) {
app.report_open_failure(&f, &e);
}
}
for f in other_files {
open_non_unicode(&mut app, &f);
}
// The personal agent files, the session record and the control token all live in the
// profile; the app's own services are built with the nightly rule in mind.
if let Some(warning) = &session_health_warning {
app.status_long(warning.clone());
}
if previous_nightly_unclean {
app.status_long(
}
for f in other_files {
open_non_unicode(&mut app, &f);
}
// The personal agent files, the session record and the control token all live in the
// profile; the app's own services are built with the nightly rule in mind.
if let Some(warning) = &session_health_warning {
app.status_long(warning.clone());
}
if previous_nightly_unclean {
app.status_long(
"The previous WordCraft Nightly session did not finish normally. You can report a problem from Help › About. No diagnostics have been sent.",
);
noticed_in_window.store(true, std::sync::atomic::Ordering::Relaxed);
}
Ok(Box::new(App {
#[cfg(target_os = "macos")]
native_menu: native_menu::install(&ctx, &app),
app,
panels,
drops,
settings,
spool,
control: control_server,
exit: Some(Box::new(move || {
nightly_session::finish_once(&session_for_exit, noticed_for_exit.load(std::sync::atomic::Ordering::Relaxed));
})),
}))
}),
);
noticed_in_window.store(true, std::sync::atomic::Ordering::Relaxed);
}
Ok(Box::new(App {
#[cfg(target_os = "macos")]
native_menu: native_menu::install(&ctx, &app),
app,
panels,
document_windows,
drops,
settings,
spool,
control: control_server,
exit: Some(Box::new(move || {
nightly_session::finish_once(&session_for_exit, noticed_for_exit.load(std::sync::atomic::Ordering::Relaxed));
})),
}))
};
let result = startup_mode::run(first_mode, create_app, |mode, inputs| {
eframe::run_native(
wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity()),
native_options(mode),
Box::new(move |cc| {
let create = inputs.take().ok_or("the app was already created")?;
create(cc, mode)
}),
)
});
// The exit hook has run; this is the no-op fallback for a start that created no window.
nightly_session::finish_once(&nightly_watch, unclean_notice_shown.load(std::sync::atomic::Ordering::Relaxed));
// The app is dropped by now: whatever it saved on the way out is in the store.
@@ -991,6 +1054,7 @@ mod launch_arg_tests {
#[cfg(test)]
mod smoke {
use super::*;
use craft::platform::open::DroppedFile;
use craft::ui::testing::Frames;
use serde_json::json;
@@ -1038,6 +1102,7 @@ mod smoke {
native_menu: None,
app,
panels,
document_windows: Default::default(),
drops,
settings,
spool,
@@ -1199,14 +1264,22 @@ mod command_line_tests {
use super::{documents_to_open, split_at_delimiter};
/// The argv the Launcher starts a nightly with, as `prepare_launch` hands it on. The root is the one this
/// platform would pass: `/nightly-data/...` has no drive prefix, so on Windows `parse` rightly refuses it.
/// platform would pass: `/nightly-data/...` has no drive prefix, so on Windows validation rightly refuses it.
fn launcher_argv(tail: &[&str]) -> Vec<String> {
let mut argv: Vec<std::ffi::OsString> = ["--launch-profile", "nightly-v1", "--profile-root", super::launch_profile::launcher_root(), "--"]
.iter()
.map(std::ffi::OsString::from)
.collect();
argv.extend(tail.iter().map(std::ffi::OsString::from));
super::launch_profile::parse(argv).unwrap().args.iter().map(|a| a.to_string_lossy().into_owned()).collect()
let had_separator = super::launch_profile::had_launcher_separator(&argv);
let launch = craft_nightly::parse_startup(
crate::build_flavor::BuildFlavor::NightlyV1,
&crate::profile_root::spec(),
argv,
&craft_nightly::StartupOptions::new(),
)
.unwrap();
super::launch_profile::passthrough_args(launch.passthrough_args, had_separator).iter().map(|a| a.to_string_lossy().into_owned()).collect()
}
#[test]
+2 -2
View File
@@ -10,7 +10,7 @@ use std::path::{Path, PathBuf};
use craft::settings::{LegacyFile, LoadReport, Location, OpenOptions, SettingsStore, SharedSettings, Source};
use craft::window::restore::Store;
use wordcraft_ui_egui::prefs::{Prefs, import_legacy_window, legacy_ui_json};
use wordcraft_ui_egui::prefs::{Prefs, import_legacy_window, legacy_ui_json_slots};
/// The most of an old `ui.json` read for its window entry; the file is a few kilobytes.
const LEGACY_LIMIT: u64 = 8 << 20;
@@ -41,7 +41,7 @@ fn open_in(dir: Option<PathBuf>, placement: &mut Store) -> (SharedSettings<Prefs
None => OpenOptions::new(Location::Memory),
};
if let Some(dir) = &dir {
options = options.legacy(vec![LegacyFile { path: dir.join("ui.json"), parse: legacy_ui_json }]);
options = options.legacy(vec![LegacyFile { paths: vec![dir.join("ui.json")], parse: legacy_ui_json_slots }]);
}
let (store, report) = SettingsStore::<Prefs>::open_with(options);
if let Source::Legacy(path) = &report.source {
+160 -553
View File
@@ -1,4 +1,5 @@
//! App-owned nightly profile fences; no stable fallback, migration or process environment changes.
//! App-owned nightly profile specification for `craft-nightly`; no stable fallback, migration or
//! process environment changes.
//!
//! WordCraft keeps all of its user state in one settings folder (`wordcraft_control_key::settings_dir`):
//! `config.toml`, `window.json`, `logs/`, `recovery/`, `fonts/`, `Templates/`,
@@ -8,603 +9,209 @@
//! (`wordcraft_engine::packs::use_font_store_in`). Every stable location of either is fenced here.
use std::ffi::OsString;
use std::path::PathBuf;
use std::path::{Component, Path, PathBuf};
use craft_nightly::AppProfileSpec;
/// The app id of the nightly Flatpak this build ships in (`packaging/linux/flatpak-bundle.sh`).
pub const NIGHTLY_FLATPAK_ID: &str = "ai.storyteller.wordcraft.nightly";
pub const APP_ID: &str = "wordcraft";
pub const DISPLAY_NAME: &str = "WordCraft";
pub const STABLE_PACKAGE_ID: &str = "ai.storyteller.wordcraft";
pub const NIGHTLY_PACKAGE_ID: &str = "ai.storyteller.wordcraft.nightly";
pub const STABLE_DIR_NAMES: &[&str] = &["wordcraft", "WordCraft", "craft-fonts", "Craft Fonts"];
pub const FORBIDDEN_ENV_VARS: &[&str] = &["WORDCRAFT_PROFILE_DIR"];
pub const FOLDER_ONLY_ENTRIES: &[&str] = &["recovery", "logs", "fonts", "Templates", "FontStore"];
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Platform {
Windows,
Linux,
Mac,
/// Returns WordCraft's `craft-nightly` isolation specification, including OS-specific installation
/// and sandbox roots that must never overlap a nightly profile.
pub fn spec() -> AppProfileSpec {
spec_with(|key| std::env::var_os(key))
}
impl Platform {
fn current() -> Result<Self, String> {
match std::env::consts::OS {
"windows" => Ok(Self::Windows),
"linux" => Ok(Self::Linux),
"macos" => Ok(Self::Mac),
_ => Err("nightly-v1 is not defined for this operating system".into()),
fn spec_with(env: impl Fn(&str) -> Option<OsString>) -> AppProfileSpec {
AppProfileSpec {
app_id: APP_ID,
display_name: DISPLAY_NAME,
stable_dir_names: STABLE_DIR_NAMES,
stable_package_id: STABLE_PACKAGE_ID,
nightly_package_id: NIGHTLY_PACKAGE_ID,
profile_root_env: None,
forbidden_env_vars: FORBIDDEN_ENV_VARS,
portable_markers: &[],
folder_only_entries: FOLDER_ONLY_ENTRIES,
extra_forbidden_roots: extra_forbidden_roots_with(env),
}
}
#[cfg(any(unix, target_os = "windows"))]
fn non_empty_abs(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Option<PathBuf> {
let value = env(key)?;
if value.is_empty() {
return None;
}
let path = PathBuf::from(value);
if path.is_absolute() { Some(path) } else { None }
}
fn extra_forbidden_roots_with(env: impl Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
let mut roots = Vec::new();
#[cfg(target_os = "windows")]
{
// Per-user and per-machine MSI install locations.
if let Some(local) =
non_empty_abs(&env, "LOCALAPPDATA").or_else(|| non_empty_abs(&env, "USERPROFILE").map(|p| p.join("AppData").join("Local")))
{
roots.push(local.join("Programs").join("ArtCraft").join("WordCraft"));
}
}
fn ignores_case(self) -> bool {
self != Self::Linux
}
}
fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
return Err(format!("{label} must be absolute and contain no parent traversal"));
}
Ok(path)
}
fn required_base(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Result<PathBuf, String> {
let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?;
absolute(PathBuf::from(value), key)
}
fn xdg_base(env: &impl Fn(&str) -> Option<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
match env(key).filter(|v| !v.is_empty()) {
Some(value) => absolute(PathBuf::from(value), key),
None => Ok(required_base(env, "HOME")?.join(fallback)),
}
}
/// Resolve existing ancestors before creating anything. A dangling link or inaccessible ancestor
/// is not a missing directory that may be replaced or followed later.
fn canonical_future(path: &Path) -> Result<PathBuf, String> {
let mut parent = path;
let mut missing = Vec::new();
loop {
match std::fs::symlink_metadata(parent) {
Ok(_) => break,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string());
parent = parent.parent().ok_or("the profile root has no existing ancestor")?;
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
if let Some(base) = non_empty_abs(&env, key) {
roots.push(base.join("ArtCraft").join("WordCraft"));
}
Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")),
}
}
let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?;
for part in missing.into_iter().rev() {
resolved.push(part);
}
Ok(resolved)
}
fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool {
let parts = |p: &Path| {
p.components()
.map(|c| {
let value = c.as_os_str().to_string_lossy().into_owned();
if platform.ignores_case() { value.to_lowercase() } else { value }
})
.collect::<Vec<_>>()
};
let (a, b) = (parts(a), parts(b));
a.starts_with(&b) || b.starts_with(&a)
}
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
let parent = exe.parent().ok_or("cannot establish the installation boundary")?;
if platform == Platform::Mac {
// A profile in Resources is still inside the versioned install, not beside MacOS.
if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) {
return Ok(bundle.to_path_buf());
#[cfg(all(unix, not(target_os = "macos")))]
{
// Native packages' locations and the stable Flatpak's per-app data folder.
roots.extend(["/usr/bin/wordcraft", "/usr/local/bin/wordcraft", "/opt/wordcraft"].map(PathBuf::from));
if let Some(home) = non_empty_abs(&env, "HOME") {
roots.push(home.join(".var/app/ai.storyteller.wordcraft"));
}
}
Ok(parent.to_path_buf())
}
fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>, exe: &Path) -> Result<Vec<PathBuf>, String> {
let mut roots = match platform {
Platform::Windows => {
let mut roots = ["APPDATA", "LOCALAPPDATA"]
.into_iter()
.map(|key| required_base(env, key).map(|p| p.join("WordCraft")))
.collect::<Result<Vec<_>, _>>()?;
// The suite's shared font store and the MSI's default per-user and per-machine folders.
roots.push(required_base(env, "LOCALAPPDATA")?.join("Craft Fonts"));
roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("WordCraft"));
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
if let Some(base) = env(key).filter(|v| !v.is_empty()) {
roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("WordCraft"));
}
}
roots
}
Platform::Linux => {
let mut roots =
[("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")]
.into_iter()
.map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("wordcraft")))
.collect::<Result<Vec<_>, _>>()?;
// The shared font store (fonts and Language packs) and the native packages' locations.
roots.push(xdg_base(env, "XDG_DATA_HOME", ".local/share")?.join("craft-fonts"));
roots.extend(["/usr/bin/wordcraft", "/usr/local/bin/wordcraft", "/opt/wordcraft"].map(PathBuf::from));
// The stable Flatpak keeps its data in its own per-app folder.
roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.wordcraft"));
roots
}
Platform::Mac => {
let home = required_base(env, "HOME")?;
#[cfg(target_os = "macos")]
{
roots.push(PathBuf::from("/Applications/WordCraft.app"));
if let Some(home) = non_empty_abs(&env, "HOME") {
let library = home.join("Library");
vec![
library.join("Application Support/WordCraft"),
library.join("Caches/WordCraft"),
library.join("Caches/ai.storyteller.wordcraft"),
library.join("Preferences/WordCraft"),
library.join("Preferences/ai.storyteller.wordcraft.plist"),
library.join("Saved Application State/ai.storyteller.wordcraft.savedState"),
library.join("Application Support/Craft Fonts"),
home.join("Applications/WordCraft.app"),
PathBuf::from("/Applications/WordCraft.app"),
]
}
};
roots.push(installation_boundary(platform, exe)?);
roots.into_iter().map(|p| canonical_future(&p)).collect()
}
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
let child = canonical_future(&chosen.join(name))?;
if child == chosen || !child.starts_with(&chosen) {
return Err(format!("the nightly {label} must stay inside its selected profile"));
}
if std::fs::metadata(&child).is_ok_and(|meta| !meta.is_dir()) {
return Err(format!("the nightly {label} must be a directory"));
}
Ok(child)
}
/// Every existing entry directly in the profile (`config.toml`, `logs`, `recovery`, `fonts`,
/// `Templates`, `window.json` and so on) must resolve inside it, so a link there cannot point
/// Nightly's writes at another app's data.
fn entries_stay_inside(root: &Path) -> Result<(), String> {
let entries = match std::fs::read_dir(root) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")),
};
for entry in entries {
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
let path = entry.path();
let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
// Settings and session state are ordinary files, not directories. Keep the existing
// directory-boundary check for folders (including the known folder-only entries).
let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name));
if metadata.is_file() && !folder_only {
private_regular_file(&path, &metadata)?;
} else {
private_subdirectory(root, entry.file_name(), "profile entry")?;
roots.push(library.join("Preferences/ai.storyteller.wordcraft.plist"));
roots.push(library.join("Saved Application State/ai.storyteller.wordcraft.savedState"));
roots.push(home.join("Applications/WordCraft.app"));
}
}
Ok(())
#[cfg(not(any(unix, target_os = "windows")))]
let _ = env;
roots
}
/// Persisted files must have their own ordinary file identity, not an alias to other data.
fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt as _;
if metadata.nlink() != 1 {
return Err("the nightly profile file must not be shared".into());
}
}
#[cfg(windows)]
{
use winsafe::{HFILE, co};
let (file, _) = HFILE::CreateFile(
path.to_str().ok_or("the nightly profile file path is not textual")?,
co::GENERIC::default(),
Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE),
None,
co::DISPOSITION::OPEN_EXISTING,
co::FILE_ATTRIBUTE::NORMAL,
Some(co::FILE_FLAG::OPEN_REPARSE_POINT),
None,
None,
)
.map_err(|e| e.to_string())?;
let info = file.GetFileInformationByHandle().map_err(|e| e.to_string())?;
if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT | co::FILE_ATTRIBUTE::DIRECTORY) {
return Err("the nightly profile file must not be an alias or directory".into());
}
if info.nNumberOfLinks != 1 {
return Err("the nightly profile file must not be shared".into());
}
}
let _ = (path, metadata);
Ok(())
}
/// The app's exclusive create probe: a file only this process can have made, created and removed.
pub fn probe_writable(dir: &Path) -> std::io::Result<()> {
static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
let probe = dir.join(format!(".nightly-writable-{}-{}", std::process::id(), NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)));
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
drop(file);
std::fs::remove_file(probe)
}
/// The writable hook is injected so filesystem boundary tests exercise the real policy without
/// starting the app or creating the profile of the person running them.
pub fn validate(
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
validate_for(Platform::current()?, root, env, exe, writable)
}
fn validate_for(
platform: Platform,
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
absolute(root.to_path_buf(), "the nightly profile root")?;
// The developer switch that points a run at any folder: Nightly's folder comes from the Launcher.
if env("WORDCRAFT_PROFILE_DIR").is_some_and(|v| !v.is_empty()) {
return Err("nightly-v1 cannot be combined with WORDCRAFT_PROFILE_DIR".into());
}
// These rows are native tar/app-bundle launches, not a Flatpak package. Inheriting a Flatpak
// runtime could point another profile at the stable app's token files; the nightly Flatpak
// itself (`packaging/linux/flatpak-bundle.sh`) is the one sandbox this build ships in.
if platform != Platform::Windows
&& let Some(id) = env("FLATPAK_ID").filter(|v| !v.is_empty())
&& id != NIGHTLY_FLATPAK_ID
{
return Err("nightly-v1 native packages cannot inherit a Flatpak instance; launch through the native Launcher".into());
}
let chosen = canonical_future(root)?;
let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?;
let forbidden = forbidden_roots(platform, &env, &exe)?;
if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) {
return Err("the nightly root must not overlap stable data or an installation".into());
}
// Existing aliases under the profile must not redirect its own subfolders elsewhere.
entries_stay_inside(&chosen)?;
// Recovery can read, adopt and sweep entries; a link there must never leave the profile.
private_subdirectory(&chosen, "recovery", "recovery folder")?;
let mut create = std::fs::DirBuilder::new();
create.recursive(true);
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt as _;
create.mode(0o700);
}
create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?;
let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?;
if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) {
return Err("the nightly profile changed while it was being validated".into());
}
private_subdirectory(&confirmed, "recovery", "recovery folder")?;
entries_stay_inside(&confirmed)?;
writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?;
Ok(confirmed)
}
const PROFILE_FOLDERS: [&str; 5] = ["recovery", "logs", "fonts", "Templates", "FontStore"];
#[cfg(test)]
mod tests {
use super::*;
use super::{
APP_ID, DISPLAY_NAME, FOLDER_ONLY_ENTRIES, FORBIDDEN_ENV_VARS, NIGHTLY_PACKAGE_ID, STABLE_DIR_NAMES, STABLE_PACKAGE_ID,
extra_forbidden_roots_with, spec_with,
};
use craft_nightly::{ProfileError, validate_and_prepare_root};
use std::collections::BTreeMap;
use std::ffi::OsString;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
struct Fixture {
root: PathBuf,
env: BTreeMap<String, OsString>,
exe: PathBuf,
}
struct TempRoot(PathBuf);
impl Fixture {
fn new() -> Self {
impl TempRoot {
fn new(label: &str) -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
let root = loop {
let candidate =
std::env::temp_dir().join(format!("wordcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
let candidate = std::env::temp_dir().join(format!(
"wordcraft-profile-spec-{label}-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
match std::fs::create_dir(&candidate) {
Ok(()) => break std::fs::canonicalize(candidate).unwrap(),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create owned fixture: {error}"),
}
};
let home = root.join("home");
let exe = root.join("install/wordcraft");
std::fs::create_dir_all(&home).unwrap();
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
std::fs::write(&exe, b"fixture executable, never run").unwrap();
let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))]
.into_iter()
.map(|(key, value)| (key.into(), value.into_os_string()))
.collect();
Self { root, env, exe }
}
fn get(&self, key: &str) -> Option<OsString> {
self.env.get(key).cloned()
}
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
validate_for(
platform,
root,
|key| self.get(key),
Some(&self.exe),
|dir| {
let probe = dir.join("exclusive-test-probe");
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
drop(file);
std::fs::remove_file(probe)
},
)
}
fn home(&self) -> PathBuf {
PathBuf::from(self.get("HOME").unwrap())
Self(root)
}
}
impl Drop for Fixture {
impl Drop for TempRoot {
fn drop(&mut self) {
// Only the directory successfully created by this fixture is owned for removal.
std::fs::remove_dir_all(&self.root).unwrap();
let _ = std::fs::remove_dir_all(&self.0);
}
}
#[test]
fn linux_fences_the_settings_folders_font_store_and_packages_but_allows_the_launcher_sibling() {
let mut fixture = Fixture::new();
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
fixture.env.insert(key.into(), fixture.root.join(key).into_os_string());
}
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
let stable = PathBuf::from(fixture.get(key).unwrap()).join("wordcraft");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap();
for candidate in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
}
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
}
let fonts = PathBuf::from(fixture.get("XDG_DATA_HOME").unwrap()).join("craft-fonts");
std::fs::create_dir_all(fonts.join("language-packs")).unwrap();
for candidate in [fonts.clone(), fonts.join("nightly")] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
}
for package in ["/usr/bin/wordcraft", "/usr/local/bin/wordcraft", "/opt/wordcraft"] {
assert!(fixture.check(Platform::Linux, &PathBuf::from(package)).is_err());
}
let data = PathBuf::from(fixture.get("XDG_DATA_HOME").unwrap());
let nightly = data.join("ArtCraftLauncher/nightly/profiles/wordcraft");
assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly);
assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0);
fn spec_preserves_wordcraft_isolation_contract() {
let spec = spec_with(|_| None);
assert_eq!(spec.app_id, APP_ID);
assert_eq!(spec.display_name, DISPLAY_NAME);
assert_eq!(spec.stable_dir_names, STABLE_DIR_NAMES);
assert_eq!(spec.stable_package_id, STABLE_PACKAGE_ID);
assert_eq!(spec.nightly_package_id, NIGHTLY_PACKAGE_ID);
assert_eq!(spec.profile_root_env, None);
assert_eq!(spec.forbidden_env_vars, FORBIDDEN_ENV_VARS);
assert!(spec.portable_markers.is_empty());
assert_eq!(spec.folder_only_entries, FOLDER_ONLY_ENTRIES);
}
#[cfg(all(unix, not(target_os = "macos")))]
#[test]
fn linux_extra_forbidden_roots_cover_native_packages_and_stable_flatpak() {
let env = BTreeMap::from([(String::from("HOME"), OsString::from("/home/tester"))]);
let roots = extra_forbidden_roots_with(|k| env.get(k).cloned());
assert!(roots.contains(&PathBuf::from("/usr/bin/wordcraft")));
assert!(roots.contains(&PathBuf::from("/usr/local/bin/wordcraft")));
assert!(roots.contains(&PathBuf::from("/opt/wordcraft")));
assert!(roots.contains(&PathBuf::from("/home/tester/.var/app/ai.storyteller.wordcraft")));
}
#[cfg(target_os = "macos")]
#[test]
fn macos_extra_forbidden_roots_cover_bundles_plist_and_saved_state() {
let env = BTreeMap::from([(String::from("HOME"), OsString::from("/Users/tester"))]);
let roots = extra_forbidden_roots_with(|k| env.get(k).cloned());
assert!(roots.contains(&PathBuf::from("/Applications/WordCraft.app")));
assert!(roots.contains(&PathBuf::from("/Users/tester/Applications/WordCraft.app")));
assert!(roots.contains(&PathBuf::from("/Users/tester/Library/Preferences/ai.storyteller.wordcraft.plist")));
assert!(roots.contains(&PathBuf::from("/Users/tester/Library/Saved Application State/ai.storyteller.wordcraft.savedState")));
}
#[cfg(target_os = "windows")]
#[test]
fn windows_extra_forbidden_roots_cover_per_user_and_machine_installs() {
let env = BTreeMap::from([
(String::from("LOCALAPPDATA"), OsString::from(r"C:\Users\tester\AppData\Local")),
(String::from("ProgramFiles"), OsString::from(r"C:\Program Files")),
(String::from("ProgramFiles(x86)"), OsString::from(r"C:\Program Files (x86)")),
]);
let roots = extra_forbidden_roots_with(|k| env.get(k).cloned());
assert!(roots.contains(&PathBuf::from(r"C:\Users\tester\AppData\Local\Programs\ArtCraft\WordCraft")));
assert!(roots.contains(&PathBuf::from(r"C:\Program Files\ArtCraft\WordCraft")));
assert!(roots.contains(&PathBuf::from(r"C:\Program Files (x86)\ArtCraft\WordCraft")));
}
#[test]
fn nightly_profile_reopens_after_saving_settings_and_session_state() {
let fixture = Fixture::new();
for platform in [Platform::Mac, Platform::Linux, Platform::Windows] {
let private = fixture.root.join(format!("nightly-reopen-{platform:?}"));
assert_eq!(fixture.check(platform, &private).unwrap(), private);
for name in ["config.toml", "window.json", "nightly-session.lock", "nightly-session.json"] {
std::fs::write(private.join(name), b"saved profile data").unwrap();
}
for name in PROFILE_FOLDERS {
std::fs::create_dir(private.join(name)).unwrap();
}
assert_eq!(fixture.check(platform, &private).unwrap(), private);
assert_eq!(std::fs::read(private.join("config.toml")).unwrap(), b"saved profile data");
for name in PROFILE_FOLDERS {
let path = private.join(name);
std::fs::remove_dir(&path).unwrap();
std::fs::write(&path, b"not a directory").unwrap();
assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory");
std::fs::remove_file(&path).unwrap();
std::fs::create_dir(&path).unwrap();
}
fn nightly_profile_reopens_and_enforces_folder_only_entries_and_extra_fences() {
let temp = TempRoot::new("reopen");
let fenced = temp.0.join("fenced-stable");
let mut spec = spec_with(|_| None);
spec.extra_forbidden_roots.push(fenced.clone());
let overlap = validate_and_prepare_root(&fenced.join("nightly"), &spec).unwrap_err();
assert!(matches!(overlap, ProfileError::ForbiddenRootOverlap { .. }));
assert!(!fenced.exists());
let private = temp.0.join("nightly-private");
assert_eq!(validate_and_prepare_root(&private, &spec).unwrap(), private);
for name in ["config.toml", "window.json", "nightly-session.lock", "nightly-session.json"] {
std::fs::write(private.join(name), b"saved profile data").unwrap();
}
}
#[test]
fn linux_fences_the_stable_flatpak_data_folder() {
let fixture = Fixture::new();
let flatpak = fixture.home().join(".var/app/ai.storyteller.wordcraft");
for candidate in [flatpak.clone(), flatpak.join("data/nightly")] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
for name in FOLDER_ONLY_ENTRIES {
std::fs::create_dir(private.join(name)).unwrap();
}
assert!(!flatpak.exists());
assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.launcher/nightly")).is_ok());
// Inside the Nightly Flatpak, XDG_DATA_HOME is this app's own persistent data folder, so
// the launcher's profile lands there rather than on the discarded sandbox home.
let nightly = fixture.home().join(".var/app/ai.storyteller.wordcraft.nightly/data/wordcraft-nightly");
assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly);
}
#[test]
fn mac_fences_the_app_library_subtrees_the_shared_font_store_and_the_whole_bundle() {
let mut fixture = Fixture::new();
fixture.exe = fixture.root.join("install/WordCraft Nightly.app/Contents/MacOS/WordCraft");
std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap();
std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap();
let library = fixture.home().join("Library");
for suffix in [
"Application Support/WordCraft",
"Caches/WordCraft",
"Caches/ai.storyteller.wordcraft",
"Preferences/WordCraft",
"Saved Application State/ai.storyteller.wordcraft.savedState",
"Application Support/Craft Fonts",
] {
let stable = library.join(suffix);
assert!(fixture.check(Platform::Mac, &stable.join("nightly")).unwrap_err().contains("overlap"));
assert!(!stable.exists());
assert_eq!(validate_and_prepare_root(&private, &spec).unwrap(), private);
for name in ["config.toml", "window.json", "nightly-session.lock", "nightly-session.json"] {
assert_eq!(std::fs::read(private.join(name)).unwrap(), b"saved profile data", "{name} remains intact after reopen");
}
let inside_resources = fixture.exe.parent().unwrap().parent().unwrap().join("Resources/profile");
assert!(fixture.check(Platform::Mac, &inside_resources).unwrap_err().contains("overlap"));
assert!(!inside_resources.exists());
let valid = library.join("Application Support/ArtCraftLauncher/nightly/profiles/wordcraft");
assert_eq!(fixture.check(Platform::Mac, &valid).unwrap(), valid);
}
#[test]
fn windows_roaming_local_font_store_and_install_fences_remain_active() {
let fixture = Fixture::new();
let mut fixture = fixture;
for key in ["APPDATA", "LOCALAPPDATA"] {
let stable = PathBuf::from(fixture.get(key).unwrap()).join("WordCraft");
assert!(fixture.check(Platform::Windows, &stable.join("nightly")).unwrap_err().contains("overlap"));
assert!(!stable.exists());
for name in FOLDER_ONLY_ENTRIES {
let path = private.join(name);
std::fs::remove_dir(&path).unwrap();
std::fs::write(&path, b"not a directory").unwrap();
let err = validate_and_prepare_root(&private, &spec).unwrap_err();
assert!(matches!(err, ProfileError::ExpectedDirectoryEntry(_)), "{name} must stay a directory");
std::fs::remove_file(&path).unwrap();
std::fs::create_dir(&path).unwrap();
}
let fonts = PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join("Craft Fonts");
assert!(fixture.check(Platform::Windows, &fonts.join("nightly")).unwrap_err().contains("overlap"));
assert!(fixture.check(Platform::Windows, &fixture.exe.parent().unwrap().join("profile")).is_err());
let local = PathBuf::from(fixture.get("LOCALAPPDATA").unwrap());
let per_user = local.join("Programs").join("ArtCraft").join("WordCraft");
assert!(fixture.check(Platform::Windows, &per_user.join("nightly")).unwrap_err().contains("overlap"));
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
let base = fixture.root.join(format!("machine {key}"));
fixture.env.insert(key.into(), base.clone().into_os_string());
let machine = base.join("ArtCraft").join("WordCraft");
assert!(fixture.check(Platform::Windows, &machine.join("nightly")).unwrap_err().contains("overlap"));
assert!(!machine.exists());
}
let sibling = local.join("Programs").join("ArtCraft").join("ArtCraftLauncher").join("nightly").join("wordcraft");
assert!(fixture.check(Platform::Windows, &sibling).is_ok(), "the Launcher's own Programs sibling is not WordCraft's install");
}
#[test]
fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() {
let fixture = Fixture::new();
let root = fixture.home().join("nightly/profiles/wordcraft");
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
assert!(overlaps(&root, &root.join("recovery"), platform));
assert!(overlaps(&root.join("recovery"), &root, platform));
assert!(!overlaps(&root, &root.with_file_name("wordcraft-other"), platform));
}
}
#[cfg(unix)]
#[test]
fn recovery_and_entry_aliases_cannot_leave_the_profile_and_stable_bytes_stay_untouched() {
let fixture = Fixture::new();
let stable = fixture.home().join(".config/wordcraft/recovery");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-autosave"), b"stable recovery bytes").unwrap();
for (index, target) in [stable.clone(), fixture.root.join("missing recovery target")].into_iter().enumerate() {
let private = fixture.root.join(format!("nightly-{index}"));
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&target, private.join("recovery")).unwrap();
let probed = std::cell::Cell::new(false);
let result = validate_for(
Platform::Linux,
&private,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
probed.set(true);
Ok(())
},
);
assert!(result.is_err(), "recovery must not escape the private profile or follow a dangling alias");
assert!(!probed.get());
}
for name in ["logs", "fonts", "config.toml"] {
let private = fixture.root.join(format!("nightly-entry-{name}"));
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&stable, private.join(name)).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_err(), "{name} must not lead outside the profile");
}
assert_eq!(std::fs::read(stable.join("stable-autosave")).unwrap(), b"stable recovery bytes");
assert_eq!(std::fs::read_dir(stable).unwrap().count(), 1);
}
#[cfg(unix)]
#[test]
fn a_recovery_alias_inside_the_profile_keeps_it_usable() {
let fixture = Fixture::new();
let private = fixture.root.join("nightly-private");
let recovery = private.join("private-recovery");
std::fs::create_dir_all(&recovery).unwrap();
std::os::unix::fs::symlink(&recovery, private.join("recovery")).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_ok());
assert_eq!(std::fs::canonicalize(private.join("recovery")).unwrap(), recovery);
}
#[test]
fn ambiguous_environment_and_non_native_sandbox_are_refused_before_creation() {
let mut fixture = Fixture::new();
let candidate = fixture.home().join("nightly/profiles/wordcraft");
fixture.env.insert("XDG_CACHE_HOME".into(), "relative/cache".into());
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("absolute"));
fixture.env.remove("XDG_CACHE_HOME");
fixture.env.insert("WORDCRAFT_PROFILE_DIR".into(), fixture.home().join("custom-stable").into_os_string());
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("WORDCRAFT_PROFILE_DIR"));
fixture.env.remove("WORDCRAFT_PROFILE_DIR");
fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.wordcraft".into());
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak"));
fixture.env.remove("FLATPAK_ID");
// The nightly Flatpak is the one sandbox this build ships in, so its own id is accepted.
let flatpak_profile = fixture.home().join("nightly/flatpak-profile");
fixture.env.insert("FLATPAK_ID".into(), NIGHTLY_FLATPAK_ID.into());
assert_eq!(fixture.check(Platform::Linux, &flatpak_profile).unwrap(), flatpak_profile);
fixture.env.remove("FLATPAK_ID");
fixture.env.remove("HOME");
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("HOME"));
assert!(!candidate.exists());
}
#[test]
fn non_directory_and_failed_write_probe_never_fall_back_to_stable() {
let fixture = Fixture::new();
let file = fixture.home().join("not-a-directory");
std::fs::write(&file, b"do not replace me").unwrap();
assert!(fixture.check(Platform::Linux, &file).is_err());
assert_eq!(std::fs::read(file).unwrap(), b"do not replace me");
let candidate = fixture.home().join("nightly");
let calls = std::cell::Cell::new(0);
let result = validate_for(
Platform::Linux,
&candidate,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
calls.set(calls.get() + 1);
Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "injected write refusal"))
},
);
assert!(result.unwrap_err().contains("not writable"));
assert_eq!(calls.get(), 1);
assert!(!fixture.home().join(".config/wordcraft").exists());
}
#[cfg(unix)]
#[test]
fn symlink_and_dangling_aliases_cannot_create_or_modify_stable_data() {
use std::os::unix::fs::symlink;
let fixture = Fixture::new();
let stable = fixture.home().join(".config/wordcraft");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("sentinel"), b"untouched").unwrap();
let alias = fixture.home().join("alias");
symlink(&stable, &alias).unwrap();
assert!(fixture.check(Platform::Linux, &alias.join("nightly")).unwrap_err().contains("overlap"));
let missing = fixture.home().join("missing-target");
let dangling = fixture.home().join("dangling");
symlink(&missing, &dangling).unwrap();
assert!(fixture.check(Platform::Linux, &dangling.join("nightly")).is_err());
assert!(!missing.exists());
assert!(!stable.join("nightly").exists());
assert_eq!(std::fs::read(stable.join("sentinel")).unwrap(), b"untouched");
}
}
+172
View File
@@ -0,0 +1,172 @@
//! Which root WordCraft starts with, and the one fallback to normal windows.
//!
//! The windowless root is the default. `WORDCRAFT_WINDOWLESS_TRIAL=0` (exactly `0`) rolls back to
//! a windowed root; any other value, or none, keeps the default. On Linux and the BSDs the
//! windowless bootstrap supports only native Wayland, so a start whose event loop winit will open
//! on X11 or XWayland starts windowed from the outset and never retries ([`winit_picks_x11`]).
//!
//! Everything else is decided by eframe, from the display it actually connected to: its windowless
//! bootstrap returns [`eframe::Error::UnsupportedConfiguration`] for an X11 display handle (and,
//! on macOS and Windows, for a renderer bootstrap it cannot use) before it calls the app creator
//! and before any root window exists. With `run_and_return` that error comes back out of
//! `run_native`, the thread's event loop stays cached, and a second `run_native` on this thread
//! reuses it. [`run`] then starts once more with normal windows, only when the creator has not
//! started. Every other error, a second `UnsupportedConfiguration`, and any error after the
//! creator started (including a document window whose surface cannot be attached later, which
//! eframe reports per document) is returned unchanged.
//!
//! Source-only caveat: on a native Wayland display eframe's logical root takes the launcher's
//! activation token before the renderer starts, so a fallback window there may open without it.
use std::cell::RefCell;
use std::rc::Rc;
use eframe::RootViewportMode;
/// The variable that rolls the windowless root back to a windowed one, with the value `0`.
pub(crate) const ROLLBACK_VAR: &str = "WORDCRAFT_WINDOWLESS_TRIAL";
/// The root mode of the first start: windowed when rolled back or when winit opens X11.
pub(crate) fn first_mode(rollback: Option<&std::ffi::OsStr>, x11: bool) -> RootViewportMode {
if x11 || rollback.is_some_and(|v| v == "0") { RootViewportMode::Windowed } else { RootViewportMode::Windowless }
}
/// Whether winit's event loop opens on X11 (XWayland included): forced by the app, or unforced
/// with no Wayland display and an X server. Mirrors the pinned winit's choice exactly: empty and
/// non-Unicode values count as unset, and Wayland wins over `DISPLAY` when unforced. Neither set
/// means winit fails to start at all, which no mode changes.
#[cfg(all(unix, not(target_os = "macos")))]
pub(crate) fn winit_picks_x11(forced_x11: bool, env: impl Fn(&str) -> Option<std::ffi::OsString>) -> bool {
let set = |name: &str| env(name).is_some_and(|v| v.to_str().is_some_and(|v| !v.is_empty()));
forced_x11 || (!set("WAYLAND_DISPLAY") && !set("WAYLAND_SOCKET") && set("DISPLAY"))
}
/// The app's one-shot startup inputs, shared by every start but taken by one app creator only.
pub(crate) struct OneShot<T>(Rc<RefCell<Option<T>>>);
impl<T> Clone for OneShot<T> {
fn clone(&self) -> Self {
Self(Rc::clone(&self.0))
}
}
impl<T> OneShot<T> {
/// The inputs, for the app creator that runs; `None` once any creator has taken them.
pub(crate) fn take(&self) -> Option<T> {
self.0.borrow_mut().take()
}
fn untouched(&self) -> bool {
self.0.borrow().is_some()
}
}
/// Starts the app in `first` mode through `launch`, and once more with normal windows when a
/// windowless start was refused as unsupported before its app creator took `inputs`.
pub(crate) fn run<T>(first: RootViewportMode, inputs: T, mut launch: impl FnMut(RootViewportMode, OneShot<T>) -> eframe::Result) -> eframe::Result {
let inputs = OneShot(Rc::new(RefCell::new(Some(inputs))));
match launch(first, inputs.clone()) {
Err(eframe::Error::UnsupportedConfiguration(reason)) if first == RootViewportMode::Windowless && inputs.untouched() => {
log::warn!("windowless start unsupported here ({reason}); opening normal windows instead");
launch(RootViewportMode::Windowed, inputs)
}
other => other,
}
}
#[cfg(test)]
mod tests {
use super::*;
use RootViewportMode::{Windowed, Windowless};
fn unsupported() -> eframe::Result {
Err(eframe::Error::UnsupportedConfiguration("windowless root: X11".into()))
}
/// Runs the real policy with scripted starts; each step sees whether it may create the app and
/// returns that start's result. Returns the modes started, the modes that created the app, and
/// the result.
fn script(first: RootViewportMode, mut steps: Vec<(bool, eframe::Result)>) -> (Vec<RootViewportMode>, Vec<RootViewportMode>, eframe::Result) {
steps.reverse();
let mut started = Vec::new();
let mut created = Vec::new();
let result = run(first, "inputs", |mode, inputs| {
started.push(mode);
let (creates, result) = steps.pop().unwrap_or((false, Ok(())));
if creates && inputs.take().is_some() {
created.push(mode);
}
result
});
(started, created, result)
}
#[test]
fn an_unsupported_windowless_bootstrap_starts_once_more_with_windows() {
let (started, created, result) = script(Windowless, vec![(false, unsupported()), (true, Ok(()))]);
assert_eq!(started, [Windowless, Windowed]);
assert_eq!(created, [Windowed], "the inputs reach the windowed start's creator, once");
assert!(result.is_ok());
}
#[test]
fn the_windowed_start_is_the_last_one() {
let (started, created, result) = script(Windowless, vec![(false, unsupported()), (false, unsupported())]);
assert_eq!(started, [Windowless, Windowed]);
assert!(created.is_empty());
assert!(matches!(result, Err(eframe::Error::UnsupportedConfiguration(_))));
}
#[test]
fn a_windowed_start_is_never_retried() {
let (started, _, result) = script(first_mode(None, true), vec![(false, unsupported())]);
assert_eq!(started, [Windowed], "X11 starts windowed, once");
assert!(matches!(result, Err(eframe::Error::UnsupportedConfiguration(_))));
}
#[test]
fn other_errors_come_back_unchanged() {
let (started, _, result) = script(Windowless, vec![(false, Err(eframe::Error::AppCreation("no runtime".into())))]);
assert_eq!(started, [Windowless]);
assert!(matches!(result, Err(eframe::Error::AppCreation(e)) if e.to_string() == "no runtime"));
}
#[test]
fn nothing_starts_again_once_the_app_creator_ran() {
let (started, created, result) = script(Windowless, vec![(true, unsupported())]);
assert_eq!((started, created), (vec![Windowless], vec![Windowless]));
assert!(matches!(result, Err(eframe::Error::UnsupportedConfiguration(_))));
}
#[test]
fn only_exactly_zero_rolls_back() {
let var = |v: &str| Some(std::ffi::OsString::from(v));
assert_eq!(first_mode(var("0").as_deref(), false), Windowed);
for value in [None, var("1"), var(""), var("off"), var(" 0")] {
assert_eq!(first_mode(value.as_deref(), false), Windowless, "{value:?}");
}
}
/// The pinned winit opens Wayland whenever a Wayland display is named and the app forces
/// nothing, even with `DISPLAY` set; X11 only when forced or with no Wayland display.
#[cfg(all(unix, not(target_os = "macos")))]
#[test]
fn x11_is_what_winit_opens_not_what_the_session_says() {
use std::os::unix::ffi::OsStringExt;
let picks = |forced, vars: &[(&str, &str)]| {
winit_picks_x11(forced, |name| vars.iter().find(|(k, _)| *k == name).map(|(_, v)| std::ffi::OsString::from(v)))
};
let both = [("DISPLAY", ":0"), ("WAYLAND_DISPLAY", "wayland-0")];
assert!(picks(true, &both), "forced XWayland");
assert!(!picks(false, &both), "unforced, Wayland wins");
assert!(!picks(false, &[("DISPLAY", ":0"), ("WAYLAND_SOCKET", "3")]));
assert!(picks(false, &[("DISPLAY", ":0"), ("WAYLAND_DISPLAY", "")]), "an empty Wayland display is unset");
assert!(!picks(false, &[]));
let non_unicode = |name: &str| match name {
"DISPLAY" => Some(":0".into()),
"WAYLAND_DISPLAY" => Some(std::ffi::OsString::from_vec(b"w\xe9".to_vec())),
_ => None,
};
assert!(winit_picks_x11(false, non_unicode), "winit reads a non-Unicode Wayland display as unset");
}
}
@@ -0,0 +1,167 @@
//! Integration test for Linux Wayland client-side window decoration controls (#5814, #5375).
//!
//! Ensures that on Linux, client-side window controls use font-free Adwaita vector paths
//! so the close button is rendered as a clean vector cross rather than a square fallback,
//! and that sctk-adwaita has proper license attribution in NOTICE without bundling font files.
use std::path::Path;
/// Strips an unquoted TOML `#` comment from a single line.
fn strip_toml_comment(line: &str) -> &str {
let mut in_double = false;
let mut in_single = false;
for (idx, ch) in line.char_indices() {
match ch {
'"' if !in_single => in_double = !in_double,
'\'' if !in_double => in_single = !in_single,
'#' if !in_double && !in_single => return &line[..idx],
_ => {}
}
}
line
}
/// Extracts the comment-stripped body of a TOML table section by exact `[header]`.
fn toml_section(content: &str, header: &str) -> String {
let mut in_section = false;
let mut out = String::new();
for raw_line in content.lines() {
let line = strip_toml_comment(raw_line).trim();
if line.starts_with('[') && line.ends_with(']') {
if in_section {
break;
}
in_section = line == header;
continue;
}
if in_section && !line.is_empty() {
out.push_str(line);
out.push('\n');
}
}
assert!(in_section, "expected target section {header} in apps/wordcraft/Cargo.toml");
out
}
/// Parses the `features = [...]` string array from the `winit = { ... }` dependency entry in a TOML section.
fn winit_features(section: &str) -> Vec<&str> {
let winit_start = section.find("winit").expect("target section must declare a winit dependency");
let after_winit = &section[winit_start..];
let table_end = after_winit.find('}').expect("winit inline table must close with '}'");
let winit_table = &after_winit[..=table_end];
let features_start = winit_table.find("features").expect("winit dependency must declare features");
let after_features = &winit_table[features_start..];
let open_bracket = after_features.find('[').expect("winit features must open with '['");
let after_open = &after_features[open_bracket + 1..];
let close_bracket = after_open.find(']').expect("winit features must close with ']'");
let array_body = &after_open[..close_bracket];
array_body.split(',').map(|item| item.trim().trim_matches('"')).filter(|item| !item.is_empty()).collect()
}
/// Verifies that `apps/wordcraft/Cargo.toml` enables `wayland-csd-adwaita-notitle` for Linux.
#[test]
fn linux_manifest_enables_wayland_csd_adwaita_notitle() {
let cargo_toml = Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml");
let content = std::fs::read_to_string(&cargo_toml).expect("read apps/wordcraft/Cargo.toml");
let linux_section = toml_section(&content, "[target.'cfg(target_os = \"linux\")'.dependencies]");
let linux_features = winit_features(&linux_section);
assert!(
linux_features.contains(&"x11") && linux_features.contains(&"wayland-csd-adwaita-notitle"),
"Linux winit dependency must enable x11 and wayland-csd-adwaita-notitle, got: {linux_features:?}"
);
let other_unix_section = toml_section(&content, "[target.'cfg(all(unix, not(any(target_os = \"macos\", target_os = \"linux\"))))'.dependencies]");
let other_unix_features = winit_features(&other_unix_section);
assert!(
other_unix_features.contains(&"x11") && !other_unix_features.contains(&"wayland-csd-adwaita-notitle"),
"Non-Linux Unix winit dependency must enable x11 without wayland-csd-adwaita-notitle, got: {other_unix_features:?}"
);
}
/// Verifies that `NOTICE` documents sctk-adwaita and its MIT licence.
#[test]
fn notice_documents_sctk_adwaita_attribution() {
let workspace_root = Path::new(env!("CARGO_MANIFEST_DIR")).parent().and_then(Path::parent).expect("workspace root");
let notice = std::fs::read_to_string(workspace_root.join("NOTICE")).expect("read NOTICE");
assert!(notice.contains("Linux Wayland window decorations"), "NOTICE must include 'Linux Wayland window decorations'");
assert!(notice.contains("sctk-adwaita"), "NOTICE must document sctk-adwaita");
assert!(notice.contains("Bartłomiej Maryńczak"), "NOTICE must retain sctk-adwaita's author copyright");
}
/// Parses `[[package]]` entries from `Cargo.lock` as `(name, version, dependencies)`.
fn parse_lockfile_packages(lockfile: &str) -> Vec<(&str, &str, Vec<&str>)> {
lockfile
.split("[[package]]")
.skip(1)
.filter_map(|chunk| {
let mut name = None;
let mut version = None;
let mut deps = Vec::new();
let mut in_deps = false;
for raw_line in chunk.lines() {
let line = raw_line.trim();
if in_deps {
if line == "]" {
in_deps = false;
continue;
}
let dep = line.trim_end_matches(',').trim().trim_matches('"');
if !dep.is_empty() {
deps.push(dep);
}
continue;
}
if let Some(rest) = line.strip_prefix("name = ") {
name = Some(rest.trim_matches('"'));
} else if let Some(rest) = line.strip_prefix("version = ") {
version = Some(rest.trim_matches('"'));
} else if line == "dependencies = [" {
in_deps = true;
}
}
Some((name?, version?, deps))
})
.collect()
}
/// Verifies that WordCraft's resolved Linux `winit` -> `sctk-adwaita` dependency path in
/// `Cargo.lock` does not pull in any title-font renderer crates.
#[test]
fn cargo_lock_contains_font_free_sctk_adwaita() {
use std::collections::{HashSet, VecDeque};
let workspace_root = Path::new(env!("CARGO_MANIFEST_DIR")).parent().and_then(Path::parent).expect("workspace root");
let lockfile = std::fs::read_to_string(workspace_root.join("Cargo.lock")).expect("read Cargo.lock");
let packages = parse_lockfile_packages(&lockfile);
let has_dep = |pkg_name: &str, target: &str| {
packages.iter().any(|(name, _, deps)| *name == pkg_name && deps.iter().any(|spec| spec.split_whitespace().next() == Some(target)))
};
assert!(has_dep("winit", "sctk-adwaita"), "winit in Cargo.lock must depend on sctk-adwaita");
let mut queue = VecDeque::new();
let mut visited = HashSet::new();
for (idx, (name, _, _)) in packages.iter().enumerate() {
if *name == "sctk-adwaita" && visited.insert(idx) {
queue.push_back(idx);
}
}
assert!(!queue.is_empty(), "Cargo.lock must include sctk-adwaita");
let forbidden = ["fontdue", "ab_glyph", "cosmic-text", "crossfont"];
while let Some(idx) = queue.pop_front() {
let (name, _, deps) = &packages[idx];
assert!(!forbidden.contains(name), "sctk-adwaita's resolved dependency path must not include title-font renderer {name}");
for spec in deps {
let mut parts = spec.split_whitespace();
let dep_name = parts.next().expect("dependency name");
let dep_ver = parts.next();
for (next_idx, (cand_name, cand_ver, _)) in packages.iter().enumerate() {
if *cand_name == dep_name && dep_ver.is_none_or(|v| v == *cand_ver) && visited.insert(next_idx) {
queue.push_back(next_idx);
}
}
}
}
}
+2
View File
@@ -2,5 +2,7 @@
mod appimage_env;
mod control_arg;
mod help;
#[cfg(target_os = "linux")]
mod linux_decorations;
#[cfg(unix)]
mod non_utf8_args;
+96
View File
@@ -0,0 +1,96 @@
# DOCX corpus (local only)
This directory is where a local, real-world DOCX corpus can live for the opt-in
`cargo xtask docx-corpus` harness. **The corpus is never committed.** `/corpus` is
git-ignored; only this README is tracked. Never commit Word-produced files, documents
you do not have the right to redistribute, or any proprietary template, theme, font
or image. Word-produced documents are useful locally, including ones you made
yourself, but they must stay untracked.
## Populate it
Put `.docx` files anywhere under this directory (subfolders are walked, symlinks are
skipped):
```sh
mkdir -p corpus/docx/mine
cp ~/Documents/report.docx corpus/docx/mine/
```
Useful sources for a local corpus:
- documents you wrote yourself, exported from Word, Google Docs, LibreOffice or Pages;
- public-domain or openly licensed DOCX samples whose licence allows local testing;
- synthetic files generated by WordCraft (`wordcraft-cli run --template sample --save …`);
- deliberately broken files for the failure path (a text file renamed `.docx`, a
truncated ZIP, a package missing `word/document.xml`).
Keep a note of where each file came from. If a corpus must be shared, share the
manifest and the harness report, not the documents.
## Run it
```sh
# The runner builds wordcraft-cli before every run (a no-op when it is current).
cargo xtask docx-corpus --dir corpus/docx
cargo xtask docx-corpus --dir corpus/docx --out target/docx-corpus/report.json
cargo xtask docx-corpus --dir corpus/docx --all-pages
cargo xtask docx-corpus --dir corpus/docx --timeout 120 --cli target/debug/wordcraft-cli
```
Options:
| Option | Meaning |
|---|---|
| `--dir <path>` | corpus directory (required) |
| `--out <path>` | JSON report path (default `target/docx-corpus/report.json`); the Markdown summary is written beside it with an `.md` extension |
| `--all-pages` | render every page instead of only page 1 (capped at 2,000 pages per file) |
| `--timeout <secs>` | per-child-process timeout, default 60, maximum 3,600 |
| `--cli <path>` | use a specific `wordcraft-cli` binary |
| `-h`, `--help` | usage |
A missing or empty corpus directory is not an error: the command explains what is
missing and exits successfully.
## What each file goes through
Every `.docx` is handled in child `wordcraft-cli` processes, each with the timeout
above, so one hostile or hanging file cannot stop the run:
1. **Open + inspect** — `wordcraft-cli info` gives page and word counts; `wordcraft-cli text`
gives the plain text baseline.
2. **Render** — page 1 to PNG (`--all-pages` renders every page). Images go to
`<report-stem>-artifacts/<index>-<file>/page-NNNN.png` beside the report.
3. **Save** — `wordcraft-cli convert` writes a temporary `.docx` copy under the system
temporary directory.
4. **Reopen + compare** — the copy is opened again for page count and plain text. The
temporary copy is then deleted.
The report records file name, bytes, open time, page count, word count, render time,
round-trip time, rendered images, and every failure. Failures are classified as:
| Kind | Meaning |
|---|---|
| `open` | the file could not be opened or inspected (invalid package, encrypted, timeout, oversized, …) |
| `render` | page rendering failed |
| `save` | saving the temporary copy failed |
| `reopen` | the saved copy could not be opened or its text read |
| `text_mismatch` | reopened plain text differs from the original |
| `page_count_delta` | reopened page count differs from the original |
The JSON report is deterministic for the same corpus and arguments apart from the
timing fields: files are sorted by relative path, failure counts are always present,
and there is no timestamp. The Markdown summary is a short human-readable table.
## Limits
- This harness measures open/render/save/reopen and text/page stability. It does **not**
compare with Word's own rendering or page count, and it does not fix document bugs.
A Word-vs-WordCraft visual comparison is a separate task.
- PNG rendering is a smoke test that the page can be produced, not a fidelity score.
- Files are treated as hostile: recursion depth, file count, file size, render pages and
child output are capped, and symlinks are skipped. The caps are deliberately generous
for normal documents; a file above them is reported as a failure rather than skipped
silently.
- The corpus and its reports stay local. `target/` is git-ignored too, so reports do not
enter commits.
+1 -1
View File
@@ -1 +1 @@
e56d26244bbac099bfd42e23fb12f78a4be418a7
217f4130d7d3dbb21a160f23f6b0021918906cc0
+37 -9
View File
@@ -21,26 +21,32 @@ pub fn use_settings_dir(dir: PathBuf) -> Result<(), String> {
/// an environment variable a child or a wrapper might have inherited. `WORDCRAFT_PROFILE_DIR`
/// overrides the entire folder for isolated runs otherwise.
pub fn settings_dir() -> Option<PathBuf> {
if let Some(path) = CHOSEN.get() {
settings_dir_with(CHOSEN.get(), |k| std::env::var_os(k))
}
fn settings_dir_with(chosen: Option<&PathBuf>, mut env: impl FnMut(&str) -> Option<std::ffi::OsString>) -> Option<PathBuf> {
if let Some(path) = chosen {
return Some(path.clone());
}
if let Some(path) = std::env::var_os("WORDCRAFT_PROFILE_DIR").filter(|p| !p.is_empty()) {
if let Some(path) = env("WORDCRAFT_PROFILE_DIR").filter(|p| !p.is_empty()) {
return Some(PathBuf::from(path));
}
platform_settings_dir()
platform_settings_dir_for(env)
}
/// The platform's own folder, when nothing chose one (see [`settings_dir`]).
#[cfg(test)]
fn platform_settings_dir() -> Option<PathBuf> {
platform_settings_dir_for(|k| std::env::var_os(k))
}
fn platform_settings_dir_for(mut env: impl FnMut(&str) -> Option<std::ffi::OsString>) -> Option<PathBuf> {
if cfg!(target_os = "macos") {
std::env::var_os("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/WordCraft"))
env("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/WordCraft"))
} else if cfg!(windows) {
std::env::var_os("APPDATA").map(|a| PathBuf::from(a).join("WordCraft"))
env("APPDATA").map(|a| PathBuf::from(a).join("WordCraft"))
} else {
std::env::var_os("XDG_CONFIG_HOME")
.map(PathBuf::from)
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))
.map(|c| c.join("wordcraft"))
env("XDG_CONFIG_HOME").map(PathBuf::from).or_else(|| env("HOME").map(|h| PathBuf::from(h).join(".config"))).map(|c| c.join("wordcraft"))
}
}
@@ -109,4 +115,26 @@ mod tests {
assert_eq!(key_path(dir, 7981), dir.join("control-key.local-7981"));
}
}
#[test]
fn settings_dir_is_the_apps_folder() {
let default_dir = settings_dir_with(None, |key| match key {
"HOME" | "APPDATA" | "XDG_CONFIG_HOME" => Some("/tmp/base".into()),
_ => None,
})
.expect("settings_dir should return Some when platform env var is set");
let default_name = default_dir.file_name().and_then(|n| n.to_str()).unwrap_or("");
assert!(default_name == "wordcraft" || default_name == "WordCraft", "{}", default_dir.display());
assert_eq!(settings_dir_with(None, |_| None), None);
let override_dir = settings_dir_with(None, |key| (key == "WORDCRAFT_PROFILE_DIR").then(|| "/tmp/profile".into()));
assert_eq!(override_dir.as_deref(), Some(Path::new("/tmp/profile")));
let empty_override = settings_dir_with(None, |key| match key {
"WORDCRAFT_PROFILE_DIR" => Some("".into()),
"HOME" | "APPDATA" | "XDG_CONFIG_HOME" => Some("/tmp/base".into()),
_ => None,
});
assert_eq!(empty_override, Some(default_dir));
}
}
+52 -3
View File
@@ -230,10 +230,26 @@ impl ChartAxis {
pub const MAX_FMT: usize = 128;
/// A number format code: control characters as spaces, ends trimmed, at most [`MAX_FMT`]
/// characters.
/// characters. A trailing space stays when it is part of the code: the character after `_`,
/// `*` or `\`, or text inside quotes.
pub fn clean_fmt(s: &str) -> String {
let s: String = s.chars().take(MAX_FMT * 4).map(|c| if c.is_control() { ' ' } else { c }).collect();
s.trim().chars().take(MAX_FMT).collect::<String>().trim_end().to_string()
let chars: Vec<char> = s.chars().take(MAX_FMT * 4).skip_while(|c| c.is_whitespace() || c.is_control()).take(MAX_FMT).collect();
let mut keep = 0;
let mut quoted = false;
let mut operand = false;
for (i, &c) in chars.iter().enumerate() {
if !c.is_control() && (!c.is_whitespace() || operand || quoted) {
keep = i + 1;
}
if operand {
operand = false;
} else if c == '"' {
quoted = !quoted;
} else if !quoted && matches!(c, '_' | '*' | '\\') {
operand = true;
}
}
chars[..keep].iter().map(|&c| if c.is_control() { ' ' } else { c }).collect()
}
/// A chart WordCraft can edit.
@@ -512,4 +528,37 @@ mod tests {
spec.sanitize();
assert_eq!(spec.series[0].line_w, Some(20.0), "a wild width clamps to 20 pt");
}
#[test]
fn format_keeps_a_trailing_space_that_is_an_operand() {
// `_`, `*` and `\` take the next character, so a final space after one is part of the code.
assert_eq!(clean_fmt("0_ "), "0_ ");
assert_eq!(clean_fmt("#,##0_ "), "#,##0_ ");
assert_eq!(clean_fmt("0* "), "0* ");
assert_eq!(clean_fmt("0\\ "), "0\\ ");
assert_eq!(clean_fmt("0_ \n "), "0_ ");
assert_eq!(clean_fmt("0\"a "), "0\"a ", "a space inside quotes is text");
// Other spaces at the ends, and control characters, still go.
assert_eq!(clean_fmt(" 0.00 \t"), "0.00");
assert_eq!(clean_fmt("0_\n"), "0_");
assert_eq!(clean_fmt("0\"a\" "), "0\"a\"");
assert_eq!(clean_fmt("\\_ "), "\\_", "an escaped `_` takes no operand");
assert_eq!(clean_fmt("0\u{1}0"), "0 0");
assert_eq!(clean_fmt("_\u{1}"), "_");
assert_eq!(clean_fmt(" \n "), "");
let long = format!("{}_ ", "0".repeat(MAX_FMT - 2));
assert_eq!(clean_fmt(&long), long, "a code of exactly MAX_FMT characters keeps its operand");
// Axis and series formats both go through the cleaner.
let mut a = ChartAxis { fmt: Some("0_ ".into()), ..Default::default() };
a.sanitize();
assert_eq!(a.fmt.as_deref(), Some("0_ "));
let mut spec = ChartSpec {
series: vec![ChartSeries { name: "s".into(), values: vec![Some(1.0)], fmt: Some("#,##0_ ".into()), ..Default::default() }],
categories: vec!["a".into()],
..Default::default()
};
spec.sanitize();
assert_eq!(spec.series[0].fmt.as_deref(), Some("#,##0_ "));
}
}
+30 -8
View File
@@ -703,25 +703,44 @@ impl Document {
}
/// A drawing id no shape uses yet (for gluing a connector to a shape that has none).
///
/// Returns one past the largest in-use shape id across the body, all secondary parts, and
/// footnote/endnote separator stories (walking nested groups and tables); if `u32::MAX` is
/// already in use, falls back via [`free_id`] to the smallest unused non-zero id (or `0` only
/// if every non-zero `u32` id is taken).
pub fn next_shape_id(&self) -> u32 {
let mut max = 0u32;
let mut largest: Option<u32> = None;
let mut used: Vec<u32> = Vec::new();
let mut record = |id: u32| {
if id != 0 {
largest = largest.max(Some(id));
used.push(id);
}
};
let mut see = |o: &InlineObject| match o {
InlineObject::Shape { extra, .. } => max = max.max(extra.id),
InlineObject::Shape { extra, .. } => record(extra.id),
InlineObject::Group { children, .. } => {
for c in children {
if let InlineObject::Shape { extra, .. } = &c.obj {
max = max.max(extra.id);
let mut todo: Vec<&InlineObject> = children.iter().map(|c| &c.obj).collect();
while let Some(obj) = todo.pop() {
match obj {
InlineObject::Shape { extra, .. } => record(extra.id),
InlineObject::Group { children, .. } => todo.extend(children.iter().map(|c| &c.obj)),
_ => {}
}
}
}
_ => {}
};
for blocks in std::iter::once(&self.body).chain(self.parts.values().map(|p| &p.blocks)) {
let sep_stories = [&self.footnote_separators, &self.endnote_separators]
.into_iter()
.flat_map(|s| [&s.separator, &s.continuation_separator, &s.continuation_notice])
.flatten();
for blocks in std::iter::once(&self.body).chain(self.parts.values().map(|p| &p.blocks)).chain(sep_stories) {
for b in blocks {
edit::each_para(b, 0, &mut |p| p.objects.iter().for_each(&mut see));
}
}
max.saturating_add(1).max(1)
free_id(largest, used.into_iter(), 1).unwrap_or(0)
}
/// Change every inline object in every story (paragraphs inside tables too), copying only
@@ -798,7 +817,10 @@ impl Document {
stories.extend(self.parts.values_mut().map(|p| &mut p.blocks));
for blocks in stories {
for b in blocks.iter_mut() {
edit::each_para_mut(Arc::make_mut(b), 0, &mut Paragraph::normalize);
edit::each_para_mut(Arc::make_mut(b), 0, &mut |p: &mut Paragraph| {
p.normalize();
p.reconcile_objects();
});
}
}
}
+83 -1
View File
@@ -340,6 +340,72 @@ impl Paragraph {
self.runs = out;
}
/// Make the objects match the U+FFFC markers one to one (files lie): drop surplus objects,
/// and remove markers past the last object. Runs must already cover the text.
///
/// One scan finds the unmatched markers, one pass removes them and the runs and objects are
/// fixed up once, so the cost is linear in the paragraph however many markers are unmatched.
/// There is no cap on the markers: stopping early would leave markers without objects.
pub fn reconcile_objects(&mut self) {
let keep = self.objects.len();
// Byte offsets of the unmatched markers (every marker after the first `keep`), ascending.
let mut seen = 0usize;
let mut drop: Vec<usize> = Vec::new();
for (i, _) in self.text.match_indices(OBJ) {
crate::work::steps(1);
if seen >= keep {
drop.push(i);
}
seen += 1;
}
if self.objects.len() > seen {
self.objects.truncate(seen);
self.touch();
}
if drop.is_empty() {
return;
}
let w = OBJ.len_utf8();
if self.text.len() == drop.len() * w {
// Emptying: the mark keeps the formatting of what was deleted (as `delete` does).
let revisions = (self.mark.ins, self.mark.del, self.mark.fmt_change.clone());
let mut mark = self.props_of_char(0).clone();
(mark.ins, mark.del, mark.fmt_change) = revisions;
self.mark = mark;
}
// Shrink the runs: each removed marker takes `w` bytes off the run that holds it.
let mut d = 0usize;
let mut start = 0usize;
for r in &mut self.runs {
crate::work::steps(1);
let re = start + r.len;
let mut cut = 0usize;
while let Some(&off) = drop.get(d) {
crate::work::steps(1);
if off >= re {
break;
}
if off >= start {
cut += w;
}
d += 1;
}
start = re;
r.len -= cut.min(r.len);
}
let mut out = String::with_capacity(self.text.len() - drop.len() * w);
// The pieces between markers; marker `k` sits before piece `k + 1` and stays if matched.
for (k, piece) in self.text.split(OBJ).enumerate() {
if k > 0 && k <= keep {
out.push(OBJ);
}
out.push_str(piece);
}
self.text = out;
self.normalize();
self.touch();
}
/// Delete `a..b` (bytes). Objects inside are removed.
pub fn delete(&mut self, a: usize, b: usize) -> Result<()> {
let (a, b) = (a.min(b), a.max(b));
@@ -553,7 +619,8 @@ impl Paragraph {
/// The word around `off` (double-click): (start, end) without trailing space.
pub fn word_at(&self, off: usize) -> (usize, usize) {
let off = self.clamp(off);
let is_w = |c: char| crate::bidi::is_word_char(c);
// Word's word unit takes a typographic apostrophe (’) like `'`, at either end too (#6517).
let is_w = |c: char| crate::bidi::is_word_char(c) || c == '’';
let mut a = off;
for (i, c) in self.text.get(..off).unwrap_or("").char_indices().rev() {
if !is_w(c) {
@@ -786,6 +853,21 @@ mod tests {
assert_eq!(p.prev_boundary(0), 0);
}
#[test]
fn word_at_takes_a_typographic_apostrophe_like_a_straight_one() {
// Byte offsets: `’` is three bytes. Word: `don’t ` (#6517).
let p = Paragraph::with_text("don’t stop", CharProps::default());
assert_eq!(p.word_at(1), (0, 8));
assert_eq!(p.word_at(2), (0, 8));
let p = Paragraph::with_text("the dogs’ bone", CharProps::default());
assert_eq!(p.word_at(5), (4, 12));
let p = Paragraph::with_text("’tis here", CharProps::default());
assert_eq!(p.word_at(3), (0, 7));
assert_eq!(p.word_at(4), (0, 7));
let p = Paragraph::with_text("well-known", CharProps::default());
assert_eq!(p.word_at(1), (0, 4));
}
proptest::proptest! {
#[test]
fn edits_keep_runs_consistent(ops in proptest::collection::vec((0u8..4, 0usize..40, 0usize..40, "[a-zé ]{0,5}"), 0..40)) {
+32 -10
View File
@@ -291,25 +291,47 @@ impl InlineObject {
_ => None,
}
}
/// The text box stories this object shows: a text box's, or its group members'.
/// The text box stories this object shows: a text box's, or its group members' (nested groups
/// included, in member order).
pub fn text_boxes(&self) -> Vec<u32> {
match self {
InlineObject::Shape { story: Some(id), .. } => vec![*id],
InlineObject::Group { children, .. } => children.iter().filter_map(|c| c.obj.text_box()).collect(),
InlineObject::Group { children, .. } => {
let mut out = Vec::new();
let mut todo: Vec<&InlineObject> = children.iter().rev().map(|c| &c.obj).collect();
while let Some(obj) = todo.pop() {
match obj {
InlineObject::Shape { story: Some(id), .. } => out.push(*id),
InlineObject::Group { children, .. } => {
todo.extend(children.iter().rev().map(|c| &c.obj));
}
_ => {}
}
}
out
}
_ => Vec::new(),
}
}
/// The text box story slots of this object and its group members, to repoint.
/// The text box story slots of this object and its group members (nested groups included, in
/// member order), to repoint.
pub fn text_box_slots(&mut self) -> Vec<&mut Option<u32>> {
match self {
InlineObject::Shape { story, .. } => vec![story],
InlineObject::Group { children, .. } => children
.iter_mut()
.filter_map(|c| match &mut c.obj {
InlineObject::Shape { story, .. } => Some(story),
_ => None,
})
.collect(),
InlineObject::Group { children, .. } => {
let mut out = Vec::new();
let mut todo: Vec<&mut InlineObject> = children.iter_mut().rev().map(|c| &mut c.obj).collect();
while let Some(obj) = todo.pop() {
match obj {
InlineObject::Shape { story, .. } => out.push(story),
InlineObject::Group { children, .. } => {
todo.extend(children.iter_mut().rev().map(|c| &mut c.obj));
}
_ => {}
}
}
out
}
_ => Vec::new(),
}
}
+5
View File
@@ -506,6 +506,11 @@ pub struct ParaProps {
/// file (not laid out yet); Word sizes a line by it, so dropping it changes Word's pages.
#[serde(skip_serializing_if = "Option::is_none")]
pub text_alignment: Option<TextAlignment>,
/// A list item's paragraph after its first (or a list header's), with no number of its own,
/// at this list level (0..=8): formats with list items (ODT, HTML, Markdown) keep it in the
/// item. Set only directly, never by a style.
#[serde(skip_serializing_if = "Option::is_none")]
pub list_item: Option<u8>,
}
impl ParaProps {
+17 -1
View File
@@ -42,11 +42,27 @@ pub struct Revision {
/// insertion or deletion.
#[serde(skip_serializing_if = "Option::is_none")]
pub move_name: Option<String>,
/// The change's UTC timestamp: from the file (`w16du:dateUtc`, where `date` is the local time
/// Word writes in `w:date`), or the time WordCraft stamped the change with. `None` when the
/// file doesn't give it.
#[serde(skip_serializing_if = "Option::is_none")]
pub date_utc: Option<String>,
}
impl Revision {
pub fn new(kind: RevisionKind, author: impl Into<String>, date: impl Into<String>) -> Revision {
Revision { kind, author: author.into(), date: date.into(), move_name: None }
Revision { kind, author: author.into(), date: date.into(), move_name: None, date_utc: None }
}
/// A change made here: `date` is the local wall-clock time it was made at, as Word writes
/// `w:date`, and `date_utc` the same instant in UTC.
pub fn made_at(kind: RevisionKind, author: impl Into<String>, date: impl Into<String>, utc: impl Into<String>) -> Revision {
Revision { kind, author: author.into(), date: date.into(), move_name: None, date_utc: Some(utc.into()) }
}
/// The instant changes are grouped by: the UTC time when it is known, else `date`.
pub fn instant(&self) -> &str {
self.date_utc.as_deref().unwrap_or(&self.date)
}
}
+409
View File
@@ -440,6 +440,116 @@ fn prune_text_boxes_drops_only_unshown_ones() {
assert_eq!(d.prune_text_boxes(), 0);
}
/// A text-box shape (`story: Some(id)`) or plain shape (`story: None`) for nested-group tests.
fn test_shape(story: Option<u32>) -> InlineObject {
InlineObject::Shape {
kind: para::ShapeKind::TextBox,
w: 50.0,
h: 20.0,
fill: None,
stroke: None,
stroke_width: 0.0,
float: Default::default(),
story,
freeform: None,
effects: Default::default(),
extra: Default::default(),
}
}
/// A group holding `children`.
fn test_group(children: Vec<InlineObject>) -> InlineObject {
InlineObject::Group {
w: 100.0,
h: 100.0,
float: Default::default(),
ch_w: 100.0,
ch_h: 100.0,
children: children.into_iter().map(|obj| para::GroupChild { x: 0.0, y: 0.0, obj }).collect(),
canvas: None,
}
}
/// `obj` wrapped inside `levels` nested [`InlineObject::Group`]s.
fn nested_group(levels: usize, obj: InlineObject) -> InlineObject {
(0..levels).fold(obj, |inner, _| test_group(vec![inner]))
}
#[test]
fn nested_group_text_boxes_are_collected_and_slots_repointed_in_order() {
let mut outer = test_group(vec![
test_shape(Some(1)),
test_shape(None),
nested_group(1, test_shape(Some(2))), // depth 2 from outer
test_group(vec![nested_group(1, test_shape(Some(3))), test_shape(Some(4))]), // depth 3 and depth 2
nested_group(39, test_shape(Some(5))), // depth 40 from outer
]);
assert_eq!(outer.text_boxes(), vec![1, 2, 3, 4, 5]);
let slots = outer.text_box_slots();
assert_eq!(slots.len(), 6);
for id in slots.into_iter().flatten() {
*id += 100;
}
assert_eq!(outer.text_boxes(), vec![101, 102, 103, 104, 105]);
}
#[test]
fn prune_text_boxes_keeps_nested_group_boxes_and_drops_unreachable() {
let para_of = |t: &str| vec![para_block(Paragraph::with_text(t, CharProps::default()))];
let mut d = Document::from_text("body");
let depth2 = d.add_part(PartKind::TextBox, para_of("depth 2"));
let depth3 = d.add_part(PartKind::TextBox, para_of("depth 3"));
let deep = d.add_part(PartKind::TextBox, para_of("depth 40"));
let linked_live = d.add_part(PartKind::TextBox, para_of("linked follower"));
let orphan = d.add_part(PartKind::TextBox, para_of("unreachable"));
let orphan_nested = d.add_part(PartKind::TextBox, para_of("inside unreachable"));
// Live link between two nested-group boxes and a dangling link to an unreachable box.
d.parts.get_mut(&depth2).unwrap().body.next = Some(linked_live);
d.parts.get_mut(&depth3).unwrap().body.next = Some(orphan);
d.insert_object(&Pos::body(0, 0), nested_group(2, test_shape(Some(depth2))), &CharProps::default()).unwrap();
d.insert_object(&Pos::body(0, 0), nested_group(3, test_shape(Some(depth3))), &CharProps::default()).unwrap();
d.insert_object(&Pos::body(0, 0), nested_group(40, test_shape(Some(deep))), &CharProps::default()).unwrap();
d.insert_object(&Pos::body(0, 0), nested_group(2, test_shape(Some(linked_live))), &CharProps::default()).unwrap();
let at_orphan = Pos { story: StoryRef::Part(orphan), path: Path::top(0), off: 0 };
d.insert_object(&at_orphan, nested_group(2, test_shape(Some(orphan_nested))), &CharProps::default()).unwrap();
assert_eq!(d.prune_text_boxes(), 2);
let kept: Vec<u32> = d.parts.keys().copied().collect();
assert_eq!(kept, vec![depth2, depth3, deep, linked_live]);
assert_eq!(d.plain_text(StoryRef::Part(depth2)), "depth 2");
assert_eq!(d.plain_text(StoryRef::Part(depth3)), "depth 3");
assert_eq!(d.plain_text(StoryRef::Part(deep)), "depth 40");
assert_eq!(d.parts.get(&depth2).unwrap().body.next, Some(linked_live), "live chain link stays");
assert_eq!(d.parts.get(&depth3).unwrap().body.next, None, "dangling chain link is cleared");
assert_eq!(d.prune_text_boxes(), 0);
}
#[test]
fn prune_text_boxes_terminates_on_cyclic_nested_group_stories() {
let para_of = |t: &str| vec![para_block(Paragraph::with_text(t, CharProps::default()))];
let mut d = Document::from_text("body");
let a = d.add_part(PartKind::TextBox, para_of("a"));
let b = d.add_part(PartKind::TextBox, para_of("b"));
let dead_c = d.add_part(PartKind::TextBox, para_of("dead c"));
let dead_d = d.add_part(PartKind::TextBox, para_of("dead d"));
let at = |id| Pos { story: StoryRef::Part(id), path: Path::top(0), off: 0 };
// Reachable cycle: body -> nested group -> a -> nested group -> b -> nested group -> (a, b).
d.insert_object(&Pos::body(0, 0), nested_group(2, test_shape(Some(a))), &CharProps::default()).unwrap();
d.insert_object(&at(a), nested_group(2, test_shape(Some(b))), &CharProps::default()).unwrap();
d.insert_object(&at(b), nested_group(2, test_group(vec![test_shape(Some(a)), test_shape(Some(b))])), &CharProps::default()).unwrap();
// Unreachable cycle: dead_c <-> dead_d through nested groups.
d.insert_object(&at(dead_c), nested_group(2, test_shape(Some(dead_d))), &CharProps::default()).unwrap();
d.insert_object(&at(dead_d), nested_group(2, test_shape(Some(dead_c))), &CharProps::default()).unwrap();
assert_eq!(d.prune_text_boxes(), 2);
let kept: Vec<u32> = d.parts.keys().copied().collect();
assert_eq!(kept, vec![a, b]);
assert_eq!(d.counted_stories(), vec![StoryRef::Body, StoryRef::Part(a), StoryRef::Part(b)]);
}
/// `blocks` in the only cell of `levels` tables, each nested in the next.
fn nested_tables(levels: usize, blocks: Blocks) -> Blocks {
(0..levels).fold(blocks, |inner, _| {
@@ -818,3 +928,302 @@ fn missing_pictures_are_capped_deduplicated_and_not_content() {
assert!(!serde_json::to_string(&d).unwrap().contains("p0"));
assert_eq!(MissingPictureReason::ExternalTarget.label(), "external target");
}
#[test]
fn normalize_runs_reconciles_objects_with_markers() {
let c = CharProps::default();
let markers = |p: &Paragraph| p.text.chars().filter(|ch| *ch == '\u{FFFC}').count();
let build = || {
let mut d = Document::from_text("abc");
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
p.insert_object(1, fs("A"), &c).unwrap();
p.insert_object(5, fs("B"), &c).unwrap();
d
};
// More objects than markers (as a hand-edited .json can say): the surplus goes.
let mut d = build();
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().objects.push(fs("C"));
d.normalize_runs();
let p = d.para(StoryRef::Body, &Path::top(0)).unwrap();
assert_eq!((markers(p), p.objects.len()), (2, 2));
assert_eq!(p.objects, vec![fs("A"), fs("B")]);
// More markers than objects: the unmatched marker goes, runs still cover the text.
let mut d = build();
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
p.text.push('\u{FFFC}');
p.runs[0].len += 3;
d.normalize_runs();
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
assert_eq!((markers(p), p.objects.len()), (2, 2));
assert_eq!(p.runs.iter().map(|r| r.len).sum::<usize>(), p.text.len());
// Deleting the first marker keeps B on the second.
p.delete(1, 4).unwrap();
assert_eq!(p.objects, vec![fs("B")]);
// 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| {
let mut p = Paragraph::default();
p.objects = vec![fs("A")];
p.text = format!("\u{FFFC}{}x", "\u{FFFC}".repeat(extra));
p.runs = vec![Run { len: p.text.len(), props: c.clone() }];
crate::work::count(|| {
p.reconcile_objects();
assert_eq!(p.text, "\u{FFFC}x");
std::hint::black_box(&p);
})
};
let (s1, s8) = (reconcile(2_000), reconcile(16_000));
assert!(s1 > 0, "no steps counted, so the walk this test watches no longer counts them (crate::work)");
let ratio = s8 as f64 / s1 as f64;
assert!(ratio <= 12.0, "8x the markers cost {ratio:.1}x the steps ({s1} -> {s8})");
}
#[test]
fn reconcile_objects_drops_many_unmatched_markers_in_one_pass() {
let c = CharProps::default();
let mut d = Document::from_text("");
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
p.insert_object(0, fs("A"), &c).unwrap();
p.insert_object(p.text.len(), fs("B"), &c).unwrap();
let extra = 50_000;
// "<A>x<B>" followed by many unmatched markers around more text, in one run.
p.text = format!("\u{FFFC}x\u{FFFC}{}y{}z", "\u{FFFC}".repeat(extra), "\u{FFFC}".repeat(extra));
p.runs = vec![Run { len: p.text.len(), props: c.clone() }];
p.reconcile_objects();
assert_eq!(p.text, "\u{FFFC}x\u{FFFC}yz");
assert_eq!(p.objects, vec![fs("A"), fs("B")]);
assert_eq!(p.runs.iter().map(|r| r.len).sum::<usize>(), p.text.len());
}
#[test]
fn reconcile_objects_keeps_every_matched_object() {
let c = CharProps::default();
let n = 100_050;
let mut d = Document::from_text("");
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
p.text = "\u{FFFC}".repeat(n);
p.objects = (0..n).map(|_| fs("A")).collect();
p.runs = vec![Run { len: p.text.len(), props: c }];
p.reconcile_objects();
assert_eq!(p.objects.len(), n);
assert_eq!(p.text.matches('\u{FFFC}').count(), n);
assert_eq!(p.runs.iter().map(|r| r.len).sum::<usize>(), p.text.len());
}
#[test]
fn reconcile_objects_keeps_run_props_across_several_runs() {
let (plain, bold) = (CharProps::default(), CharProps { bold: Some(true), ..CharProps::default() });
let italic = CharProps { italic: Some(true), ..CharProps::default() };
let mut d = Document::from_text("");
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
p.objects = vec![fs("A")];
// Runs: plain "a<A>b<X>" | bold "<X><X>" (only unmatched, becomes empty) | italic "<X>c<X>" | plain "d".
let x = "\u{FFFC}";
let parts = [
(format!("a\u{FFFC}b{x}"), plain.clone()),
(format!("{x}{x}"), bold),
(format!("{x}c{x}"), italic.clone()),
("d".to_string(), plain.clone()),
];
p.text = parts.iter().map(|(t, _)| t.as_str()).collect();
p.runs = parts.iter().map(|(t, c)| Run { len: t.len(), props: c.clone() }).collect();
p.reconcile_objects();
assert_eq!(p.text, "a\u{FFFC}bcd");
assert_eq!(p.objects, vec![fs("A")]);
let got: Vec<(usize, CharProps)> = p.runs.iter().map(|r| (r.len, r.props.clone())).collect();
// "a<A>b" plain (5 bytes: 1 + 3 + 1), "c" italic, "d" plain.
assert_eq!(got, vec![(5, plain.clone()), (1, italic), (1, plain)]);
}
#[test]
fn reconcile_objects_marker_on_run_boundary_shrinks_the_right_run() {
let (plain, bold) = (CharProps::default(), CharProps { bold: Some(true), ..CharProps::default() });
let mut d = Document::from_text("");
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
let x = "\u{FFFC}";
// plain "ab" | bold "<X>cd" : the marker is the first byte of the second run.
p.text = format!("ab{x}cd");
p.runs = vec![Run { len: 2, props: plain.clone() }, Run { len: 2 + x.len(), props: bold.clone() }];
p.reconcile_objects();
assert_eq!(p.text, "abcd");
let got: Vec<(usize, CharProps)> = p.runs.iter().map(|r| (r.len, r.props.clone())).collect();
assert_eq!(got, vec![(2, plain), (2, bold)]);
}
#[test]
fn reconcile_objects_all_unmatched_markers_empties_the_paragraph() {
let bold = CharProps { bold: Some(true), ..CharProps::default() };
let mut d = Document::from_text("");
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
p.text = "\u{FFFC}".repeat(3);
p.runs = vec![Run { len: p.text.len(), props: bold.clone() }];
p.mark = CharProps { ins: Some(7), ..CharProps::default() };
p.reconcile_objects();
assert_eq!(p.text, "");
assert!(p.objects.is_empty());
assert!(p.runs.is_empty());
// The mark takes the deleted formatting but keeps its own revision.
assert_eq!(p.mark, CharProps { bold: Some(true), ins: Some(7), ..CharProps::default() });
}
fn shape_with_id(id: u32, story: Option<u32>) -> InlineObject {
InlineObject::Shape {
kind: para::ShapeKind::Rectangle,
w: 50.0,
h: 20.0,
fill: None,
stroke: None,
stroke_width: 0.0,
float: Default::default(),
story,
freeform: None,
effects: Default::default(),
extra: connector::ShapeExtra { id, ..Default::default() },
}
}
fn group_of(children: Vec<InlineObject>) -> InlineObject {
InlineObject::Group {
w: 100.0,
h: 100.0,
float: Default::default(),
ch_w: 100.0,
ch_h: 100.0,
children: children.into_iter().map(|obj| para::GroupChild { x: 0.0, y: 0.0, obj }).collect(),
canvas: None,
}
}
fn nested_group_of(depth: usize, leaf: InlineObject) -> InlineObject {
(0..depth).fold(leaf, |inner, _| group_of(vec![inner]))
}
#[test]
fn next_shape_id_accounts_for_shapes_in_nested_groups() {
// Doubly-nested group carrying shape id 1: must not reissue id 1.
let mut d = Document::from_text("body");
d.insert_object(&Pos::body(0, 0), nested_group_of(2, shape_with_id(1, None)), &CharProps::default()).unwrap();
assert_eq!(d.next_shape_id(), 2);
// Deeper nesting (5-level and 40-level groups) with mixed siblings.
d.insert_object(
&Pos::body(0, 0),
nested_group_of(5, group_of(vec![shape_with_id(42, None), nested_group_of(35, shape_with_id(99, None))])),
&CharProps::default(),
)
.unwrap();
assert_eq!(d.next_shape_id(), 100);
// Nested group inside a secondary story (part).
let hdr = d.add_part(PartKind::Header, vec![para_block(Paragraph::with_text("hdr", CharProps::default()))]);
let at_hdr = Pos { story: StoryRef::Part(hdr), path: Path::top(0), off: 0 };
d.insert_object(&at_hdr, nested_group_of(3, shape_with_id(150, None)), &CharProps::default()).unwrap();
assert_eq!(d.next_shape_id(), 151);
}
#[test]
fn next_shape_id_preserves_flat_group_and_ungrouped_allocation() {
let mut d = Document::from_text("body");
assert_eq!(d.next_shape_id(), 1);
// Ungrouped shapes (including id 0).
d.insert_object(&Pos::body(0, 0), shape_with_id(0, None), &CharProps::default()).unwrap();
assert_eq!(d.next_shape_id(), 1);
d.insert_object(&Pos::body(0, 0), shape_with_id(3, None), &CharProps::default()).unwrap();
d.insert_object(&Pos::body(0, 0), shape_with_id(7, None), &CharProps::default()).unwrap();
assert_eq!(d.next_shape_id(), 8);
// Flat (1-level) group.
d.insert_object(&Pos::body(0, 0), group_of(vec![shape_with_id(12, None), shape_with_id(4, None)]), &CharProps::default()).unwrap();
assert_eq!(d.next_shape_id(), 13);
// At u32::MAX, overflow falls back to an unused non-zero id rather than reissuing u32::MAX.
d.insert_object(&Pos::body(0, 0), nested_group_of(2, shape_with_id(u32::MAX, None)), &CharProps::default()).unwrap();
let id = d.next_shape_id();
assert_ne!(id, 0);
for used in [3, 4, 7, 12, u32::MAX] {
assert_ne!(id, used);
}
assert_eq!(id, 1);
}
#[test]
fn next_shape_id_avoids_reissuing_u32_max_on_overflow() {
// Non-overflow boundary: u32::MAX - 1 still advances to u32::MAX.
let mut d = Document::from_text("body");
d.insert_object(&Pos::body(0, 0), shape_with_id(u32::MAX - 1, None), &CharProps::default()).unwrap();
assert_eq!(d.next_shape_id(), u32::MAX);
// Once u32::MAX is in use inside a nested group, allocator must not reissue any in-use id.
let hdr = d.add_part(PartKind::Header, vec![para_block(Paragraph::with_text("hdr", CharProps::default()))]);
let at_hdr = Pos { story: StoryRef::Part(hdr), path: Path::top(0), off: 0 };
d.insert_object(&Pos::body(0, 0), shape_with_id(1, None), &CharProps::default()).unwrap();
d.insert_object(&at_hdr, nested_group_of(2, shape_with_id(2, None)), &CharProps::default()).unwrap();
d.insert_object(&Pos::body(0, 0), nested_group_of(3, shape_with_id(u32::MAX, None)), &CharProps::default()).unwrap();
let in_use = [1, 2, u32::MAX - 1, u32::MAX];
let first = d.next_shape_id();
assert_ne!(first, 0);
assert!(!in_use.contains(&first), "reissued in-use shape id {first}");
assert_eq!(first, 3);
// Using the returned id advances to the next unused id rather than repeating it.
d.insert_object(&Pos::body(0, 0), nested_group_of(2, shape_with_id(first, None)), &CharProps::default()).unwrap();
let second = d.next_shape_id();
assert_ne!(second, 0);
assert_ne!(second, first);
assert!(!in_use.contains(&second), "reissued in-use shape id {second}");
assert_eq!(second, 4);
}
#[test]
fn next_shape_id_terminates_on_cyclic_nested_group_stories() {
// InlineObject::Group owns Vec<GroupChild> by value (and unsafe is forbidden), so a cyclic
// in-memory Group tree cannot be constructed in safe Rust; mirror #8068 by constructing a
// cyclic text-box story graph through nested groups instead.
let para_of = |t: &str| vec![para_block(Paragraph::with_text(t, CharProps::default()))];
let mut d = Document::from_text("body");
let a = d.add_part(PartKind::TextBox, para_of("a"));
let b = d.add_part(PartKind::TextBox, para_of("b"));
let at = |id| Pos { story: StoryRef::Part(id), path: Path::top(0), off: 0 };
d.insert_object(&Pos::body(0, 0), nested_group_of(2, shape_with_id(5, Some(a))), &CharProps::default()).unwrap();
d.insert_object(&at(a), nested_group_of(2, shape_with_id(10, Some(b))), &CharProps::default()).unwrap();
d.insert_object(&at(b), nested_group_of(2, shape_with_id(25, Some(a))), &CharProps::default()).unwrap();
assert_eq!(d.next_shape_id(), 26);
}
#[test]
fn next_shape_id_accounts_for_shapes_in_note_separators() {
let blocks_with = |obj: InlineObject| -> Blocks {
let mut p = Paragraph::with_text("sep", CharProps::default());
p.insert_object(0, obj, &CharProps::default()).unwrap();
vec![para_block(p)]
};
// A shape ID used only in a footnote separator story must not be reissued.
let mut d = Document::from_text("body");
d.footnote_separators.separator = Some(blocks_with(shape_with_id(1, None)));
assert_eq!(d.next_shape_id(), 2);
// Every footnote and endnote separator slot is walked, including nested groups and tables.
d.footnote_separators.continuation_separator = Some(blocks_with(nested_group_of(2, shape_with_id(2, None))));
d.footnote_separators.continuation_notice = Some(nested_tables(1, blocks_with(shape_with_id(5, None))));
assert_eq!(d.next_shape_id(), 6);
d.endnote_separators.separator = Some(blocks_with(shape_with_id(9, None)));
assert_eq!(d.next_shape_id(), 10);
d.endnote_separators.continuation_separator = Some(blocks_with(nested_group_of(3, shape_with_id(14, None))));
assert_eq!(d.next_shape_id(), 15);
// Overflow fallback also respects IDs held exclusively in note-separator stories.
d.endnote_separators.continuation_notice = Some(blocks_with(nested_group_of(2, shape_with_id(u32::MAX, None))));
let allocated = d.next_shape_id();
assert_ne!(allocated, 0);
for used in [1, 2, 5, 9, 14, u32::MAX] {
assert_ne!(allocated, used);
}
assert_eq!(allocated, 3);
}
+15 -2
View File
@@ -177,6 +177,19 @@ fn glossary_value_from_shared(
})
}
fn note_separators_from_shared(
source: craft_wordmodel::NoteSeparators,
graphics: &mut GraphicCache,
) -> Result<wordcraft_doc::NoteSeparators, DocxError> {
let craft_wordmodel::NoteSeparators { separator, continuation_separator, continuation_notice } = source;
let mut blocks = |b: Option<craft_wordmodel::Blocks>| b.map(|b| blocks_from_shared(b, graphics)).transpose();
Ok(wordcraft_doc::NoteSeparators {
separator: blocks(separator)?,
continuation_separator: blocks(continuation_separator)?,
continuation_notice: blocks(continuation_notice)?,
})
}
fn missing_pictures_from_shared(source: craft_wordmodel::MissingPictures) -> Result<wordcraft_doc::MissingPictures, DocxError> {
let mut target = wordcraft_doc::MissingPictures::default();
target.truncated = source.truncated;
@@ -239,8 +252,8 @@ pub fn from_shared_model(mut source: craft_wordmodel::Document) -> Result<wordcr
document.core = convert(core)?;
document.sources = convert(sources)?;
document.custom_props = convert(custom_props)?;
document.footnote_separators = convert(footnote_separators)?;
document.endnote_separators = convert(endnote_separators)?;
document.footnote_separators = note_separators_from_shared(footnote_separators, &mut graphics)?;
document.endnote_separators = note_separators_from_shared(endnote_separators, &mut graphics)?;
document.media = media;
document.passthrough = passthrough;
document.glossary = glossary.into_iter().map(|g| glossary_value_from_shared(g, &mut graphics)).collect::<Result<_, _>>()?;
+30
View File
@@ -2444,6 +2444,36 @@ fn note_separators_and_continuation_notice_round_trip() {
check(&wordcraft_docx::read(&out).unwrap());
}
/// A picture frame shape in a footnote or endnote separator opens as the same shape kind as it does
/// in the body, instead of failing the whole document. (The test name dates from when the body
/// opened this shape as a rectangle.)
#[test]
fn a_frame_shape_in_a_note_separator_reads_as_a_rectangle() {
let frame = r#"<w:r><w:drawing><wp:inline><wp:extent cx="508000" cy="381000"/><wp:docPr id="1" name="F"/><a:graphic><a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"><wps:wsp><wps:spPr><a:prstGeom prst="frame"/></wps:spPr><wps:bodyPr/></wps:wsp></a:graphicData></a:graphic></wp:inline></w:drawing></w:r>"#;
let notes = |root: &str, item: &str| {
format!(r#"<w:{root} {W_NS}><w:{item} w:type="separator" w:id="-1"><w:p>{frame}<w:r><w:separator/></w:r></w:p></w:{item}></w:{root}>"#)
};
let footnotes = notes("footnotes", "footnote");
let endnotes = notes("endnotes", "endnote");
let bytes = docx(
&format!("<w:p>{frame}</w:p>"),
&[("rId1", "footnotes", "footnotes.xml"), ("rId2", "endnotes", "endnotes.xml")],
&[("word/footnotes.xml", &footnotes), ("word/endnotes.xml", &endnotes)],
);
let d = wordcraft_docx::read(&bytes).unwrap();
let shapes = |p: &Paragraph| -> Vec<(ShapeKind, f32)> {
p.objects.iter().filter_map(|o| if let InlineObject::Shape { kind, w, .. } = o { Some((*kind, *w)) } else { None }).collect()
};
let in_body = shapes(d.body[0].as_para().unwrap());
assert_eq!(in_body.len(), 1, "{in_body:?}");
assert_eq!(in_body[0].1, 40.0);
assert_eq!(in_body[0].0, ShapeKind::Frame);
for separators in [&d.footnote_separators, &d.endnote_separators] {
let sep = separators.separator.as_ref().unwrap()[0].as_para().unwrap();
assert_eq!(shapes(sep), in_body);
}
}
/// Issue #534: East Asian number formats are read, labelled and written back as they were; a
/// value the format doesn't define is decimal, and a level without `w:ind` has no indent.
#[test]
+65 -10
View File
@@ -229,6 +229,7 @@ fn every_para_prop_round_trips() {
fmt_change: None,
snap_to_grid: Some(false),
text_alignment: Some(TextAlignment::Top),
list_item: None, // not a DOCX property
};
let variants = [
ParaProps { line_spacing: Some(LineSpacing::AtLeast(14.0)), indent_first: Some(24.0), align: Some(Align::Center), ..Default::default() },
@@ -315,7 +316,13 @@ fn styles_and_lists_round_trip() {
#[test]
fn tracked_style_definition_change_round_trips() {
let mut d = Document::new();
d.revisions.push(Revision { kind: RevisionKind::Format, author: "Ana".into(), date: "2026-10-17T10:00:00Z".into(), move_name: None });
d.revisions.push(Revision {
kind: RevisionKind::Format,
author: "Ana".into(),
date: "2026-10-17T10:00:00Z".into(),
move_name: None,
date_utc: None,
});
std::sync::Arc::make_mut(&mut d.styles).upsert(Style {
id: "Mine".into(),
name: "Mine".into(),
@@ -1004,8 +1011,20 @@ fn toc_field_skips_nested_stories() {
#[test]
fn tracked_changes_round_trip() {
let mut d = Document::new();
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Alice".into(), date: "2026-05-01T10:00:00Z".into(), move_name: None });
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Bob".into(), date: "2026-05-02T10:00:00Z".into(), move_name: None });
d.revisions.push(Revision {
kind: RevisionKind::Insert,
author: "Alice".into(),
date: "2026-05-01T10:00:00Z".into(),
move_name: None,
date_utc: None,
});
d.revisions.push(Revision {
kind: RevisionKind::Delete,
author: "Bob".into(),
date: "2026-05-02T10:00:00Z".into(),
move_name: None,
date_utc: None,
});
d.settings.track_changes = true;
let ins = CharProps { ins: Some(0), ..Default::default() };
let del = CharProps { del: Some(1), bold: Some(true), ..Default::default() };
@@ -1033,8 +1052,20 @@ fn tracked_changes_round_trip() {
fn tracked_equations_round_trip() {
// Issue #6011: equations saved with tracked revision marks (w:ins / w:del) around math.
let mut d = Document::new();
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Alice".into(), date: "2026-05-01T10:00:00Z".into(), move_name: None });
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Bob".into(), date: "2026-05-02T10:00:00Z".into(), move_name: None });
d.revisions.push(Revision {
kind: RevisionKind::Insert,
author: "Alice".into(),
date: "2026-05-01T10:00:00Z".into(),
move_name: None,
date_utc: None,
});
d.revisions.push(Revision {
kind: RevisionKind::Delete,
author: "Bob".into(),
date: "2026-05-02T10:00:00Z".into(),
move_name: None,
date_utc: None,
});
d.settings.track_changes = true;
let ins = CharProps { ins: Some(0), ..Default::default() };
let del = CharProps { del: Some(1), ..Default::default() };
@@ -1088,8 +1119,20 @@ fn tracked_equations_round_trip() {
fn nested_omath_para_revisions_read() {
// Defensive reader check: w:ins and w:del nested inside m:oMathPara.
let mut d = Document::new();
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: "2026-05-01T10:00:00Z".into(), move_name: None });
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Charles".into(), date: "2026-05-02T10:00:00Z".into(), move_name: None });
d.revisions.push(Revision {
kind: RevisionKind::Insert,
author: "Ada".into(),
date: "2026-05-01T10:00:00Z".into(),
move_name: None,
date_utc: None,
});
d.revisions.push(Revision {
kind: RevisionKind::Delete,
author: "Charles".into(),
date: "2026-05-02T10:00:00Z".into(),
move_name: None,
date_utc: None,
});
let doc_xml = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math"><w:body><w:p><m:oMathPara><w:ins w:id="1" w:author="Ada" w:date="2026-05-01T10:00:00Z"><m:oMath><m:r><m:t>x+1</m:t></m:r></m:oMath></w:ins><w:del w:id="2" w:author="Charles" w:date="2026-05-02T10:00:00Z"><m:oMath><m:r><m:t>y-1</m:t></m:r></m:oMath></w:del></m:oMathPara></w:p></w:body></w:document>"#;
let base = wordcraft_docx::write(&d).unwrap();
let bytes = replace_part(&base, "word/document.xml", doc_xml.as_bytes());
@@ -1107,8 +1150,20 @@ fn tracked_paragraph_marks_round_trip() {
// Issue #229: an inserted / deleted paragraph mark is `w:ins` / `w:del` in the mark's
// `w:rPr` (ECMA-376 §17.13.5.16, §17.13.5.15), alone or with mark formatting.
let mut d = Document::new();
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Alice".into(), date: "2026-05-01T10:00:00Z".into(), move_name: None });
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Bob".into(), date: "2026-05-02T10:00:00Z".into(), move_name: None });
d.revisions.push(Revision {
kind: RevisionKind::Insert,
author: "Alice".into(),
date: "2026-05-01T10:00:00Z".into(),
move_name: None,
date_utc: None,
});
d.revisions.push(Revision {
kind: RevisionKind::Delete,
author: "Bob".into(),
date: "2026-05-02T10:00:00Z".into(),
move_name: None,
date_utc: None,
});
let mut split = Paragraph::with_text("Owned ALPHA ", CharProps::default());
split.mark.ins = Some(0);
let mut joined = Paragraph::with_text("Owned BETA", CharProps::default());
@@ -1862,7 +1917,7 @@ fn kitchen_sink() -> Document {
let f = d.add_part(PartKind::Footnote, vec![para_block(Paragraph::with_text("Note", CharProps::default()))]);
let c = d.add_part(PartKind::Comment, vec![para_block(Paragraph::with_text("Comment", CharProps::default()))]);
d.comments.insert(3, Comment { author: "X".into(), part: c, ..Default::default() });
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "A".into(), date: String::new(), move_name: None });
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "A".into(), date: String::new(), move_name: None, date_utc: None });
d.last_section.headers.default = Some(h);
let mut blocks: Blocks = Vec::new();
let mut p = para_runs(&[
+1 -1
View File
@@ -41,7 +41,7 @@ fn sample() -> Document {
let foot = d.add_part(PartKind::Footnote, vec![para_block(Paragraph::with_text("Sown in May.", CharProps::default()))]);
let com = d.add_part(PartKind::Comment, vec![para_block(Paragraph::with_text("Too short?", CharProps::default()))]);
d.comments.insert(3, Comment { author: "Bo".into(), part: com, ..Default::default() });
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None });
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None, date_utc: None });
d.last_section.headers.default = Some(head);
let mut p = Paragraph::new();
+2
View File
@@ -298,6 +298,8 @@ Review|Language|Translate|review.translate
Review|Language|Language|review.language
Review|Comments|New Comment|review.newComment
Review|Comments|Delete|review.deleteComment
Review|Comments|Delete All Comments in Document|review.deleteComment
Review|Comments|Delete All Resolved Comments|review.deleteComment
Review|Comments|Previous|review.previousComment
Review|Comments|Next|review.nextComment
Review|Comments|Show Comments|review.comments
+27 -2
View File
@@ -210,14 +210,21 @@ pub fn new_revision(s: &mut Session, kind: RevisionKind) -> u32 {
.iter()
.enumerate()
.rev()
.find(|(i, r)| r.kind == kind && r.author == s.author && r.date == date && r.move_name.is_none() && held != Some(*i as u32))
.find(|(i, r)| r.kind == kind && r.author == s.author && r.instant() == date && r.move_name.is_none() && held != Some(*i as u32))
{
return i as u32;
}
s.doc.revisions.push(Revision { kind, author: s.author.clone(), date, move_name: None });
s.doc.revisions.push(made_revision(kind, s.author.clone(), date));
(s.doc.revisions.len() - 1) as u32
}
/// A revision record for a change made at `utc` (ISO 8601, UTC): dated in local wall-clock time,
/// as Word writes `w:date`, with the UTC time beside it, so a save writes it as it is (#6851).
pub fn made_revision(kind: RevisionKind, author: String, utc: String) -> Revision {
let date = crate::io_ext::word_date(&utc, local_offset_secs).unwrap_or_else(|| utc.clone());
Revision::made_at(kind, author, date, utc)
}
/// Whether the paragraph at `path` is followed by another paragraph in the same container (so
/// its paragraph mark can be removed by joining the two).
pub fn has_next_para(s: &Session, story: StoryRef, path: &wordcraft_doc::Path) -> bool {
@@ -556,6 +563,10 @@ pub fn iso_from_unix_secs(secs: u64) -> String {
/// Seconds since the Unix epoch (UTC): the system clock, or the browser's on the web.
pub fn now_unix() -> u64 {
#[cfg(test)]
if let Some(now) = TEST_NOW.with(std::cell::Cell::get) {
return now;
}
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
{
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
@@ -577,9 +588,23 @@ pub fn now_iso() -> String {
/// 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 {
#[cfg(test)]
if let Some(zone) = TEST_ZONE.with(std::cell::Cell::get) {
return zone(unix);
}
system_offset_secs(unix).clamp(-26 * 3600, 26 * 3600)
}
#[cfg(test)]
thread_local! {
/// The clock [`now_unix`] reads on this thread in place of the system's, so a test can make
/// edits at the instants it needs.
pub static TEST_NOW: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) };
/// The zone [`local_offset_secs`] gives on this thread in place of the system's. CI runs on
/// UTC, where local time is UTC, so a test sets a zone that isn't to tell them apart.
pub static TEST_ZONE: std::cell::Cell<Option<fn(u64) -> i64>> = const { std::cell::Cell::new(None) };
}
#[cfg(not(target_arch = "wasm32"))]
fn system_offset_secs(unix: u64) -> i64 {
use chrono::Offset;
+4 -4
View File
@@ -362,10 +362,10 @@ fn copy_member(s: &mut Session, pos: &Pos, index: usize) -> CmdResult {
if !copied {
return Err(CmdError::Failed("the member vanished".into()));
}
s.clipboard_text = f.clipboard_text();
s.clip_history.push(&f, &s.clipboard_text);
s.clipboard = Some(f);
Ok(super::edit::copy_result(s))
let text = f.clipboard_text();
let r = super::edit::copy_result(s, &f, &text)?;
s.clip_history.push(&f, &text);
Ok(r)
}
/// Take member `index` out of the canvas at `pos`; the canvas stays selected.
+30 -2
View File
@@ -1,7 +1,9 @@
//! Caret movement and selection.
use serde_json::Value;
use wordcraft_doc::{Pos, StoryRef};
use wordcraft_doc::math_edit::MathPos;
use wordcraft_doc::para::OBJ;
use wordcraft_doc::{InlineObject, Pos, StoryRef};
use wordcraft_layout::ViewMode;
use super::{parse_pos, sel_result};
@@ -119,9 +121,31 @@ fn lr(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
if bidi_para(s) {
return visual_lr(s, v, is_left);
}
if !extend(v)
&& !s.math_left
&& let Some(r) = into_equation(s, is_left)
{
return r;
}
mv(s, v, if is_left { left } else { right })
}
/// Left/Right onto an equation opens it, at its end from the right and at its start from the
/// left, as in Word (#4138). Leaving it puts the caret on the far side, so the same arrow then
/// moves on instead of going back in. A caret.left/right that itself left an equation (sent
/// while editing one) moves on too.
fn into_equation(s: &mut Session, is_left: bool) -> Option<CmdResult> {
let f = s.sel.focus.clone();
let off = if is_left { f.off.checked_sub(OBJ.len_utf8())? } else { f.off };
if !matches!(s.doc.para_at(&f)?.object_at(off), Some(InlineObject::Equation { .. })) {
return None;
}
s.sel = Selection::caret(Pos { off, ..f });
s.goal_x = None;
s.pending = None;
Some(super::equation::edit_at(s, (!is_left).then(MathPos::default)))
}
/// Left/Right in bidirectional text: one caret position to the left or right on the screen.
/// Past the line's visual end the caret goes to the neighbouring line in reading order (the
/// previous line when moving toward the paragraph's start edge).
@@ -276,7 +300,11 @@ fn page(s: &mut Session, v: &Value, dir: i32) -> CmdResult {
}
let Some(c) = l.caret_on(&from, s.page_hint) else { return sel_result(s) };
let np = if dir < 0 { c.page.saturating_sub(1) } else { (c.page + 1).min(l.pages.len().saturating_sub(1)) };
let to = l.hit(np, c.x, c.top + 1.0, from.story).unwrap_or(from);
let to = if np == c.page {
if dir < 0 { s.doc.start_of(from.story) } else { s.doc.end_of(from.story) }
} else {
l.hit(np, c.x, c.top + 1.0, from.story).unwrap_or(from)
};
s.page_hint = np;
apply(s, to, ext);
sel_result(s)
+1 -1
View File
@@ -35,7 +35,7 @@ pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec::new("references.sources", "Manage Sources", "References › Citations & Bibliography", sources)
.params(r#"{"add"?: Source, "remove"?: tag, "import"?: path (a Word bibliography file, `b:Sources` / `Sources.xml`)} → list"#),
CommandSpec::new("references.citation", "Insert Citation", "References › Citations & Bibliography", citation).params(r#"{"tag"?: string, "source"?: Source (added if new), "pages"?: string}"#),
CommandSpec::new("references.citation", "Insert Citation", "References › Citations & Bibliography", citation).params(r#"{"tag"?: string, "source"?: Source (added, or edited when its tag exists, and cited when no tag is given), "pages"?: string}"#),
CommandSpec::new("references.citationStyle", "Style", "References › Citations & Bibliography", |s, v| {
let st = p::str(v, "style").unwrap_or("APA");
let st = find_style(st).ok_or_else(|| {
+33 -25
View File
@@ -37,22 +37,7 @@ fn auto_tag_base(src: &Source) -> String {
/// document's sources. `import` reads a Word bibliography file (`b:Sources`, #2640).
pub(super) fn sources(s: &mut Session, v: &Value) -> CmdResult {
if let Some(a) = v.get("add") {
let mut src: Source = serde_json::from_value(a.clone()).map_err(|e| CmdError::Params(e.to_string()))?;
// A new source's tag is made from its author and year; an edit keeps the tag it has.
if src.tag.is_empty() {
src.tag = auto_tag(&s.doc, &src);
}
// Edit Source keeps the source's place in the list and refreshes its citations.
match s.doc.sources.iter().position(|x| x.tag == src.tag) {
Some(i) => {
if let Some(x) = s.doc.sources.get_mut(i) {
*x = src;
}
update_citations(s)?;
}
None => s.doc.sources.push(src),
}
s.touch();
add_source(s, a)?;
}
if let Some(t) = p::str(v, "remove") {
s.doc.sources.retain(|x| x.tag != t);
@@ -63,6 +48,28 @@ pub(super) fn sources(s: &mut Session, v: &Value) -> CmdResult {
Ok(serde_json::to_value(&s.doc.sources).unwrap_or(Value::Null))
}
/// Adds a source, or edits the one with its tag, and returns that tag (#7443).
fn add_source(s: &mut Session, a: &Value) -> Result<String, CmdError> {
let mut src: Source = serde_json::from_value(a.clone()).map_err(|e| CmdError::Params(e.to_string()))?;
// A new source's tag is made from its author and year; an edit keeps the tag it has.
if src.tag.is_empty() {
src.tag = auto_tag(&s.doc, &src);
}
let tag = src.tag.clone();
// Edit Source keeps the source's place in the list and refreshes its citations.
match s.doc.sources.iter().position(|x| x.tag == src.tag) {
Some(i) => {
if let Some(x) = s.doc.sources.get_mut(i) {
*x = src;
}
update_citations(s)?;
}
None => s.doc.sources.push(src),
}
s.touch();
Ok(tag)
}
/// The largest bibliography sources file imported from disk.
#[cfg(not(target_arch = "wasm32"))]
const MAX_SOURCES_FILE: u64 = 32 << 20;
@@ -126,15 +133,16 @@ fn import_sources(s: &mut Session, path: &str) -> Result<(), CmdError> {
}
pub(super) fn citation(s: &mut Session, v: &Value) -> CmdResult {
if v.get("source").is_some() {
sources(s, &json!({"add": v.get("source")}))?;
}
let tag = match p::str(v, "tag") {
Some(t) => t.to_string(),
None => match v.get("source") {
Some(_) => s.doc.sources.last().map(|x| x.tag.clone()).unwrap_or_default(),
None => return Err(CmdError::Params("give `tag` or `source`".into())),
},
// The source just added or edited is the one cited when no `tag` is given, wherever it sits
// in the list (#7443).
let added = match v.get("source") {
Some(a) => Some(add_source(s, a)?),
None => None,
};
let tag = match (p::str(v, "tag"), added) {
(Some(t), _) => t.to_string(),
(None, Some(t)) => t,
(None, None) => return Err(CmdError::Params("give `tag` or `source`".into())),
};
let src = s.doc.sources.iter().find(|x| x.tag == tag).cloned().ok_or_else(|| CmdError::Params(format!("no source `{tag}`")))?;
let pages = p::str(v, "pages").unwrap_or("").to_string();
+16
View File
@@ -597,6 +597,22 @@ fn editing_author_and_year_keeps_the_tag_and_updates_the_citation_text() {
assert!(f[0].1.contains("Jones") && f[0].1.contains("2021"), "{:?}", f[0].1);
}
#[test]
fn citing_an_edited_source_that_is_not_last_cites_that_source() {
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("references.sources", &json!({"add": src_of("Alice, Ann", "2000")})).unwrap();
s.run("references.sources", &json!({"add": src_of("Bob, Ben", "2001")})).unwrap();
let mut edited = src_of("Alice Edited, Ann", "2000");
edited["tag"] = json!("Ali00");
let r = s.run("references.citation", &json!({"source": edited})).unwrap();
assert_eq!(r["tag"], "Ali00");
let tags: Vec<_> = s.doc.sources.iter().map(|x| x.tag.as_str()).collect();
assert_eq!(tags, ["Ali00", "Bob01"]);
let f = fields(&s);
assert_eq!(f[0].0, "CITATION Ali00");
assert!(f[0].1.contains("Alice Edited") && f[0].1.contains("2000"), "{:?}", f[0].1);
}
#[test]
fn a_new_sources_tag_is_three_letters_and_two_year_digits() {
let mut s = Session::new(wordcraft_doc::Document::new());
+3 -3
View File
@@ -244,10 +244,10 @@ fn copy(s: &mut Session, segs: &[(Pos, Pos)]) -> CmdResult {
rows.push(row_text(s, &a, &b));
blocks.push(Block::Para(para));
}
s.clipboard_text = rows.join("\n");
let text = rows.join("\n");
let media = s.doc.media_of_blocks(&blocks);
s.clipboard = Some(Fragment { blocks, parts, media });
Ok(super::edit::copy_result(s))
let f = Fragment { blocks, parts, media };
super::edit::copy_result(s, &f, &text)
}
/// Delete each row's piece (bottom up, so earlier positions stay valid) and leave the caret at
+21 -11
View File
@@ -279,6 +279,22 @@ fn content_base(s: &Session, r: &ControlRange) -> CharProps {
content_props(&s.doc, &props)
}
/// The formatting of what replaces a control's content: typed text, a list entry, a date or a
/// check box's mark. In place of the placeholder, that is the control's own run properties
/// (ECMA-376 §17.5.2.27), else the content's formatting without the placeholder style: the
/// showing placeholder's own character style is that style, whatever a producer called it (Word
/// localizes only the id; another program may localize the name too). In place of a value, it is
/// that value's formatting.
fn replacement_props(s: &Session, r: &ControlRange) -> CharProps {
if !r.control.showing_placeholder {
return content_base(s, r);
}
match &r.control.run_props {
Some(rp) => content_props(&s.doc, rp),
None => CharProps { style: None, ..content_base(s, r) },
}
}
// ---------------------------------------------------------------------------------------------
// Rules for typing and deleting
@@ -327,14 +343,8 @@ pub fn prepare_edit(s: &mut Session) -> Result<Option<CharProps>, CmdError> {
if !r.control.showing_placeholder || !r.contains(&b) {
return Ok(None);
}
// Text typed in place of the placeholder takes the control's own run properties (Word, and
// ECMA-376 §17.5.2.27), else the content's formatting without the placeholder style. The
// showing placeholder's own character style is that style, whatever a producer called it
// (Word localizes only the id; another program may localize the name too).
let props = match &r.control.run_props {
Some(rp) => content_props(&s.doc, rp),
None => CharProps { style: None, ..content_base(s, &r) },
};
// Text typed in place of the placeholder takes the control's own run properties, as in Word.
let props = replacement_props(s, &r);
s.sel = Selection { anchor: r.content_start(), focus: r.end.clone() };
if let Some(c) = s.doc.control_mut(&r.start) {
c.showing_placeholder = false;
@@ -666,7 +676,7 @@ fn toggle_check_box(s: &mut Session, v: &Value) -> CmdResult {
}
let now = p::bool(v, "value").unwrap_or(!checked);
let (ch, font) = if now { (*checked_char, checked_font) } else { (*unchecked_char, unchecked_font) };
let mut props = content_base(s, &r);
let mut props = replacement_props(s, &r);
if !font.is_empty() {
props.font = Some(font.clone());
}
@@ -696,7 +706,7 @@ fn choose_item(s: &mut Session, v: &Value) -> CmdResult {
return Err(CmdError::Params("give index, value or text".into()));
};
let Some(item) = item.cloned() else { return Err(CmdError::Params("no such entry".into())) };
let props = content_base(s, &r);
let props = replacement_props(s, &r);
let end = set_content(s, &r, &item.display, &props)?;
if let Some(c) = s.doc.control_mut(&r.start) {
if let ControlKind::ComboBox { last_value, .. } | ControlKind::DropDown { last_value, .. } = &mut c.kind {
@@ -716,7 +726,7 @@ fn set_date(s: &mut Session, v: &Value) -> CmdResult {
}
let (y, m, d) = p::str(v, "date").and_then(parse_date).ok_or_else(|| CmdError::Params("date: YYYY-MM-DD".into()))?;
let text = format_date_value(format, y, m, d);
let props = content_base(s, &r);
let props = replacement_props(s, &r);
let end = set_content(s, &r, &text, &props)?;
if let Some(c) = s.doc.control_mut(&r.start) {
if let ControlKind::Date { full_date, .. } = &mut c.kind {
+43 -5
View File
@@ -3,7 +3,7 @@
use serde_json::{Value, json};
use std::sync::Arc;
use wordcraft_doc::props::{Border, BorderStyle, Borders, CharProps, LineSpacing, Rgb, TextColor};
use wordcraft_doc::{Watermark, styles};
use wordcraft_doc::{StyleKind, Watermark, styles};
use super::sel_result;
use crate::{CmdError, CmdResult, CommandSpec, Session, p};
@@ -209,9 +209,16 @@ fn para_spacing(s: &mut Session, v: &Value) -> CmdResult {
"double" => (0.0, 8.0, 2.0),
_ => (0.0, 8.0, 1.15),
};
Arc::make_mut(&mut s.doc.styles).default_para.space_before = Some(before);
Arc::make_mut(&mut s.doc.styles).default_para.space_after = Some(after);
Arc::make_mut(&mut s.doc.styles).default_para.line_spacing = Some(LineSpacing::Multiple(line));
let st = Arc::make_mut(&mut s.doc.styles);
let apply = |p: &mut wordcraft_doc::props::ParaProps| {
p.space_before = Some(before);
p.space_after = Some(after);
p.line_spacing = Some(LineSpacing::Multiple(line));
};
apply(&mut st.default_para);
for style in st.styles.iter_mut().filter(|style| style.builtin && style.kind == StyleKind::Paragraph) {
apply(&mut style.para);
}
sel_result(s)
}
@@ -287,7 +294,7 @@ fn page_borders(s: &mut Session, v: &Value) -> CmdResult {
};
let blocks: Vec<usize> = match p::str(v, "applyTo") {
Some("document") => s.doc.sections().iter().map(|(end, _)| *end).collect(),
Some("section") | None => vec![s.sel.focus.path.0.first().copied().unwrap_or(0) as usize],
Some("section") | None => vec![super::page::section_end_of_focus(s)],
Some(x) => return Err(CmdError::Params(format!("unknown `applyTo` `{x}`"))),
};
for block in blocks {
@@ -295,3 +302,34 @@ fn page_borders(s: &mut Session, v: &Value) -> CmdResult {
}
sel_result(s)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
use wordcraft_doc::{Document, Style};
#[test]
fn paragraph_spacing_preset_updates_builtin_styles_and_keeps_custom_styles() {
let mut s = Session::new(Document::new());
Arc::make_mut(&mut s.doc.styles).styles.push(Style {
id: "CustomSpacing".into(),
name: "Custom Spacing".into(),
kind: StyleKind::Paragraph,
builtin: false,
para: wordcraft_doc::props::ParaProps { space_after: Some(24.0), ..Default::default() },
..Default::default()
});
s.run("design.paragraphSpacing", &json!({"value": "double"})).unwrap();
let normal = s.doc.styles.get("Normal").unwrap();
assert_eq!(normal.para.line_spacing, Some(LineSpacing::Multiple(2.0)));
let heading = s.doc.styles.get("Heading1").unwrap();
assert_eq!((heading.para.space_before, heading.para.space_after), (Some(0.0), Some(8.0)));
assert_eq!(heading.para.line_spacing, Some(LineSpacing::Multiple(2.0)));
let custom = s.doc.styles.get("CustomSpacing").unwrap();
assert_eq!(custom.para.space_after, Some(24.0));
assert_eq!(custom.para.line_spacing, None);
}
}
+25 -20
View File
@@ -208,29 +208,28 @@ fn copy_with(s: &mut Session, whole: Option<&Path>) -> CmdResult {
None if a == b => return Ok(json!({"text": ""})),
None => s.doc.copy_range(&a, &b),
};
s.clipboard_text = f.clipboard_text();
s.clip_history.push(&f, &s.clipboard_text);
s.clipboard = Some(f);
Ok(copy_result(s))
let text = f.clipboard_text();
let r = copy_result(s, &f, &text)?;
s.clip_history.push(&f, &text);
Ok(r)
}
/// What Copy and Cut return: the clipboard's text, and the copy as HTML (equations as MathML,
/// #816) and as RTF for the host to put on the system clipboard too, so other programs keep the
/// formatting; and for a copy of one equation alone, its MathML (#1297).
pub(crate) fn copy_result(s: &mut Session) -> Value {
(s.clipboard_html, s.clipboard_rtf) = match &s.clipboard {
Some(f) => {
let mut d = f.to_document();
d.styles = s.doc.styles.clone();
if d.media.is_empty() {
d.media = s.doc.media.clone();
}
(wordcraft_formats::html::export_fragment(&d), wordcraft_formats::rtf::export(&d))
}
None => (String::new(), String::new()),
};
let mut r = json!({"text": s.clipboard_text});
for (k, v) in [("html", &s.clipboard_html), ("rtf", &s.clipboard_rtf)] {
///
/// 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 {
let mut d = f.to_document();
d.styles = s.doc.styles.clone();
if d.media.is_empty() {
d.media = s.doc.media.clone();
}
let html = wordcraft_formats::html::export_fragment(&d).map_err(|e| CmdError::Failed(format!("the copy cannot be exported as HTML: {e}")))?;
let rtf = wordcraft_formats::rtf::export(&d).map_err(|e| CmdError::Failed(format!("the copy cannot be exported as RTF: {e}")))?;
let mut r = json!({"text": text});
for (k, v) in [("html", &html), ("rtf", &rtf)] {
if !v.is_empty() {
r[k] = json!(v);
}
@@ -239,10 +238,16 @@ pub(crate) fn copy_result(s: &mut Session) -> Value {
// ("MathML" on Windows, `public.mathml.presentation` on macOS; #1297). Word looks for them
// before anything else when it pastes; a copy with text around the equation doesn't offer
// them, so pasting it keeps the text.
if let Some((linear, display)) = s.clipboard.as_ref().and_then(|f| f.sole_equation()) {
if let Some((linear, display)) = f.sole_equation() {
r["mathml"] = json!(wordcraft_formats::mathml::linear_to_mathml(linear, display));
}
r
// 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_html = html;
s.clipboard_rtf = rtf;
Ok(r)
}
/// Cut the selection, selected object, or whole table cells to the clipboard and remove it from the document.
+6 -2
View File
@@ -261,6 +261,11 @@ fn insert_nodes_as_equation(s: &mut Session, nodes: Arg, v: &Value) -> CmdResult
/// Starts editing the equation at the caret, materializing lazy nodes and clamping the requested
/// position, and returns the equation and caret.
fn edit(s: &mut Session, v: &Value) -> CmdResult {
edit_at(s, v.get("pos").and_then(|p| serde_json::from_value::<MathPos>(p.clone()).ok()))
}
/// [`edit`] at `pos` in the equation, or at its end without one.
pub(super) fn edit_at(s: &mut Session, pos: Option<MathPos>) -> CmdResult {
let at = equation_at_caret(s).ok_or_else(|| CmdError::Disabled("no equation at the caret".into()))?;
let nodes = match s.doc.para_at(&at).and_then(|p| p.object_at(at.off)) {
Some(InlineObject::Equation { math, linear, .. }) => {
@@ -272,8 +277,7 @@ fn edit(s: &mut Session, v: &Value) -> CmdResult {
}
_ => return Err(CmdError::Failed("no equation there".into())),
};
let pos =
v.get("pos").and_then(|p| serde_json::from_value::<MathPos>(p.clone()).ok()).unwrap_or_else(|| MathPos::new(Vec::new(), me::units(&nodes)));
let pos = pos.unwrap_or_else(|| MathPos::new(Vec::new(), me::units(&nodes)));
let Some(session) = crate::next_math_session() else {
return Err(CmdError::Failed("no equation editing session available".into()));
};
+89
View File
@@ -59,6 +59,74 @@ fn structures_symbols_and_navigation() {
assert!(s.math.is_none());
}
#[test]
fn left_and_right_step_into_an_equation_next_to_the_caret() {
let mut s = session();
s.run("document.setText", &json!({"text": "ab\ncd"})).unwrap();
let p0 = s.doc.start_of(s.sel.focus.story);
let p1 = Pos { path: s.doc.next_para(p0.story, &p0.path).unwrap(), ..p0.clone() };
// An equation between "a" and "b", and another one between "c" and "d".
for p in [&p0, &p1] {
s.run("caret.set", &json!({"pos": Pos { off: 1, ..p.clone() }})).unwrap();
s.run("insert.equation", &json!({"linear": "x+y", "edit": false})).unwrap();
}
let after = 1 + OBJ.len_utf8();
let editing = |s: &Session| s.math.as_ref().map(|m| (m.at.path.clone(), m.at.off, m.pos.clone()));
// Right from "a|" enters the equation at its start.
s.run("caret.set", &json!({"pos": Pos { off: 1, ..p0.clone() }})).unwrap();
s.run("caret.right", &json!({})).unwrap();
assert_eq!(editing(&s), Some((p0.path.clone(), 1, MathPos::default())));
// Leaving it to the right, the next Right goes on to the text, not back in.
for _ in 0..10 {
if s.math.is_none() {
break;
}
s.run("equation.move", &json!({"dir": "right"})).unwrap();
}
assert_eq!((s.math.is_none(), s.sel.focus.off), (true, after));
s.run("caret.right", &json!({})).unwrap();
assert_eq!((s.math.is_none(), s.sel.focus.off), (true, after + 1));
// Left from just after the equation in the second paragraph enters it at its end.
s.run("caret.set", &json!({"pos": Pos { off: after, ..p1.clone() }})).unwrap();
s.run("caret.left", &json!({})).unwrap();
let end = MathPos::new(Vec::new(), me::units(&nodes_of(&s, &Pos { off: 1, ..p1.clone() }).unwrap()));
assert_eq!(editing(&s), Some((p1.path.clone(), 1, end)));
for _ in 0..10 {
if s.math.is_none() {
break;
}
s.run("equation.move", &json!({"dir": "left"})).unwrap();
}
assert_eq!((s.math.is_none(), s.sel.focus.off), (true, 1));
s.run("caret.left", &json!({})).unwrap();
assert_eq!((s.math.is_none(), s.sel.focus.off), (true, 0));
// Shift+Right selects over the equation, as before.
s.run("caret.set", &json!({"pos": Pos { off: 1, ..p0.clone() }})).unwrap();
s.run("caret.right", &json!({"extend": true})).unwrap();
assert_eq!((s.math.is_none(), s.sel.anchor.off, s.sel.focus.off), (true, 1, after));
// caret.left/right sent while editing (the arrow keys go to equation.move instead) leave
// the equation and move on, as before, rather than opening the equation they land next to.
s.run("caret.set", &json!({"pos": Pos { off: after, ..p0.clone() }})).unwrap();
s.run("equation.edit", &json!({})).unwrap();
s.run("caret.left", &json!({})).unwrap();
assert_eq!((s.math.is_none(), s.sel.focus.off), (true, 1));
// With two equations side by side, Right from the first goes on past the second.
s.run("caret.set", &json!({"pos": Pos { off: after, ..p1.clone() }})).unwrap();
s.run("insert.equation", &json!({"linear": "z", "edit": false})).unwrap();
s.run("caret.set", &json!({"pos": Pos { off: 1, ..p1.clone() }})).unwrap();
s.run("equation.edit", &json!({})).unwrap();
s.run("caret.right", &json!({})).unwrap();
assert_eq!((s.math.is_none(), s.sel.focus.off), (true, after + OBJ.len_utf8()));
// That holds only for the command that left the equation: the next Right opens one again.
s.run("caret.set", &json!({"pos": Pos { off: 1, ..p0.clone() }})).unwrap();
s.run("caret.right", &json!({})).unwrap();
assert_eq!(editing(&s), Some((p0.path.clone(), 1, MathPos::default())));
}
#[test]
fn numbering_conversion_and_display() {
let mut s = session();
@@ -635,3 +703,24 @@ fn a_math_name_is_corrected_by_any_character_that_cannot_continue_it() {
s.run("equation.type", &json!({"text": r"\alpha+"})).unwrap();
assert_eq!(linear(&s), r"\alpha+");
}
/// Paste Formatting keeps an open equation open (matching other formatting commands and
/// `cmd::column`), whereas content-pasting commands leave the equation first.
#[test]
fn paste_formatting_keeps_an_open_equation_open() {
let mut s = session();
s.run("text.insert", &json!({"text": "source "})).unwrap();
s.run("select.text", &json!({"text": "source"})).unwrap();
s.run("format.bold", &json!({})).unwrap();
s.run("edit.copyFormat", &json!({})).unwrap();
s.run("caret.docEnd", &json!({})).unwrap();
s.run("insert.equation", &json!({"linear": "x"})).unwrap();
let before = s.math.clone();
assert!(before.is_some());
s.run("edit.pasteFormat", &json!({})).unwrap();
assert_eq!(s.math, before, "edit.pasteFormat keeps the open equation open");
s.run("edit.pasteText", &json!({"text": "y"})).unwrap();
assert!(s.math.is_none(), "edit.pasteText closes the open equation");
}
+22 -6
View File
@@ -94,9 +94,9 @@ pub fn specs() -> Vec<CommandSpec> {
.pure(),
CommandSpec::new("file.save", "Save", "File", save)
.key("Mod+S / Shift+F12 / Alt+Shift+F2")
.params(r#"{"path"?: string, "password"?: string (encrypt this and later saves with it, as file.encrypt does), "markup"?: bool (Print Markup for a PDF, PNG, HTML, Markdown or text copy: comments shown; default file.printMarkup), "format"?: "wordml2003" (an .xml file as a Word 2003 XML Document) | "flatopc" (as a Word XML Document, the default; saving over a Word 2003 XML file keeps that format), "strict"?: bool (a .pdf or .png only: refuse, writing nothing, if a character can't be drawn or a picture is missing; see file.strictReport)}"#)
.params(r#"{"path"?: string (required with `copy`), "password"?: string (encrypt this and later saves with it, as file.encrypt does), "markup"?: bool (Print Markup for a PDF, PNG, HTML, Markdown or text copy: comments shown; default file.printMarkup), "format"?: "wordml2003" (an .xml file as a Word 2003 XML Document) | "flatopc" (as a Word XML Document, the default; saving over a Word 2003 XML file keeps that format), "strict"?: bool (a .pdf or .png only: refuse, writing nothing, if a character can't be drawn or a picture is missing; see file.strictReport), "copy"?: bool (write a copy at `path`, as File › Export does: the document keeps its own file, unsaved changes and save stamps; not with `password`)}"#)
.pure(),
CommandSpec::new("file.saveAs", "Save As", "File", save_as).key(super::mac_or("F12 / Mod+Shift+S", "F12 / Alt+F2")).params(r#"{"path": string, "password"?: string, "markup"?: bool, "format"?: string (as file.save), "strict"?: bool (as file.save)}"#).pure(),
CommandSpec::new("file.saveAs", "Save As", "File", save_as).key(super::mac_or("F12 / Mod+Shift+S", "F12 / Alt+F2")).params(r#"{"path": string, "password"?: string, "markup"?: bool, "format"?: string (as file.save), "strict"?: bool (as file.save), "copy"?: bool (as file.save)}"#).pure(),
// Pure: the password must not land in Repeat or a recorded macro, and it isn't an edit
// to undo; it marks the document as changed itself.
CommandSpec::new("file.encrypt", "Encrypt with Password", "File › Info › Protect Document", encrypt)
@@ -342,6 +342,8 @@ pub(crate) fn new_from_template(s: &mut Session, v: &Value) -> CmdResult {
let path = p::req_str(v, "path")?;
let (mut doc, _) = read_document(s, path, v)?;
doc.settings.attached_template = Some(path.to_string());
// A new document: not created when the template was. Saving stamps its creation date.
doc.core.created.clear();
if p::bool(v, "replaceBlank") == Some(true) && s.used_because().is_none() {
s.set_document(doc);
} else {
@@ -393,6 +395,14 @@ fn encrypt(s: &mut Session, v: &Value) -> CmdResult {
/// Executes `file.save`: writes the document or text to disk, preserving exact file text for
/// unedited Markdown files, and updating session path and dirty state.
fn save(s: &mut Session, v: &Value) -> CmdResult {
// A copy (File › Export, #6131) is written and nothing else: the document keeps its own file,
// its unsaved changes and its save stamps, so the next Save still goes to the original.
// It never falls back to the document's own file or opens the Save As picker (whose answer is
// an ordinary save that adopts the file).
let as_copy = p::bool(v, "copy") == Some(true);
if as_copy && p::str(v, "path").is_none() {
return Err(CmdError::Params("`copy` needs a `path`: the copy has to go somewhere".into()));
}
let path = match p::str(v, "path").map(std::path::PathBuf::from).or_else(|| s.path.clone()) {
Some(p) => p,
None => {
@@ -401,6 +411,9 @@ fn save(s: &mut Session, v: &Value) -> CmdResult {
}
};
check_strict_output(p::bool(v, "strict").unwrap_or(false), &path.to_string_lossy())?;
if as_copy && v.get("password").is_some_and(|pw| !pw.is_null()) {
return Err(CmdError::Params("`password` changes the document's own saves, so it can't come with `copy` (use file.encrypt)".into()));
}
if let Some(pw) = v.get("password").filter(|pw| !pw.is_null()) {
let Some(pw) = pw.as_str().filter(|pw| !pw.is_empty()) else {
return Err(CmdError::Params("`password` must be a non-empty string (file.encrypt removes a password)".into()));
@@ -443,11 +456,14 @@ fn save(s: &mut Session, v: &Value) -> CmdResult {
Some(text) => crate::io::save_text_path(&path, text),
None => crate::io::save_path_with(&path, copy.as_ref().unwrap_or(&s.doc), password, &opts),
};
if let Err(e) = written {
(s.doc.settings.zoom, s.doc.core.last_modified_by, s.doc.core.created, s.doc.core.modified, s.doc.core.revision) = before_stamp;
return Err(CmdError::Failed(e));
}
let encrypted = password.is_some() && crate::io::can_encrypt(&path.to_string_lossy());
if written.is_err() || as_copy {
(s.doc.settings.zoom, s.doc.core.last_modified_by, s.doc.core.created, s.doc.core.modified, s.doc.core.revision) = before_stamp;
}
written.map_err(CmdError::Failed)?;
if as_copy {
return Ok(json!({"saved": true, "path": path.to_string_lossy(), "encrypted": encrypted, "copy": true}));
}
// A save in a format that doesn't keep everything (plain text, Markdown, a page image) is a
// copy, except over the document's own file: a note.txt opened and saved is saved (#2376).
// A Markdown file saved as another one loses nothing its own save wouldn't: it moves there.
+2 -2
View File
@@ -53,11 +53,11 @@ impl Recorder<'_> {
if let Some(r) = self.rid {
return r;
}
let found = self.revisions.iter().rposition(|r| r.kind == RevisionKind::Format && r.author == self.author && r.date == self.date);
let found = self.revisions.iter().rposition(|r| r.kind == RevisionKind::Format && r.author == self.author && r.instant() == self.date);
let r = match found {
Some(i) => i as u32,
None => {
self.revisions.push(Revision { kind: RevisionKind::Format, author: self.author.clone(), date: self.date.clone(), move_name: None });
self.revisions.push(crate::cmd::made_revision(RevisionKind::Format, self.author.clone(), self.date.clone()));
self.revisions.len().saturating_sub(1) as u32
}
};
+109 -3
View File
@@ -1,5 +1,7 @@
//! Character formatting (Home › Font).
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};
@@ -8,8 +10,44 @@ use wordcraft_doc::{InlineObject, PartKind, Pos, RevisionKind, StoryRef};
use super::sel_result;
use super::tools::{is_turkic, lower_char, upper_char};
use crate::doc_state::{ColumnBlock, Selection};
use crate::{CmdError, CmdResult, CommandSpec, Session, p};
#[derive(Clone, PartialEq)]
struct StateKey {
document_id: u64,
rev: u64,
sel: Selection,
pending: Option<CharProps>,
pending_at: Option<Pos>,
column: Option<ColumnBlock>,
font_gen: u64,
}
/// Cached result of [`cached_state`] and the session inputs it depends on.
pub(crate) struct StateCache {
key: StateKey,
value: Arc<Value>,
}
impl StateCache {
pub(crate) fn rev(&self) -> u64 {
self.key.rev
}
}
fn state_key(s: &Session) -> StateKey {
StateKey {
document_id: s.document_id(),
rev: s.rev(),
sel: s.sel.clone(),
pending: s.pending.clone(),
pending_at: s.pending_at.clone(),
column: s.column.clone(),
font_gen: wordcraft_fonts::FontDb::global().generation(),
}
}
/// Word's font size list.
pub const SIZES: [f32; 17] = [8.0, 9.0, 10.0, 10.5, 11.0, 12.0, 14.0, 16.0, 18.0, 20.0, 22.0, 24.0, 26.0, 28.0, 36.0, 48.0, 72.0];
@@ -171,7 +209,8 @@ fn target(s: &Session) -> Option<(Pos, Pos)> {
return Some((a, b));
}
let p = s.doc.para_at(&a)?;
let is_w = |c: char| c.is_alphanumeric() || c == '\'' || c == '_';
// Word takes a typographic apostrophe (’) like `'` here (#6517).
let is_w = |c: char| c.is_alphanumeric() || matches!(c, '\'' | '’' | '_');
let before = p.text.get(..a.off)?.chars().next_back();
let after = p.text.get(a.off..)?.chars().next();
if before.is_some_and(is_w) && after.is_some_and(is_w) {
@@ -313,6 +352,16 @@ fn resolved(s: &Session) -> Vec<ResolvedChar> {
out
}
/// Whether a toggle without a `value` turns its format on. A selection follows its first character
/// in document order, as Word does: one that starts formatted loses the format, all of it (#6516).
fn turns_on(s: &Session, has: impl Fn(&ResolvedChar) -> bool) -> bool {
let chars = resolved(s);
if !s.sel.is_collapsed() || selected_text_box(s).is_some() || column_rows(s).is_some() {
return !chars.first().is_some_and(has);
}
!chars.iter().all(has)
}
/// Bold as drawn: a run marked complex script (`w:cs`) or right to left (`w:rtl`) shows its
/// complex-script bold.
fn shown_bold(r: &ResolvedChar) -> bool {
@@ -328,7 +377,7 @@ fn shown_italic(r: &ResolvedChar) -> bool {
fn toggle(s: &mut Session, v: &Value, get: fn(&ResolvedChar) -> bool, set: fn(&mut CharProps, bool)) -> CmdResult {
let on = match p::bool(v, "value") {
Some(b) => b,
None => !resolved(s).iter().all(get),
None => turns_on(s, get),
};
apply(s, &|c| set(c, on))
}
@@ -338,7 +387,7 @@ fn underline(s: &mut Session, v: &Value) -> CmdResult {
let on = match (p::bool(v, "value"), style) {
(Some(b), _) => b,
(None, Some(_)) => true,
(None, None) => !resolved(s).iter().all(|r| r.underline != Underline::None),
(None, None) => turns_on(s, |r| r.underline != Underline::None),
};
let u = if on { style.unwrap_or(Underline::Single) } else { Underline::None };
apply(s, &|c| c.underline = Some(u))
@@ -879,8 +928,30 @@ fn set(s: &mut Session, v: &Value) -> CmdResult {
apply(s, &|c| c.overlay(&props))
}
/// What the ribbon shows: the formatting at the selection (mixed values are null), cached per
/// document revision, selection, pending caret state, column selection, and font generation.
pub fn cached_state(s: &Session) -> Arc<Value> {
let key = state_key(s);
{
let cache = s.format_state.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(cached) = cache.as_ref()
&& cached.key == key
{
return Arc::clone(&cached.value);
}
}
let value = Arc::new(compute_state(s));
let mut cache = s.format_state.lock().unwrap_or_else(PoisonError::into_inner);
*cache = Some(StateCache { key, value: Arc::clone(&value) });
value
}
/// What the ribbon shows: the formatting at the selection (mixed values are null).
pub fn state(s: &Session) -> Value {
(*cached_state(s)).clone()
}
fn compute_state(s: &Session) -> Value {
let all = resolved(s);
let first = all.first().cloned();
let same = |f: &dyn Fn(&ResolvedChar) -> Value| -> Value {
@@ -906,6 +977,7 @@ pub fn state(s: &Session) -> Value {
"italic": all.iter().all(shown_italic),
"underline": all.iter().all(|r| r.underline != Underline::None),
"underlineColor": same(&|r| json!(r.underline_color.map_or_else(|| "auto".to_string(), |c| c.hex()))),
"shading": same(&|r| json!(r.shading.map(|c| c.hex()))),
"strike": all.iter().all(|r| r.strike),
"border": all.iter().all(|r| r.border.is_some()),
"subscript": all.iter().all(|r| r.vert_align == VertAlign::Subscript),
@@ -927,6 +999,14 @@ pub fn state(s: &Session) -> Value {
})
}
/// The selection's uniform highlight colour (`Some(None)` when uniformly unhighlighted), or `None`
/// when the selection is mixed or empty.
pub fn uniform_highlight(s: &Session) -> Option<Option<Rgb>> {
let all = resolved(s);
let first = all.first()?.highlight;
all.iter().all(|r| r.highlight == first).then_some(first)
}
/// What Enclose Characters works on: the selected text (one full-width or up to two half-width
/// characters), or enclosed characters already there (selected, or beside the caret).
#[derive(Clone, Debug, PartialEq)]
@@ -1054,4 +1134,30 @@ mod tests {
assert_eq!(convert("one 3.14 apples and two 2.5 pears.", "sentence", true), "One 3.14 apples and two 2.5 pears.");
assert_eq!(convert("pi is 3.14. next sentence.", "sentence", true), "Pi is 3.14. Next sentence.");
}
#[test]
fn cached_state_hits_until_selection_format_or_pending_changes() {
use serde_json::json;
use std::sync::Arc;
let mut s = crate::Session::new(wordcraft_doc::Document::new());
let a = super::cached_state(&s);
let b = super::cached_state(&s);
assert!(Arc::ptr_eq(&a, &b), "unchanged session should reuse cached format state Arc");
s.run("text.insert", &json!({"text": "hello world"})).unwrap();
let c = super::cached_state(&s);
assert!(!Arc::ptr_eq(&b, &c), "text edit bumps rev and invalidates cache");
s.run("format.bold", &json!({})).unwrap();
let d = super::cached_state(&s);
assert!(!Arc::ptr_eq(&c, &d), "pending bold changes caret formatting");
assert_eq!(d["bold"], json!(true));
assert!(Arc::ptr_eq(&d, &super::cached_state(&s)));
s.run("select.text", &json!({"text": "hello"})).unwrap();
let e = super::cached_state(&s);
assert!(!Arc::ptr_eq(&d, &e), "selection change updates format state");
assert_eq!(e["bold"], json!(false));
}
}
+213
View File
@@ -27,6 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
r#"{"type"?: "indented|runIn", "columns"?: 1-4, "rightAlign"?: bool, "tabLeader"?: "dot|hyphen|underscore|none", "headings"?: bool (letter headings)} (replaces an existing index's settings)"#,
),
CommandSpec::new("references.updateIndex", "Update Index", "References › Index", |s, _| {
check_index_reachable(s)?;
super::citations::update_generated(s)?;
sel_result(s)
}),
@@ -135,8 +136,67 @@ fn index_field(s: &Session) -> Option<(usize, String)> {
})
}
/// 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
/// while Different First Page is off) don't count. Only an index in the main text is rebuilt.
fn has_index(s: &Session, main: bool) -> bool {
s.doc.shown_stories().into_iter().any(|story| {
s.doc
.para_paths(story)
.iter()
.filter(|path| (story == StoryRef::Body && path.depth() == 0) == main)
.filter_map(|path| s.doc.para(story, path))
.any(|p| {
p.objects.iter().any(|o| {
matches!(o, InlineObject::Field { instr, .. } | InlineObject::FieldStart { instr, .. } if FieldCode::parse(instr).name == "INDEX")
})
})
})
}
/// Refuses Insert and Update Index when the document has an index they can't rebuild, even beside
/// one in the main text, rather than adding a second index or reporting an update that left it
/// unchanged.
fn check_index_reachable(s: &Session) -> Result<(), CmdError> {
if has_index(s, false) {
return Err(CmdError::Failed(
"the index is in a table, text box, header or footer, where it can't be updated; move it into the main text, then use Update Index"
.into(),
));
}
// A range-field index after text in its paragraph is not rebuilt either: Update Index only
// takes one that starts its paragraph.
if range_index_after_text(s) {
return Err(CmdError::Failed(
"the index follows text in its paragraph, where it can't be updated; put it at the start of its own paragraph in the main text".into(),
));
}
Ok(())
}
/// Whether a main-text range-field INDEX has text before it in its paragraph.
fn range_index_after_text(s: &Session) -> bool {
s.doc.body.iter().filter_map(|b| b.as_para()).any(|p| {
p.objects_with_offsets().any(|(off, o)| {
matches!(o, InlineObject::FieldStart { instr, .. } if FieldCode::parse(instr).name == "INDEX")
&& !p.text.get(..off).is_some_and(|t| t.chars().all(|c| c.is_whitespace() || c == wordcraft_doc::para::OBJ))
})
})
}
fn insert_index(s: &mut Session, v: &Value) -> CmdResult {
let instr = index_instr(v);
check_index_reachable(s)?;
// 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).
if index_field(s).is_none() && has_index(s, true) {
super::citations::update_generated(s)?;
if index_field(s).is_none() {
return Err(CmdError::Failed("the document already has an index; use Update Index to rebuild it".into()));
}
}
match index_field(s) {
Some((i, _)) => {
// Settings for the index that is there: a new field code, then rebuild it.
@@ -484,4 +544,157 @@ mod tests {
let (i, _) = index_field(&s).unwrap();
assert_eq!(s.doc.body[i + 2].as_para().unwrap().props.tabs.as_ref().unwrap()[0].leader, TabLeader::Hyphen);
}
/// #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.
#[test]
fn an_index_outside_the_main_text_is_refused_not_doubled() {
let indexes = |s: &Session| {
std::iter::once(StoryRef::Body)
.chain(s.doc.parts.keys().map(|k| StoryRef::Part(*k)))
.flat_map(|story| s.doc.para_paths(story).into_iter().filter_map(move |path| s.doc.para(story, &path).cloned()))
.flat_map(|p| p.objects)
.filter(|o| matches!(o, InlineObject::Field { instr, .. } | InlineObject::FieldStart { instr, .. } if FieldCode::parse(instr).name == "INDEX"))
.count()
};
for in_box in [false, true] {
let mut s = Session::new(wordcraft_doc::Document::from_text(
"Kilns are hot.
End.",
));
s.run("select.text", &json!({"text": "Kilns"})).unwrap();
s.run("references.markEntry", &json!({})).unwrap();
s.run("caret.docEnd", &json!({})).unwrap();
let at = if in_box {
s.run("insert.textBox", &json!({"text": "Box"})).unwrap();
let id = s.doc.parts.iter().find(|(_, p)| p.kind == wordcraft_doc::PartKind::TextBox).map(|(id, _)| *id).unwrap();
Pos { story: StoryRef::Part(id), path: Path::top(0), off: 0 }
} else {
s.run("insert.table", &json!({"rows": 1, "cols": 1})).unwrap();
let cell = s.doc.para_paths(StoryRef::Body).into_iter().find(|path| path.depth() > 0).unwrap();
Pos { story: StoryRef::Body, path: cell, off: 0 }
};
// A range field, as a Word file holds its index.
let p = s.doc.para_mut(at.story, &at.path).unwrap();
p.insert_object(0, InlineObject::FieldEnd, &CharProps::default()).unwrap();
p.insert_object(0, InlineObject::FieldStart { instr: r#"INDEX \h "A""#.into(), locked: false, dirty: false }, &CharProps::default())
.unwrap();
s.run("caret.docEnd", &json!({})).unwrap();
let r = s.run("references.index", &json!({"columns": 2}));
assert!(r.is_err(), "Insert Index with the index in a {}: {r:?}", if in_box { "text box" } else { "table" });
assert_eq!(indexes(&s), 1, "INDEX fields after Insert Index");
assert!(s.run("references.updateIndex", &json!({})).is_err(), "Update Index reports the index it can't rebuild");
}
}
/// #3670: an index in a table is refused even when the main text also has one, so the update
/// can't report success and leave the table's index as it was.
#[test]
fn an_index_in_a_table_is_refused_beside_one_in_the_main_text() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Kilns are hot."));
s.run("select.text", &json!({"text": "Kilns"})).unwrap();
s.run("references.markEntry", &json!({})).unwrap();
s.run("caret.docEnd", &json!({})).unwrap();
s.run("references.index", &json!({})).unwrap();
s.run("insert.table", &json!({"rows": 1, "cols": 1})).unwrap();
let cell = s.doc.para_paths(StoryRef::Body).into_iter().find(|path| path.depth() > 0).unwrap();
let p = s.doc.para_mut(StoryRef::Body, &cell).unwrap();
p.insert_object(0, InlineObject::FieldEnd, &CharProps::default()).unwrap();
p.insert_object(0, InlineObject::FieldStart { instr: r#"INDEX \h "A""#.into(), locked: false, dirty: false }, &CharProps::default()).unwrap();
assert!(s.run("references.index", &json!({"columns": 2})).is_err());
assert!(s.run("references.updateIndex", &json!({})).is_err());
}
/// #3670: only the headers a page shows count. An INDEX in a first-page header is out of
/// reach while Different First Page is on, and doesn't block Insert Index while it is off.
#[test]
fn an_index_in_a_header_blocks_insert_only_while_the_header_is_shown() {
let with_header_index = |first: bool, title_page: bool| {
let mut d = wordcraft_doc::Document::from_text("Kilns are hot.");
let mut p = wordcraft_doc::Paragraph::new();
p.insert_object(0, InlineObject::FieldEnd, &CharProps::default()).unwrap();
p.insert_object(0, InlineObject::FieldStart { instr: r#"INDEX \h "A""#.into(), locked: false, dirty: false }, &CharProps::default())
.unwrap();
let id = d.add_part(wordcraft_doc::PartKind::Header, vec![std::sync::Arc::new(wordcraft_doc::Block::Para(p))]);
if first {
d.last_section.headers.first = Some(id);
} else {
d.last_section.headers.default = Some(id);
}
d.last_section.title_page = title_page;
let mut s = Session::new(d);
s.run("select.text", &json!({"text": "Kilns"})).unwrap();
s.run("references.markEntry", &json!({})).unwrap();
s.run("caret.docEnd", &json!({})).unwrap();
s
};
let body_has_index = |s: &Session| index_field(s).is_some();
// Linked (default) header: shown, so Insert Index is refused.
let mut s = with_header_index(false, false);
assert!(s.run("references.index", &json!({})).is_err());
assert!(!body_has_index(&s));
// First-page header with Different First Page off: hidden, so the body gets its index.
let mut s = with_header_index(true, false);
s.run("references.index", &json!({})).unwrap();
assert!(body_has_index(&s));
// The same header with Different First Page on is shown again.
let mut s = with_header_index(true, true);
assert!(s.run("references.index", &json!({})).is_err());
assert!(!body_has_index(&s));
}
/// An index Word wrote as a range field in the main text takes Insert Index's settings and is
/// rebuilt, rather than a second index being added at the caret (#8034).
#[test]
fn insert_index_gives_a_range_field_index_in_the_main_text_its_settings() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Kilns are hot."));
s.run("select.text", &json!({"text": "Kilns"})).unwrap();
s.run("references.markEntry", &json!({})).unwrap();
s.run("caret.docEnd", &json!({})).unwrap();
let at = s.doc.body.len();
let mut para = wordcraft_doc::para::Paragraph::new();
para.insert_object(0, InlineObject::FieldEnd, &CharProps::default()).unwrap();
para.insert_object(0, InlineObject::FieldStart { instr: r#"INDEX \h "A""#.into(), locked: false, dirty: false }, &CharProps::default())
.unwrap();
s.doc.insert_block(StoryRef::Body, &Path::top(at), wordcraft_doc::Block::Para(para)).unwrap();
s.run("caret.docEnd", &json!({})).unwrap();
s.run("references.index", &json!({"columns": 2})).unwrap();
let instrs: Vec<String> = s
.doc
.body
.iter()
.filter_map(|b| b.as_para())
.flat_map(|p| p.objects.iter())
.filter_map(|o| match o {
InlineObject::Field { instr, .. } | InlineObject::FieldStart { instr, .. } if FieldCode::parse(instr).name == "INDEX" => {
Some(instr.clone())
}
_ => None,
})
.collect();
assert_eq!(instrs.len(), 1, "one index, not a second beside it: {instrs:?}");
assert!(FieldCode::parse(&instrs[0]).arg('c').is_some(), "the index took the new columns setting: {instrs:?}");
let text: String =
s.doc.body.iter().filter_map(|b| b.as_para()).map(|p| p.text.replace(wordcraft_doc::para::OBJ, "")).collect::<Vec<_>>().join(
"
",
);
assert!(text.contains("Kilns are hot."), "the text before the index survives: {text:?}");
assert!(text.contains("Kilns, 1"), "Update Index generated an entry: {text:?}");
}
#[test]
fn a_range_field_index_after_text_is_refused_not_reported_updated() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Kilns are hot."));
s.run("select.text", &json!({"text": "Kilns"})).unwrap();
s.run("references.markEntry", &json!({})).unwrap();
let p = s.doc.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
let end = p.len();
p.insert_object(end, InlineObject::FieldEnd, &CharProps::default()).unwrap();
p.insert_object(end, InlineObject::FieldStart { instr: r#"INDEX \h "A""#.into(), locked: false, dirty: false }, &CharProps::default())
.unwrap();
assert!(s.run("references.updateIndex", &json!({})).is_err());
assert!(s.run("references.index", &json!({})).is_err());
}
}
+2 -2
View File
@@ -21,8 +21,8 @@ pub use items::{
};
use items::{cover_page, date_time, drop_cap, drop_cap_off, field, page_number, symbol};
use links::{bookmark, delete_bookmark, link, link_targets};
pub use links::{bookmark_name_ok, bookmark_range, bookmark_span};
pub use objects::{base64_decode, base64_encode};
pub use links::{bookmark_name_ok, bookmark_range, bookmark_span, selection_is_one_line};
pub use objects::{MAX_TABLE_ROWS, base64_decode, base64_encode};
use objects::{icon, shape, table, text_box};
pub(crate) use objects::{image_ext, picture};
+7 -10
View File
@@ -7,7 +7,7 @@ use super::{
/// 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).
pub(super) fn hf_part(s: &mut Session, header: bool) -> u32 {
let block = s.sel.focus.path.0.first().copied().unwrap_or(0) as usize;
let block = crate::cmd::page::section_end_of_focus(s);
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();
@@ -98,15 +98,12 @@ pub(super) fn edit_hf(s: &mut Session, v: &Value, header: bool) -> CmdResult {
let shown = match page {
Some(page) => shown_hf(s, page, header)?,
None => {
let block = s.sel.focus.path.0.first().copied().unwrap_or(0) as usize;
let set = s
.doc
.sections()
.into_iter()
.find(|(end, _)| block <= *end)
.or_else(|| s.doc.sections().pop())
.map(|(_, sp)| if header { sp.headers.default } else { sp.footers.default });
set.flatten().filter(|id| s.doc.parts.contains_key(id))
// The caret's section's own, else the one it is linked to from a section before it, as
// layout shows it (#3639): editing that one keeps the link.
let section = crate::cmd::page::hf_section_of_focus(s);
let sections = s.doc.sections();
let set = sections.iter().take(section + 1).rev().find_map(|(_, sp)| if header { sp.headers.default } else { sp.footers.default });
set.filter(|id| s.doc.parts.contains_key(id))
}
};
let Some(id) = shown else {
+89 -12
View File
@@ -205,21 +205,26 @@ pub fn format_date_at_in(fmt: &str, lang: Option<&str>, unix: u64, offset_secs:
format_date_parts_in(fmt, lang, y, m as usize, d, hms, days)
}
/// Month and weekday names of a language, as Word writes them in date fields: full names, the
/// three-letter forms (`MMM`, `ddd`) being their first three letters, without a full stop.
/// Weekdays start on Thursday (1970-01-01).
/// Month and weekday names of a language, as Word writes them in date fields: full names and the
/// abbreviations used by `MMM` and `ddd`. Weekdays start on Thursday (1970-01-01).
struct DateNames {
/// Full month names (January through December).
months: [&'static str; 12],
/// Abbreviated month names for `MMM` (January through December).
months_short: [&'static str; 12],
/// Weekday names starting on Thursday (1970-01-01).
days: [&'static str; 7],
/// Abbreviated weekday names for `ddd`, starting on Thursday (1970-01-01).
days_short: [&'static str; 7],
/// The picture of a `DATE` field without `\@`.
default: &'static str,
}
const ENGLISH: DateNames = DateNames {
months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
months_short: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
days: ["Thursday", "Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday"],
days_short: ["Thu", "Fri", "Sat", "Sun", "Mon", "Tue", "Wed"],
default: "M/d/yyyy",
};
@@ -227,14 +232,46 @@ const ENGLISH: DateNames = DateNames {
/// `ddd` = `qui`, and `dd/MM/yyyy` for a field without a picture.
const PORTUGUESE: DateNames = DateNames {
months: ["janeiro", "fevereiro", "março", "abril", "maio", "junho", "julho", "agosto", "setembro", "outubro", "novembro", "dezembro"],
months_short: ["jan", "fev", "mar", "abr", "mai", "jun", "jul", "ago", "set", "out", "nov", "dez"],
days: ["quinta-feira", "sexta-feira", "sábado", "domingo", "segunda-feira", "terça-feira", "quarta-feira"],
days_short: ["qui", "sex", "sáb", "dom", "seg", "ter", "qua"],
default: "dd/MM/yyyy",
};
/// Choose month and weekday names according to the primary language subtag.
/// German (Word's Windows NLS forms): `MMMM` = `März`, `MMM` = `Mrz`, `ddd` = `Fr` (two
/// letters), and `dd.MM.yyyy` for a field without a picture. Covers de-DE, de-CH and bare `de`.
const GERMAN: DateNames = DateNames {
months: ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
months_short: ["Jan", "Feb", "Mrz", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"],
days: ["Donnerstag", "Freitag", "Samstag", "Sonntag", "Montag", "Dienstag", "Mittwoch"],
days_short: ["Do", "Fr", "Sa", "So", "Mo", "Di", "Mi"],
default: "dd.MM.yyyy",
};
/// Austrian Standard German: January is `Jänner`, abbreviated `Jän` (Österreichisches
/// Wörterbuch; Windows NLS `de-AT`). Every other month and weekday matches [`GERMAN`].
const GERMAN_AUSTRIA: DateNames = DateNames {
months: ["Jänner", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
months_short: ["Jän", "Feb", "Mrz", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"],
days: ["Donnerstag", "Freitag", "Samstag", "Sonntag", "Montag", "Dienstag", "Mittwoch"],
days_short: ["Do", "Fr", "Sa", "So", "Mo", "Di", "Mi"],
default: "dd.MM.yyyy",
};
/// Choose month and weekday names from the language tag: the primary subtag picks the language,
/// and a region subtag refines it (`de-AT` writes `Jänner`). Tags compare case-insensitively, as
/// `w:lang` values do.
fn date_names(lang: Option<&str>) -> &'static DateNames {
let primary = lang.and_then(|l| l.trim().split(['-', '_']).next()).unwrap_or("");
if primary.eq_ignore_ascii_case("pt") { &PORTUGUESE } else { &ENGLISH }
let mut subtags = lang.unwrap_or("").trim().split(['-', '_']);
let primary = subtags.next().unwrap_or("");
if primary.eq_ignore_ascii_case("pt") {
&PORTUGUESE
} else if primary.eq_ignore_ascii_case("de") {
// Austria keeps `Jänner` / `Jän`; Germany and Switzerland keep `Januar` / `Jan`.
if subtags.any(|region| region.eq_ignore_ascii_case("AT")) { &GERMAN_AUSTRIA } else { &GERMAN }
} else {
&ENGLISH
}
}
/// The picture Word gives a `DATE` field that has no `\@` switch, in the field's language.
@@ -252,9 +289,12 @@ pub fn format_date_parts(fmt: &str, y: i64, m: usize, d: u32, hms: (u32, u32, u3
#[allow(clippy::too_many_arguments)]
pub fn format_date_parts_in(fmt: &str, lang: Option<&str>, y: i64, m: usize, d: u32, (hh, mm, ss): (u32, u32, u32), days_since: i64) -> String {
let names = date_names(lang);
let month = names.months.get(m.saturating_sub(1)).copied().unwrap_or(names.months[0]);
let day = names.days.get(days_since.rem_euclid(7) as usize).copied().unwrap_or(names.days[0]);
let three = |s: &str| -> String { s.chars().take(3).collect() };
let mi = m.saturating_sub(1);
let di = days_since.rem_euclid(7) as usize;
let month = names.months.get(mi).copied().unwrap_or(names.months[0]);
let month_short = names.months_short.get(mi).copied().unwrap_or(names.months_short[0]);
let day = names.days.get(di).copied().unwrap_or(names.days[0]);
let day_short = names.days_short.get(di).copied().unwrap_or(names.days_short[0]);
let mut out = String::new();
let chars: Vec<char> = fmt.chars().collect();
let mut i = 0;
@@ -296,11 +336,11 @@ pub fn format_date_parts_in(fmt: &str, lang: Option<&str>, y: i64, m: usize, d:
('y' | 'Y', 4..) => out.push_str(&format!("{y:04}")),
('y' | 'Y', _) => out.push_str(&format!("{:02}", y % 100)),
('M', 4..) => out.push_str(month),
('M', 3) => out.push_str(&three(month)),
('M', 3) => out.push_str(month_short),
('M', 2) => out.push_str(&format!("{m:02}")),
('M', 1) => out.push_str(&m.to_string()),
('d' | 'D', 4..) => out.push_str(day),
('d' | 'D', 3) => out.push_str(&three(day)),
('d' | 'D', 3) => out.push_str(day_short),
('d' | 'D', 2) => out.push_str(&format!("{d:02}")),
('d' | 'D', 1) => out.push_str(&d.to_string()),
('H', 2..) => out.push_str(&format!("{hh:02}")),
@@ -311,7 +351,7 @@ pub fn format_date_parts_in(fmt: &str, lang: Option<&str>, y: i64, m: usize, d:
('m', _) => out.push_str(&mm.to_string()),
('s', 2..) => out.push_str(&format!("{ss:02}")),
('s', _) => out.push_str(&ss.to_string()),
('a' | 'A', _) => out.push_str(if hh < 12 { "AM" } else { "PM" }),
// Bare `a`/`A` is literal; AM/PM is the `am/pm` token (#3488).
_ => {
for _ in 0..n {
out.push(c);
@@ -574,6 +614,43 @@ mod date_time_locale_tests {
assert_eq!(format("MMMM", 20), "outubro");
}
/// German month and weekday names, and the default picture, are chosen by the language tag
/// (de-DE, de-AT, de-CH), as in Word (#7146).
#[test]
fn german_date_names_render_for_de() {
assert_eq!(format_date_parts_in("dddd, d. MMMM yyyy", Some("de-DE"), 2026, 11, 21, (12, 0, 0), 2), "Samstag, 21. November 2026");
assert_eq!(default_date_picture(Some("de-CH")), "dd.MM.yyyy");
}
/// Windows NLS short forms: two-letter weekdays (`Mo`, `Di`…) and `Mrz` for March, with no
/// trailing full stop (#7146).
#[test]
fn german_short_names_match_windows_nls() {
let format = |pic| format_date_parts_in(pic, Some("de-DE"), 2026, 3, 15, (12, 0, 0), 3);
assert_eq!(format("ddd, d. MMM yyyy"), "So, 15. Mrz 2026");
assert_eq!(format("dddd"), "Sonntag");
assert_eq!(format("MMM"), "Mrz");
}
/// Austrian Standard German writes January as `Jänner` (`Jän`), while Germany, Switzerland
/// and bare `de` keep `Januar` (`Jan`); every other name is shared (#7146).
#[test]
fn austrian_german_january_is_jaenner() {
let january = |lang, pic| format_date_parts_in(pic, Some(lang), 2026, 1, 15, (12, 0, 0), 0);
assert_eq!(january("de-AT", "MMMM"), "Jänner");
assert_eq!(january("de-AT", "MMM"), "Jän");
assert_eq!(january("de_at", "MMMM"), "Jänner", "region subtags compare case-insensitively");
for lang in ["de-DE", "de-CH", "de"] {
assert_eq!(january(lang, "MMMM"), "Januar", "{lang}");
assert_eq!(january(lang, "MMM"), "Jan", "{lang}");
}
// Only January differs: February and March read the same in Austria and Germany.
for month in [2, 3] {
let names = |lang| format_date_parts_in("MMMM MMM", Some(lang), 2026, month, 1, (12, 0, 0), 0);
assert_eq!(names("de-AT"), names("de-DE"));
}
}
/// A pt-BR dynamic field keeps its result after DOCX round-trip and refresh.
#[test]
fn pt_br_date_time_dialog_inserts_dynamic_field() {
+30 -10
View File
@@ -84,25 +84,45 @@ pub(super) fn link(s: &mut Session, v: &Value) -> CmdResult {
sel_result(s)
}
/// The `text` to retype a selection with before linking it: only when it differs from the selected
/// text and both fit in one line of one paragraph without pictures or fields, outside any field's
/// result. Otherwise (as Word shows `<<Selection in Document>>`) the selection keeps its text.
fn retyped_text(s: &Session, v: &Value) -> Option<String> {
/// What can't stand in one line of text: breaks, and pictures or fields.
const NOT_ONE_LINE: [char; 7] = {
use wordcraft_doc::para::{COLUMN_BREAK, LINE_BREAK, OBJ, PAGE_BREAK};
/// What can't stand in one line of text: breaks, and pictures or fields.
const NOT_ONE_LINE: [char; 7] = [LINE_BREAK, '\r', '\u{2029}', '\u{b}', PAGE_BREAK, COLUMN_BREAK, OBJ];
let text = p::str(v, "text").filter(|t| !t.is_empty() && t.len() <= 4096)?;
if text.contains(NOT_ONE_LINE) {
[LINE_BREAK, '\r', '\u{2029}', '\u{b}', PAGE_BREAK, COLUMN_BREAK, OBJ]
};
/// The raw text of the selection when it is one run of one paragraph without breaks, pictures or fields.
fn one_line_selection(s: &Session) -> Option<&str> {
// A column (block) selection has both ends in one paragraph but holds a piece of each line it
// covers: it isn't one line of text (#8581).
if s.column_segments().is_some_and(|segs| !segs.is_empty()) {
return None;
}
let (a, b) = s.sel.ordered();
if a.story != b.story || a.path != b.path {
return None;
}
let shown = s.doc.para(a.story, &a.path)?.text.get(a.off..b.off)?;
if shown.contains(NOT_ONE_LINE) || shown == text {
s.doc.para(a.story, &a.path)?.text.get(a.off..b.off).filter(|t| !t.contains(NOT_ONE_LINE))
}
/// Whether the selection is plain text in one line of one paragraph: otherwise (as Word shows
/// `<<Selection in Document>>`) Text to display can't show it and linking keeps its content (#8286).
pub fn selection_is_one_line(s: &Session) -> bool {
one_line_selection(s).is_some()
}
/// The `text` to retype a selection with before linking it: only when it differs from the selected
/// text and both fit in one line of one paragraph without pictures or fields, outside any field's
/// result. Otherwise (as Word shows `<<Selection in Document>>`) the selection keeps its text.
fn retyped_text(s: &Session, v: &Value) -> Option<String> {
let text = p::str(v, "text").filter(|t| !t.is_empty() && t.len() <= 4096)?;
if text.contains(NOT_ONE_LINE) {
return None;
}
let shown = one_line_selection(s)?;
if shown == text {
return None;
}
let (a, b) = s.sel.ordered();
// A selection in a field's result (between its markers, which it doesn't hold) is retyped by
// the next update of the field, not here.
if s.doc.field_ranges(a.story).iter().any(|r| r.start < b && a <= r.end) {
+6 -1
View File
@@ -23,8 +23,13 @@ fn insert_block_at_caret(s: &mut Session, block: Block) -> Result<Path, CmdError
Ok(insert_at)
}
/// Most rows an inserted table has. The table model holds more, but an inserted table starts
/// small: the command that inserts one clamps to this, so the others read it rather than
/// repeating the number.
pub const MAX_TABLE_ROWS: usize = 1_000;
pub(super) fn table(s: &mut Session, v: &Value) -> CmdResult {
let rows = p::u64(v, "rows").unwrap_or(2).clamp(1, 1000) as usize;
let rows = p::u64(v, "rows").unwrap_or(2).clamp(1, MAX_TABLE_ROWS as u64) as usize;
let cols = p::u64(v, "cols").unwrap_or(2).clamp(1, 63) as usize;
let width = s.doc.sections().first().map(|(_, sp)| sp.text_width()).unwrap_or(468.0);
let mut t = Table::new(rows, cols, width);
+2
View File
@@ -358,6 +358,8 @@ fn date_pictures_keep_quoted_text() {
// Two quotes outside quoted text are one too (an apostrophe), not an empty quoted text.
assert_eq!(format_date_parts("yyyy '' MM", 2026, 10, 21, (0, 0, 0), 0), "2026 ' 10");
assert_eq!(format_date_parts("d''MM", 2026, 10, 21, (0, 0, 0), 0), "21'10");
// Bare `a` is literal, not AM/PM (#3488).
assert_eq!(format_date_parts("yyyy a", 2026, 10, 21, (14, 30, 0), 0), "2026 a");
}
#[test]
+1 -1
View File
@@ -27,7 +27,7 @@ pub use merge::{merge_range, refresh};
#[cfg(test)]
use merge::{mergefield_name, placeholder};
use recipients::recipients;
pub use recipients::{RECIPIENT_EXTENSIONS, is_spreadsheet_name, parse_csv};
pub use recipients::{CsvLimits, MAX_CELLS, MAX_FIELDS, MAX_TEXT_BYTES, RECIPIENT_EXTENSIONS, RECIPIENT_LIMITS, is_spreadsheet_name, parse_csv};
/// The mail-merge data source and preview state (lives in the session, not the document).
#[derive(Clone, Debug, Default)]
+75 -19
View File
@@ -19,22 +19,32 @@ fn csv_separator(text: &str) -> char {
[',', ';', '\t'].into_iter().max_by_key(|c| unquoted.matches(*c).count()).unwrap_or(',')
}
/// Ends the current row: kept when it has any non-empty field, otherwise dropped.
fn push_csv_row(rows: &mut Vec<Vec<String>>, row: &mut Vec<String>) {
if row.iter().any(|x| !x.is_empty()) {
rows.push(std::mem::take(row));
} else {
row.clear();
}
/// What a CSV may hold while it is read: the parser refuses a list that is over these, so a
/// hostile file is never built and then cut.
#[derive(Clone, Copy)]
pub struct CsvLimits {
/// Most columns in a record.
pub fields: usize,
/// Most cells in the list: its records times its widest record.
pub cells: usize,
/// Most bytes of cell text in all.
pub text: usize,
}
/// Parse CSV (RFC 4180-ish: quotes, doubled quotes, commas/semicolons/tabs).
pub fn parse_csv(text: &str) -> Vec<Vec<String>> {
///
/// The limits are kept while the list is read, not after it: a record wider than
/// `limits.fields`, a list of more than `limits.cells` cells, or more than `limits.text` bytes
/// of cell text is refused, rather than built and then cut.
pub fn parse_csv(text: &str, limits: &CsvLimits) -> Result<Vec<Vec<String>>, CmdError> {
let sep = csv_separator(text);
let mut rows = Vec::new();
let mut row = Vec::new();
let mut cell = String::new();
let mut q = false;
// The widest record read so far, and the bytes of cell text read so far.
let mut widest = 0usize;
let mut text_bytes = 0usize;
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
if q {
@@ -51,29 +61,75 @@ pub fn parse_csv(text: &str) -> Vec<Vec<String>> {
} else if c == '"' {
q = true;
} else if c == sep {
row.push(std::mem::take(&mut cell));
end_cell(&mut row, &mut cell, &mut text_bytes, limits)?;
} else if c == '\n' || c == '\r' {
if c == '\r' && chars.peek() == Some(&'\n') {
chars.next();
}
row.push(std::mem::take(&mut cell));
push_csv_row(&mut rows, &mut row);
end_cell(&mut row, &mut cell, &mut text_bytes, limits)?;
end_row(&mut rows, &mut row, &mut widest, limits)?;
} else {
cell.push(c);
}
// The text read so far: the finished cells and the one being read.
if text_bytes.saturating_add(cell.len()) > limits.text {
return Err(CmdError::Failed(format!("the CSV can't have more than {} of text", text_size(limits.text))));
}
if rows.len() > 100_000 {
break;
}
}
row.push(cell);
push_csv_row(&mut rows, &mut row);
rows
// The last cell, when the file doesn't end with a line break.
end_cell(&mut row, &mut cell, &mut text_bytes, limits)?;
end_row(&mut rows, &mut row, &mut widest, limits)?;
Ok(rows)
}
/// A finished cell joins the record: the record's width stays inside the limit.
fn end_cell(row: &mut Vec<String>, cell: &mut String, text_bytes: &mut usize, limits: &CsvLimits) -> Result<(), CmdError> {
*text_bytes = text_bytes.saturating_add(cell.len());
row.push(std::mem::take(cell));
if row.len() > limits.fields {
return Err(CmdError::Failed(format!("the CSV can't have more than {} columns", limits.fields)));
}
Ok(())
}
/// A finished record joins the list (an empty one is dropped). The list costs its records times
/// its widest record — a recipient list pads every record to the header's width — so a list
/// over the limit is refused here, while it is read.
fn end_row(rows: &mut Vec<Vec<String>>, row: &mut Vec<String>, widest: &mut usize, limits: &CsvLimits) -> Result<(), CmdError> {
if row.iter().any(|x| !x.is_empty()) {
*widest = (*widest).max(row.len());
rows.push(std::mem::take(row));
} else {
row.clear();
}
if rows.len().saturating_mul(*widest) > limits.cells {
return Err(CmdError::Failed(format!("the CSV can't have more than {} cells (its records times its widest record)", limits.cells)));
}
Ok(())
}
/// A byte budget, said the way a reader says it.
fn text_size(bytes: usize) -> String {
if bytes >= 1 << 20 { format!("{} MB", bytes >> 20) } else { format!("{bytes} bytes") }
}
/// Most records and fields a recipient list keeps.
const MAX_RECORDS: usize = 100_000;
const MAX_FIELDS: usize = 1_000;
pub const MAX_FIELDS: usize = 1_000;
/// Most cells a recipient list keeps: its records times its fields. A recipient list pads every
/// record to the header's width, so this is what a list costs, not how many values it says.
pub const MAX_CELLS: usize = 2_000_000;
/// Most bytes of cell text a recipient list keeps. The table path keeps the same budget.
pub const MAX_TEXT_BYTES: usize = 64 << 20;
/// The limits a recipient list keeps.
pub const RECIPIENT_LIMITS: CsvLimits = CsvLimits { fields: MAX_FIELDS, cells: MAX_CELLS, text: MAX_TEXT_BYTES };
pub(super) fn cell(x: &Value) -> String {
match x {
@@ -117,12 +173,12 @@ fn table_from_rows(fields: Option<&Vec<Value>>, arr: &[Value]) -> Result<(Vec<St
/// Skip unquoted blank prefix lines only when a text recipient list has a header.
/// Headerless lists and the shared CSV reader keep whitespace records.
fn recipient_csv(text: &str, headers: bool) -> Vec<Vec<String>> {
fn recipient_csv(text: &str, headers: bool) -> Result<Vec<Vec<String>>, CmdError> {
let prefix = text
.split_inclusive(['\n', '\r'])
.take_while(|line| headers && line.trim().is_empty())
.fold(0_usize, |bytes, line| bytes.saturating_add(line.len()));
parse_csv(text.get(prefix..).unwrap_or_default())
parse_csv(text.get(prefix..).unwrap_or_default(), &RECIPIENT_LIMITS)
}
pub(super) fn recipients(s: &mut Session, v: &Value) -> CmdResult {
@@ -131,7 +187,7 @@ pub(super) fn recipients(s: &mut Session, v: &Value) -> CmdResult {
table_from_rows(v.get("fields").and_then(Value::as_array), arr)?
} else {
let all = if let Some(c) = p::str(v, "csv") {
recipient_csv(c, p::bool(v, "headers").unwrap_or(true))
recipient_csv(c, p::bool(v, "headers").unwrap_or(true))?
} else {
let (bytes, ext) = if let Some(d) = p::str(v, "data") {
let b = crate::cmd::insert::base64_decode(d.trim()).ok_or_else(|| CmdError::Params("`data` isn't valid base64".into()))?;
@@ -188,7 +244,7 @@ pub(super) fn recipients(s: &mut Session, v: &Value) -> CmdResult {
sheet = json!(chosen);
rows
} else {
recipient_csv(&decode(&bytes, v)?, p::bool(v, "headers").unwrap_or(true))
recipient_csv(&decode(&bytes, v)?, p::bool(v, "headers").unwrap_or(true))?
}
};
header_split(all, p::bool(v, "headers").unwrap_or(true))?
+71 -16
View File
@@ -2,9 +2,54 @@ use super::*;
#[test]
fn csv_parsing() {
let r = parse_csv("Name,City\n\"Smith, Ann\",Paris\r\nBo,\"Oslo \"\"N\"\"\"\n\n");
let r = parse_csv("Name,City\n\"Smith, Ann\",Paris\r\nBo,\"Oslo \"\"N\"\"\"\n\n", &RECIPIENT_LIMITS).unwrap();
assert_eq!(r, vec![vec!["Name", "City"], vec!["Smith, Ann", "Paris"], vec!["Bo", "Oslo \"N\""]]);
assert_eq!(parse_csv("a;b\n1;2")[1], vec!["1", "2"]);
assert_eq!(parse_csv("a;b\n1;2", &RECIPIENT_LIMITS).unwrap()[1], vec!["1", "2"]);
}
/// The parser keeps its limits while it reads the list, so a hostile list is refused
/// instead of being built and then cut.
#[test]
fn csv_parsing_refuses_a_list_over_its_limits() {
// A record wider than the limit.
let e = parse_csv("a,b,c,d,e", &CsvLimits { fields: 4, cells: 100, text: 1_000 }).unwrap_err();
assert!(e.to_string().contains("4 columns"), "{e}");
// More cells than the list keeps.
let e = parse_csv("a,b\nc,d\ne,f\ng,h\ni,j\nk,l", &CsvLimits { fields: 10, cells: 10, text: 1_000 }).unwrap_err();
assert!(e.to_string().contains("10 cells"), "{e}");
// More text than the list keeps.
let e = parse_csv("abcdefghij", &CsvLimits { fields: 10, cells: 100, text: 8 }).unwrap_err();
assert!(e.to_string().contains("of text"), "{e}");
// A list inside the limits still parses.
let limits = CsvLimits { fields: 4, cells: 10, text: 1_000 };
assert_eq!(parse_csv("a,b\nc,d", &limits).unwrap(), vec![vec!["a", "b"], vec!["c", "d"]]);
}
/// A recipient list over its limits is refused, not built.
#[test]
fn a_recipient_list_over_its_limits_is_refused() {
// A record wider than the list's fields.
let wide = format!("{}\nvalue", "f,".repeat(MAX_FIELDS + 1));
let e = parse_csv(&wide, &RECIPIENT_LIMITS).unwrap_err();
assert!(e.to_string().contains(&format!("{MAX_FIELDS} columns")), "{e}");
// A record of exactly the limit's width is kept.
let exact = format!("{}\nvalue", "f,".repeat(MAX_FIELDS - 1));
assert_eq!(parse_csv(&exact, &RECIPIENT_LIMITS).unwrap()[0].len(), MAX_FIELDS);
// A wide header over many records: the list would cost more cells than it keeps, and
// every record is padded to the header's width.
let mut csv = format!("{}\n", (0..MAX_FIELDS).map(|i| format!("f{i}")).collect::<Vec<_>>().join(","));
for _ in 0..=MAX_CELLS / MAX_FIELDS {
csv.push_str("value\n");
}
let e = parse_csv(&csv, &RECIPIENT_LIMITS).unwrap_err();
assert!(e.to_string().contains(&format!("{MAX_CELLS} cells")), "{e}");
// The command refuses it too, with a message of its own.
let mut s = Session::new(Document::new());
let e = s.run("mailings.recipients", &json!({"csv": wide})).unwrap_err();
assert!(e.to_string().contains("columns"), "{e}");
}
/// #4001: finishing a merge opens a new document, with a new undo history. It is not an
@@ -56,13 +101,16 @@ fn csv_delimiter_reads_complete_header_record() {
let quoted = header.replace('"', "\"\"");
let text = format!("\"{quoted}\"{sep}City{sep}{sep}\r\nAda{sep}Paris{sep}{sep}\nBo{sep}Oslo{sep}{sep}");
assert_eq!(
parse_csv(&text),
parse_csv(&text, &RECIPIENT_LIMITS).unwrap(),
vec![vec![header.as_str(), "City", "", ""], vec!["Ada", "Paris", "", ""], vec!["Bo", "Oslo", "", ""]],
"separator {sep:?}, embedded newline {newline:?}"
);
// A multiline field after an ordinary column must not end detection either.
let text = format!("ID{sep}\"{quoted}\"{sep}City\n1{sep}Ada{sep}Paris\n2{sep}Bo{sep}Oslo");
assert_eq!(parse_csv(&text), vec![vec!["ID", header.as_str(), "City"], vec!["1", "Ada", "Paris"], vec!["2", "Bo", "Oslo"]]);
assert_eq!(
parse_csv(&text, &RECIPIENT_LIMITS).unwrap(),
vec![vec!["ID", header.as_str(), "City"], vec!["1", "Ada", "Paris"], vec!["2", "Bo", "Oslo"]]
);
}
}
}
@@ -74,7 +122,7 @@ fn csv_delimiter_reads_multiline_headers_after_blank_lines() {
let header = format!("Given{newline}Family");
for prefix in ["\n\r\n", "\r", "\r\r"] {
let text = format!("{prefix}\"{header}\"{sep}City\rAda{sep}Paris");
assert_eq!(parse_csv(&text), vec![vec![header.as_str(), "City"], vec!["Ada", "Paris"]]);
assert_eq!(parse_csv(&text, &RECIPIENT_LIMITS).unwrap(), vec![vec![header.as_str(), "City"], vec!["Ada", "Paris"]]);
}
}
}
@@ -99,34 +147,41 @@ fn recipient_csv_blank_prefix_keeps_columns_without_dropping_literal_records() {
let rows = s.merge.rows.clone();
assert!(s.run("mailings.recipients", &json!({"csv": " \t\r\n \r"})).is_err());
assert_eq!(s.merge.rows, rows, "an empty headered list must not replace existing recipients");
assert_eq!(parse_csv(" \nName,Email\nAda,ada@example.com")[0], vec![" "], "the shared CSV reader keeps literal whitespace rows");
assert_eq!(
parse_csv(" \nName,Email\nAda,ada@example.com", &RECIPIENT_LIMITS).unwrap()[0],
vec![" "],
"the shared CSV reader keeps literal whitespace rows"
);
}
#[test]
fn csv_delimiter_keeps_record_boundaries_and_ties() {
// Later records cannot choose the header's delimiter.
assert_eq!(parse_csv("Name;City\rAda;Paris,,,,\rBo;Oslo"), vec![vec!["Name", "City"], vec!["Ada", "Paris,,,,"], vec!["Bo", "Oslo"]]);
assert_eq!(
parse_csv("Name;City\rAda;Paris,,,,\rBo;Oslo", &RECIPIENT_LIMITS).unwrap(),
vec![vec!["Name", "City"], vec!["Ada", "Paris,,,,"], vec!["Bo", "Oslo"]]
);
// Existing ties prefer tab, then semicolon, then comma.
assert_eq!(parse_csv("A,B;C\n1,2;3"), vec![vec!["A,B", "C"], vec!["1,2", "3"]]);
assert_eq!(parse_csv("A;B\tC\n1;2\t3"), vec![vec!["A;B", "C"], vec!["1;2", "3"]]);
assert_eq!(parse_csv("Name\nAda,Paris;Oslo"), vec![vec!["Name"], vec!["Ada,Paris;Oslo"]]);
assert!(parse_csv("").is_empty());
assert_eq!(parse_csv("\nName\nAda"), vec![vec!["Name"], vec!["Ada"]]);
assert_eq!(parse_csv("A,B;C\n1,2;3", &RECIPIENT_LIMITS).unwrap(), vec![vec!["A,B", "C"], vec!["1,2", "3"]]);
assert_eq!(parse_csv("A;B\tC\n1;2\t3", &RECIPIENT_LIMITS).unwrap(), vec![vec!["A;B", "C"], vec!["1;2", "3"]]);
assert_eq!(parse_csv("Name\nAda,Paris;Oslo", &RECIPIENT_LIMITS).unwrap(), vec![vec!["Name"], vec!["Ada,Paris;Oslo"]]);
assert!(parse_csv("", &RECIPIENT_LIMITS).unwrap().is_empty());
assert_eq!(parse_csv("\nName\nAda", &RECIPIENT_LIMITS).unwrap(), vec![vec!["Name"], vec!["Ada"]]);
// The reader remains permissive about an unterminated quoted cell.
assert_eq!(parse_csv("Name,City\nAda,\"Paris\nOslo"), vec![vec!["Name", "City"], vec!["Ada", "Paris\nOslo"]]);
assert_eq!(parse_csv("Name,City\nAda,\"Paris\nOslo", &RECIPIENT_LIMITS).unwrap(), vec![vec!["Name", "City"], vec!["Ada", "Paris\nOslo"]]);
}
#[test]
fn csv_delimiter_ignores_quoted_text() {
let r = parse_csv("\"Name, first, last\";City\nAnn;Paris\n");
let r = parse_csv("\"Name, first, last\";City\nAnn;Paris\n", &RECIPIENT_LIMITS).unwrap();
assert_eq!(r, vec![vec!["Name, first, last", "City"], vec!["Ann", "Paris"]]);
}
#[test]
fn csv_delimiter_skips_leading_blank_lines() {
let want = vec![vec!["Name", "Email"], vec!["Ann", "ann@x.org"]];
assert_eq!(parse_csv("\nName,Email\nAnn,ann@x.org\n"), want);
assert_eq!(parse_csv("\r\n\r\nName;Email\r\nAnn;ann@x.org"), want);
assert_eq!(parse_csv("\nName,Email\nAnn,ann@x.org\n", &RECIPIENT_LIMITS).unwrap(), want);
assert_eq!(parse_csv("\r\n\r\nName;Email\r\nAnn;ann@x.org", &RECIPIENT_LIMITS).unwrap(), want);
}
/// Field types ignore case (ECMA-376 Part 1, 17.16.1), and `MERGEFIELDX` is another field.
+24 -10
View File
@@ -103,7 +103,7 @@ fn exact_text(s: &Session) -> Option<String> {
return res.clone();
}
let kept = [s.md_file.latest.as_deref(), s.md_file.saved.as_deref()];
let res = kept.into_iter().flatten().find(|text| parse(&s.doc, text).same_content(&s.doc)).map(str::to_string);
let res = kept.into_iter().flatten().find(|text| parse(&s.doc, text).is_ok_and(|d| d.same_content(&s.doc))).map(str::to_string);
*s.md_file.cached_exact.borrow_mut() = Some((s.rev(), res.clone()));
res
}
@@ -216,15 +216,16 @@ fn enter(s: &mut Session) -> Result<(), CmdError> {
// The file's own text when it still says what the document holds, so nothing is lost.
let (text, loses_content, block_lines) = match exact_text(s) {
Some(text) => {
let (_, lines) = parse_with_lines(&s.doc, &text);
let (_, lines) = parse_with_lines(&s.doc, &text)?;
(text, false, lines)
}
None => {
let text = wordcraft_formats::markdown::export(&s.doc);
let text = wordcraft_formats::markdown::export(&s.doc)
.map_err(|e| CmdError::Failed(format!("the document cannot be written as Markdown: {e}")))?;
if text.len() > MAX_SOURCE_BYTES {
return Err(CmdError::Failed(too_long()));
}
let (doc, lines) = parse_with_lines(&s.doc, &text);
let (doc, lines) = parse_with_lines(&s.doc, &text)?;
let loses_content = !doc.same_content(&s.doc);
(text, loses_content, lines)
}
@@ -289,7 +290,19 @@ pub fn apply(s: &mut Session) {
}
(src.text.clone(), src.entry_text.clone(), src.entry_doc.clone(), src.has_step, src.entry_lines.clone())
};
let (doc, lines) = if text == *entry_text { ((*entry_doc).clone(), entry_lines) } else { parse_with_lines(&s.doc, &text) };
let (doc, lines) = if text == *entry_text {
((*entry_doc).clone(), entry_lines)
} else {
// The text cannot be read as Markdown: the document stays as it is, rather than
// becoming an empty one.
match parse_with_lines(&s.doc, &text) {
Ok(v) => v,
Err(e) => {
s.status = e.to_string();
return;
}
}
};
let step = if !has_step {
s.checkpoint(LABEL);
Some(s.undo_mark())
@@ -313,19 +326,20 @@ pub fn apply(s: &mut Session) {
/// `text` as a document and block lines, with what isn't in Markdown from `current`: its page, settings,
/// properties and language, as opening the file gave it.
fn parse_with_lines(current: &Document, text: &str) -> (Document, Vec<usize>) {
let (mut doc, lines) = wordcraft_formats::markdown::import_on_with_lines(text, &current.last_section);
fn parse_with_lines(current: &Document, text: &str) -> Result<(Document, Vec<usize>), CmdError> {
let (mut doc, lines) = wordcraft_formats::markdown::import_on_with_lines(text, &current.last_section)
.map_err(|e| CmdError::Failed(format!("the Markdown cannot be read: {e}")))?;
doc.ensure_nonempty();
doc.settings = current.settings.clone();
doc.core = current.core.clone();
Arc::make_mut(&mut doc.styles).default_chr.lang = current.styles.default_chr.lang.clone();
(doc, lines)
Ok((doc, lines))
}
/// `text` as a document, with what isn't in Markdown from `current`: its page, settings,
/// properties and language, as opening the file gave it.
fn parse(current: &Document, text: &str) -> Document {
parse_with_lines(current, text).0
fn parse(current: &Document, text: &str) -> Result<Document, CmdError> {
parse_with_lines(current, text).map(|(doc, _)| doc)
}
/// The byte offset where `line` starts, or the end of a text with fewer lines.
+22 -3
View File
@@ -56,7 +56,7 @@ pub fn cut_tracked(s: &mut Session) -> Result<bool, CmdError> {
if !s.doc.settings.track_changes || !s.doc.settings.track_moves || a == b || a.story != b.story || !move_sized(&s.clipboard_text) {
return Ok(false);
}
s.doc.revisions.push(Revision::new(RevisionKind::Delete, s.author.clone(), now_iso()));
s.doc.revisions.push(crate::cmd::made_revision(RevisionKind::Delete, s.author.clone(), now_iso()));
let rid = (s.doc.revisions.len() - 1) as u32;
let at = track_delete_as(s, &a, &b, rid)?.at;
s.sel = Selection::caret(at);
@@ -75,13 +75,13 @@ pub fn take_paste(s: &mut Session, frag: &Fragment) -> Option<u32> {
return None;
}
let src = s.doc.revisions.get(m.rev as usize).filter(|r| r.kind == RevisionKind::Delete && r.move_name.is_none())?;
let date = src.date.clone();
let (date, date_utc) = (src.date.clone(), src.date_utc.clone());
let taken: BTreeSet<&str> = s.doc.revisions.iter().filter_map(|r| r.move_name.as_deref()).collect();
let name = (1..).map(|n: u64| format!("move{n}")).find(|n| !taken.contains(n.as_str()))?;
if let Some(r) = s.doc.revisions.get_mut(m.rev as usize) {
r.move_name = Some(name.clone());
}
s.doc.revisions.push(Revision { kind: RevisionKind::Insert, author: s.author.clone(), date, move_name: Some(name) });
s.doc.revisions.push(Revision { kind: RevisionKind::Insert, author: s.author.clone(), date, move_name: Some(name), date_utc });
Some((s.doc.revisions.len() - 1) as u32)
}
@@ -278,4 +278,23 @@ mod tests {
assert_eq!(texts(&s), ["First one.", "Second one.", "Third one."]);
assert!(kinds(&mut s).is_empty());
}
/// A command that fails between a tracked cut and its paste changed nothing, so the move
/// the cut recorded is still there: the paste is a move, as it was before the command.
#[test]
fn a_failed_command_between_a_tracked_cut_and_its_paste_leaves_the_move() {
let mut s = Session::new(Document::new());
s.run("document.setText", &json!({"text": "First one.\nSecond one.\nThird one."})).unwrap();
s.run("file.setAuthor", &json!({"name": "Ana"})).unwrap();
s.run("review.trackChanges", &json!({"value": true})).unwrap();
s.run("select.range", &json!({"anchor": {"block": 1, "off": 0}, "focus": {"block": 2, "off": 0}})).unwrap();
s.run("edit.cut", &json!({})).unwrap();
// A command that fails: there is no such character style.
assert!(s.run("format.charStyle", &json!({"style": "NoSuchStyle"})).is_err());
s.run("caret.set", &json!({"pos": {"block": 0, "off": 0}})).unwrap();
s.run("edit.paste", &json!({})).unwrap();
let k = kinds(&mut s);
assert!(k.iter().any(|(k, m)| k == "moveTo" && m == "move1"), "{k:?}");
assert!(k.iter().any(|(k, m)| k == "moveFrom" && m == "move1"), "{k:?}");
}
}
+1
View File
@@ -29,6 +29,7 @@ pub use picture::{OriginalSize, PictureLook, cropped_original_size, fit_size, or
use picture::{clear_background, grown, picture_style};
#[cfg(test)]
pub(crate) use select::all_objects;
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};
+1 -1
View File
@@ -176,7 +176,7 @@ pub fn min_size(o: &InlineObject) -> f32 {
}
/// Select the object whose character is at `pos`.
pub(super) fn select_object(s: &mut Session, pos: &Pos) {
pub(crate) fn select_object(s: &mut Session, pos: &Pos) {
s.sel = Selection { anchor: pos.clone(), focus: Pos { off: pos.off + wordcraft_doc::para::OBJ.len_utf8(), ..pos.clone() } };
}
+20
View File
@@ -250,6 +250,26 @@ pub fn section_index_of_focus(s: &Session) -> usize {
}
}
/// The caret's section, for the header and footer commands. In a header or footer it is the
/// section of the caret's page when that page shows it: a section linked to the previous one
/// shows that section's header, so the header alone names the earlier section (#3639).
pub fn hf_section_of_focus(s: &mut Session) -> usize {
let wordcraft_doc::StoryRef::Part(id) = s.sel.focus.story else { return section_index_of_focus(s) };
let layout = s.layout();
match layout.pages.get(s.page_hint) {
Some(pg) if pg.header_story == Some(id) || pg.footer_story == Some(id) => pg.section,
_ => section_of_part(s, id),
}
}
/// The last body block of the caret's section ([`hf_section_of_focus`]), the block
/// [`wordcraft_doc::Document::section_mut`] takes. In a header or footer the caret's block index
/// counts that story's paragraphs, not the body's, so it would name another section (#3639).
pub fn section_end_of_focus(s: &mut Session) -> usize {
let i = hf_section_of_focus(s);
s.doc.sections().get(i).map(|(end, _)| *end).unwrap_or(0)
}
pub fn sect(s: &Session) -> SectionProps {
let i = section_index_of_focus(s);
s.doc.sections().get(i).map(|(_, x)| (*x).clone()).unwrap_or_default()
+2 -2
View File
@@ -200,7 +200,7 @@ pub fn specs() -> Vec<CommandSpec> {
r#"{"color": "RRGGBB" | null, "paragraph"?: bool} (text selected inside one paragraph is shaded itself, as in Word; `paragraph: true` shades the paragraphs instead, as Borders and Shading › Apply to: Paragraph)"#,
),
CommandSpec::new("para.borders", "Borders", "Home › Paragraph", borders).params(
r#"{"kind": "bottom|top|left|right|none|all|outside|inside|horizontalLine", "width"?: pt, "color"?: "RRGGBB", "style"?: "single|double|dotted|dashed|thick|triple|dotDash|wave", "sides"?: Sides} where Sides = {"top"|"left"|"bottom"|"right"|"between": {"style"?, "width"?: pt, "color"?: "RRGGBB"} | null}: exactly these sides (others off), instead of `kind`"#,
r#"{"kind": "bottom|top|left|right|none|all|outside|inside|horizontalLine", "width"?: pt, "color"?: "RRGGBB", "style"?: "single|double|dotted|dashed|thick|triple|dotDash|wave", "sides"?: Sides} where Sides = {"top"|"left"|"bottom"|"right"|"between": {"style"?, "width"?: pt, "color"?: "RRGGBB"} | null}: exactly these sides (others off), instead of `kind` (with whole table cells selected, `kind` borders the cells as a block instead of their paragraphs)"#,
),
CommandSpec::new("para.sort", "Sort", "Home › Paragraph", sort).params(r#"{"descending"?: bool}"#),
CommandSpec::new("para.keepNext", "Keep with Next", "Home › Paragraph › Line and Page Breaks", |s, v| tog(s, v, |p| p.keep_next, |p, b| p.keep_next = Some(b)))
@@ -304,7 +304,7 @@ pub fn specs() -> Vec<CommandSpec> {
/// start, so all of a paragraph's text is still text, except in the last paragraph of its story,
/// cell or box, where it stands for the paragraph with its mark. A selected picture, shape or text
/// box is its object character, not text (a field's object character is).
fn shades_text(s: &Session) -> bool {
pub fn shades_text(s: &Session) -> bool {
let (a, b) = s.sel.ordered();
if a == b || a.story != b.story || a.path != b.path {
return false;
@@ -102,6 +102,10 @@ pub(super) fn borders(s: &mut Session, v: &Value) -> CmdResult {
// A paragraph with a bottom border, like Word's Horizontal Line.
return fmt(s, &|p| p.borders = Some(Borders { bottom: Some(Border { width: 1.5, ..b }), ..Default::default() }));
}
// Whole table cells selected: the border goes on the cells, not their paragraphs (#7874).
if let Some(range) = s.cell_range().cloned() {
return crate::cmd::table::cell_block_borders(s, &range, kind, b);
}
fmt(s, &|p| {
let mut cur = p.borders.unwrap_or_default();
match kind {
+42 -13
View File
@@ -187,7 +187,7 @@ fn paste_special(s: &mut Session, v: &Value) -> CmdResult {
return Ok(r);
}
"formatted" => s.clipboard.clone().ok_or_else(|| CmdError::Failed("the clipboard is empty".into()))?,
"html" => adopt(s, import_html(&src)),
"html" => adopt(s, import_html(&src).map_err(|e| CmdError::Failed(format!("bad HTML: {e}")))?),
_ => adopt(s, wordcraft_formats::rtf::import(src.as_bytes()).map_err(|e| CmdError::Failed(format!("bad RTF: {e}")))?),
};
insert(s, frag)?;
@@ -204,8 +204,8 @@ const BLOCKQUOTE_INDENT: f32 = 36.0;
/// (#1270): it pastes as a Normal paragraph indented by the page's `blockquote` margins, else half
/// an inch each side, rather than in the (centred, italic) Quote style. Opening an .html file keeps
/// `<blockquote>` as Quote, so HTML round-trips.
fn import_html(html: &str) -> Document {
let mut doc = wordcraft_formats::html::import(html_fragment(html));
fn import_html(html: &str) -> Result<Document, String> {
let mut doc = wordcraft_formats::html::import(html_fragment(html))?;
let (left, right) = blockquote_margins(html);
for b in &mut doc.body {
each_para(Arc::make_mut(b), 0, &mut |p| {
@@ -217,7 +217,7 @@ fn import_html(html: &str) -> Document {
}
});
}
doc
Ok(doc)
}
/// The left and right margins (points) the payload's `<style>` sheets give `blockquote` — LibreOffice
@@ -294,7 +294,7 @@ fn has_content(d: &Document) -> bool {
/// [`MAX_PASTE_BYTES`], or it holds nothing to paste (the caller pastes the text then).
pub fn rich_fragment(s: &mut Session, v: &Value) -> Option<Fragment> {
let fits = |k: &str| p::str(v, k).filter(|t| !t.trim().is_empty() && t.len() <= MAX_PASTE_BYTES);
let doc = fits("html").map(import_html);
let doc = fits("html").and_then(|html| import_html(html).ok());
let doc = match doc.filter(has_content) {
Some(d) => d,
None => {
@@ -373,21 +373,22 @@ pub fn merge_formatting(s: &Session, frag: &mut Fragment) {
p.props = para.clone();
for run in &mut p.runs {
let src = std::mem::replace(&mut run.props, base.clone());
// Emphasis in either script is kept for both, as the Bold and Italic buttons set
// it: text pasted into a run marked `w:cs` (Thai from a WPS or Word file) is drawn
// with the complex-script bold and italic.
if src.bold == Some(true) || src.bold_cs == Some(true) {
let e = emphasis_of(s, &src);
// Emphasis the source shows in either script is kept for both, as the Bold and
// Italic buttons set it: text pasted into a run marked `w:cs` (Thai from a WPS or
// Word file) is drawn with the complex-script bold and italic.
if shown(e.bold, e.bold_cs, &e) {
run.props.bold = Some(true);
run.props.bold_cs = Some(true);
}
if src.italic == Some(true) || src.italic_cs == Some(true) {
if shown(e.italic, e.italic_cs, &e) {
run.props.italic = Some(true);
run.props.italic_cs = Some(true);
}
if src.underline.is_some_and(|u| u != wordcraft_doc::props::Underline::None) {
run.props.underline = src.underline;
if e.underline.is_some_and(|u| u != wordcraft_doc::props::Underline::None) {
run.props.underline = e.underline;
}
if src.strike == Some(true) {
if e.strike == Some(true) {
run.props.strike = Some(true);
}
run.props.link = src.link;
@@ -400,6 +401,34 @@ pub fn merge_formatting(s: &Session, frag: &mut Fragment) {
}
}
/// The formatting a pasted run's emphasis is judged by: its own, over its character style
/// chain's. Word keeps the bold, italic, underline and strikethrough a character style gives the
/// source, as direct formatting, but not a paragraph style's (measured in Word for Windows), so
/// the paragraph style isn't consulted.
fn emphasis_of(s: &Session, src: &wordcraft_doc::CharProps) -> wordcraft_doc::CharProps {
use wordcraft_doc::styles::StyleKind;
let mut e = wordcraft_doc::CharProps::default();
if let Some(id) = src.style.as_deref() {
for st in s.doc.styles.chain(id) {
if st.kind == StyleKind::Character || st.kind == StyleKind::Paragraph {
e.overlay(&st.chr);
}
}
}
e.overlay(&wordcraft_doc::CharProps { style: None, ..src.clone() });
e
}
/// Whether a run with these Latin and complex-script values of a toggle (bold or italic) shows
/// it anywhere, as the resolved formatting draws it: a run marked `w:cs` or `w:rtl` draws all
/// its text with the complex-script value, which borrows the Latin one unless the run is marked
/// `w:cs`; other runs draw their Latin text with the Latin value.
fn shown(latin: Option<bool>, complex: Option<bool>, run: &wordcraft_doc::CharProps) -> bool {
let complex_shown = complex.or(latin.filter(|_| run.cs != Some(true))) == Some(true);
let all_complex = run.cs == Some(true) || run.rtl == Some(true);
complex_shown || (!all_complex && latin == Some(true))
}
/// Paste `frag` at the selection. A copied table pasted with the caret in a table cell goes the way
/// Word's Paste does it (rows inserted or cells overwritten, #6739; see [`super::paste_cells`]);
/// anything else is [`insert_as_is`].
+10 -1
View File
@@ -305,7 +305,16 @@ pub(crate) fn greyed_out(s: &Session, id: &str, facts: impl FnOnce() -> Facts) -
}
}
let comment_ok = id.starts_with("review.") && (id.contains("Comment") || id == "review.reply");
let tracked = matches!(id, "review.accept" | "review.reject" | "review.acceptAll" | "review.rejectAll" | "review.trackChanges");
let tracked = matches!(
id,
"review.accept"
| "review.reject"
| "review.acceptAndNext"
| "review.rejectAndNext"
| "review.acceptAll"
| "review.rejectAll"
| "review.trackChanges"
);
match mode {
"readOnly" => (!facts().exceptions).then_some("the document is protected (read only)"),
"forms" => (facts().fillable == 0).then_some("the document is protected (read only)"),
+9 -1
View File
@@ -213,7 +213,15 @@ fn tracked_changes_protection_keeps_revisions() {
select(&mut s, "text");
s.run("text.insert", &json!({"text": "words"})).unwrap();
let before = s.doc.clone();
for id in ["review.acceptAll", "review.rejectAll", "review.accept", "review.reject", "review.trackChanges"] {
for id in [
"review.acceptAll",
"review.rejectAll",
"review.accept",
"review.reject",
"review.acceptAndNext",
"review.rejectAndNext",
"review.trackChanges",
] {
assert!(s.run(id, &json!({})).is_err(), "{id}");
}
assert_eq!(s.doc, before);
+31 -1
View File
@@ -422,7 +422,19 @@ pub fn update_fields_in(s: &mut Session, all: bool) -> Result<(), CmdError> {
"DATE" | "TIME" | "CREATEDATE" | "SAVEDATE" | "PRINTDATE" => {
let lang = field_lang(&s.doc, p, k);
let pic = date_picture(instr).unwrap_or_else(|| default_picture(&name, lang.as_deref()));
updates.push((k, text_result(instr, crate::cmd::insert::format_date_in(&pic, lang.as_deref()))));
let created = s.doc.core.created.trim();
// CREATEDATE shows when the document was created (ECMA-376 §17.16.5.11). A new
// document, never saved, has no creation date yet and saving stamps now. A
// file opened without one, or with one that can't be read, keeps the result
// it has.
let text = if name != "CREATEDATE" || (created.is_empty() && s.path.is_none()) {
crate::cmd::insert::format_date_in(&pic, lang.as_deref())
} else if let Some((unix, offset)) = created_at(created) {
crate::cmd::insert::format_date_at_in(&pic, lang.as_deref(), unix, offset)
} else {
continue;
};
updates.push((k, text_result(instr, text)));
}
"REF" | "PAGEREF" => {
let f = FieldCode::parse(instr);
@@ -572,6 +584,24 @@ fn field_lang(doc: &wordcraft_doc::Document, p: &wordcraft_doc::Paragraph, k: us
doc.styles.resolve_char(p.props.style.as_deref(), p.props_of_char(off)).lang
}
/// A core-properties creation date as seconds since the epoch and the UTC offset to show it at:
/// an instant (`2019-05-05T12:00:00Z`, any offset or fraction, or without the seconds,
/// `2019-05-05T12:00Z`, as W3CDTF allows) at the local offset, or a calendar date (`2019-05-05`)
/// at its own midnight, whatever the time zone. `None` for another form or a date before 1970.
fn created_at(stamp: &str) -> Option<(u64, i64)> {
let instant = chrono::DateTime::parse_from_rfc3339(stamp).ok().or_else(|| {
// `%:z` takes `+01:00` but not `Z`.
let utc = stamp.strip_suffix(['Z', 'z']).map(|t| format!("{t}+00:00"));
chrono::DateTime::parse_from_str(utc.as_deref().unwrap_or(stamp), "%Y-%m-%dT%H:%M%:z").ok()
});
if let Some(t) = instant {
let unix = u64::try_from(t.timestamp()).ok()?;
return Some((unix, crate::cmd::local_offset_secs(unix)));
}
let day = chrono::NaiveDate::parse_from_str(stamp, "%Y-%m-%d").ok()?;
Some((u64::try_from(day.and_hms_opt(0, 0, 0)?.and_utc().timestamp()).ok()?, 0))
}
/// Word's default date or time picture when a field instruction carries no `\@` picture switch.
fn default_picture(name: &str, lang: Option<&str>) -> String {
if name == "TIME" { "h:mm am/pm".into() } else { crate::cmd::insert::default_date_picture(lang).into() }
+117
View File
@@ -506,6 +506,56 @@ fn update_fields_all_covers_every_story() {
s.run("references.updateFields", &json!({"all": "yes"})).unwrap();
}
/// CREATEDATE shows when the document was created (ECMA-376 §17.16.5.11), not today's date.
#[test]
fn createdate_keeps_the_creation_date_on_update() {
let mut s = Session::new(wordcraft_doc::Document::new());
s.doc.core.created = "2019-05-05T12:00:00Z".into();
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#, "result": "2019-05"})).unwrap();
s.run("insert.field", &json!({"instr": "CREATEDATE"})).unwrap();
s.run("references.updateFields", &json!({})).unwrap();
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
// 12:00 UTC is 5 May from UTC-12 to UTC+11:59, the next day east of that.
let unix = 1_557_057_600;
let (_, _, day, _, _) = crate::cmd::local_civil(unix, crate::cmd::local_offset_secs(unix));
assert_eq!(results, ["2019-05".to_string(), format!("5/{day}/2019")]);
assert!(day == 5 || day == 6, "{day}");
// W3CDTF may leave out the seconds; that is the same instant.
for minutes in ["2019-05-05T12:00Z", "2019-05-05T14:00+02:00", "2019-05-05T07:00-05:00"] {
// From another date first, so an unread stamp, which keeps the result, shows.
s.doc.core.created = "2001-02-03".into();
s.run("references.updateFields", &json!({})).unwrap();
assert_eq!(fields(&s)[1].1, "2/3/2001");
s.doc.core.created = minutes.into();
s.run("references.updateFields", &json!({})).unwrap();
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
assert_eq!(results, ["2019-05".to_string(), format!("5/{day}/2019")], "{minutes}");
}
// A date without a time is that calendar day in every time zone.
s.doc.core.created = "2019-06-07".into();
s.run("references.updateFields", &json!({})).unwrap();
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
assert_eq!(results, ["2019-06", "6/7/2019"]);
}
/// A creation date that can't be read leaves the field's result as it was; a document that has
/// never been saved is created now (saving stamps that time as its creation date).
#[test]
fn createdate_without_a_readable_creation_date() {
let mut s = Session::new(wordcraft_doc::Document::new());
s.doc.core.created = "sometime in May".into();
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#, "result": "2019-05"})).unwrap();
assert_eq!(fields(&s)[0].1, "2019-05");
// A file opened without a creation date keeps the result too.
s.doc.core.created.clear();
s.path = Some(std::env::temp_dir().join("opened.docx"));
s.run("references.updateFields", &json!({})).unwrap();
assert_eq!(fields(&s)[0].1, "2019-05");
s.path = None;
s.run("references.updateFields", &json!({})).unwrap();
assert_eq!(fields(&s)[0].1, crate::cmd::insert::format_date("yyyy-MM"));
}
#[test]
fn toc_tabs_ignore_nonentries() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Before\nContents\nOld\t9\nAfter"));
@@ -560,6 +610,73 @@ fn caption_for_an_object_in_a_cell_stays_in_the_cell() {
assert_eq!(texts.get(1).map(String::as_str), Some("Figure 1"), "{texts:?}");
}
/// A TOC inserted before a heading leaves the caret at the heading's first character, past the
/// `_Toc` bookmark its entry links to: Delete then deletes that character, and the entry still
/// finds its heading (Delete at offset zero took the bookmark).
#[test]
fn the_caret_after_a_toc_sits_past_the_headings_bookmark() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Kilns\nBody text."));
s.run("para.style", &json!({"style": "Heading 1"})).unwrap();
s.sel = Selection::caret(Pos { story: StoryRef::Body, path: Path::top(0), off: 0 });
s.run("references.toc", &json!({"levels": 2})).unwrap();
let heading = s.doc.para_at(&s.sel.focus).cloned().unwrap();
assert_eq!(heading.plain_text(), "Kilns");
let marks = |p: &Paragraph| p.objects.iter().filter(|o| matches!(o, InlineObject::BookmarkStart { .. })).count();
assert_eq!(marks(&heading), 1, "the heading has its bookmark");
s.run("text.delete", &json!({})).unwrap();
let heading = s.doc.para_at(&s.sel.focus).cloned().unwrap();
assert_eq!(heading.plain_text(), "ilns", "Delete took the first character");
assert_eq!(marks(&heading), 1, "the bookmark stays");
}
/// Inserting a table of contents (Word itself warns when there's no heading yet, but still
/// creates an empty one) must leave the caret in a fresh paragraph just after it, like Word
/// does — not inside the table's own title, where typing the rest of the document (and later
/// updating the table) would splice stray text into unrelated paragraphs and blank the title.
#[test]
fn a_toc_inserted_before_any_headings_exist_leaves_the_caret_after_it() {
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("references.toc", &json!({"levels": 2})).unwrap();
assert_eq!(s.sel.focus.path, Path::top(1), "the caret must land right after the table, not inside it");
s.run("text.insert", &json!({"text": "\r"})).unwrap();
s.run("para.style", &json!({"style": "Heading 1"})).unwrap();
s.run("text.insert", &json!({"text": "Kilns\r"})).unwrap();
s.run("para.style", &json!({"style": "Normal"})).unwrap();
s.run("text.insert", &json!({"text": "Body text."})).unwrap();
s.run("references.updateToc", &json!({})).unwrap();
assert_eq!(
s.doc.plain_text(StoryRef::Body).matches("Contents").count(),
1,
"the title stays where it was, it doesn't vanish and reappear elsewhere"
);
assert!(s.doc.plain_text(StoryRef::Body).contains("Body text."), "typed body content survives untouched");
let heading = s.doc.body.iter().filter_map(|b| b.as_para()).find(|p| p.props.style.as_deref() == Some("Heading1"));
assert_eq!(heading.map(|p| p.plain_text()), Some("Kilns".to_string()));
}
/// A settings-based replacement of a table whose last entry is directly followed by a table
/// (nothing paragraph-shaped in between) must still land the caret in a real paragraph: the
/// block "after" the table isn't always a paragraph just because it exists.
#[test]
fn a_toc_replaced_right_before_a_table_still_lands_the_caret_in_a_paragraph() {
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("references.toc", &json!({"levels": 2})).unwrap();
s.run("insert.table", &json!({"rows": 1, "cols": 1})).unwrap();
let (_, end) = toc_range(&s).unwrap();
while s.doc.body.get(end + 1).is_some_and(|b| b.as_para().is_some_and(|p| p.is_empty())) {
s.doc.remove_block(StoryRef::Body, &Path::top(end + 1)).unwrap();
}
assert!(matches!(&*s.doc.body[end + 1], Block::Table(_)), "test setup: a table must directly follow the table's entries");
// Replacing the table's settings must still land the caret in a fresh paragraph right
// after the table, not snap back into the table's own entries (a bogus position pointing
// at the table gets silently corrected by `clamp_selection` to the nearest *preceding*
// paragraph, so a weaker "is this some paragraph" check wouldn't catch the regression).
s.run("references.toc", &json!({"levels": 3})).unwrap();
let (_, new_end) = toc_range(&s).unwrap();
assert_eq!(s.sel.focus.path, Path::top(new_end + 1), "the caret must land right after the table, not snap back into the table");
assert!(matches!(&*s.doc.body[new_end + 1], Block::Para(_)));
}
/// A fresh scratch directory for the file-name tests below.
#[cfg(not(target_arch = "wasm32"))]
fn filename_scratch_dir(tag: &str) -> std::path::PathBuf {
+35 -1
View File
@@ -412,6 +412,7 @@ pub(super) fn insert_toc(s: &mut Session, v: &Value) -> CmdResult {
// its paragraph ending the title's section, and the new entries follow in their columns.
Some((start, _)) if title_above_break(s, start).is_some() => {
replace_toc_above_break(s, v, start, &tabs)?;
caret_after_toc(s)?;
return sel_result(s);
}
Some((start, end)) => {
@@ -444,10 +445,43 @@ pub(super) fn insert_toc(s: &mut Session, v: &Value) -> CmdResult {
s.doc.insert_block(StoryRef::Body, &Path::top(i), Block::Para(head))?;
let leader = leader(p::str(v, "tabLeader").unwrap_or("dot"));
regenerate_toc(s, Some(leader), &tabs)?;
s.clamp_selection();
caret_after_toc(s)?;
sel_result(s)
}
/// Like Word, the caret lands in the paragraph right after the table, ready to keep typing — not
/// inside the table's own title or entries, where typing (or Enter) would corrupt them. When a
/// table (or nothing) follows, a paragraph is added there first, and the entries are rebuilt so
/// their page numbers count it.
fn caret_after_toc(s: &mut Session) -> Result<(), CmdError> {
if let Some((_, end)) = toc_range(s) {
let after = end + 1;
if !s.doc.body.get(after).is_some_and(|b| b.as_para().is_some()) {
s.doc.insert_block(StoryRef::Body, &Path::top(after), Block::Para(Paragraph::new()))?;
// Rebuilt as they now are (their leader and tabs), only the page numbers can change.
let tabs = cached_toc_tabs(s);
regenerate_toc(s, None, &tabs)?;
}
if let Some((_, end)) = toc_range(s) {
// Past the markers the paragraph starts with (a heading's `_Toc` bookmark, which its
// entry links to): Delete there takes the first character, not the bookmark.
let off = s.doc.body.get(end + 1).and_then(|b| b.as_para()).map_or(0, |p| {
let mut off = 0;
for (at, o) in p.objects_with_offsets() {
if at != off || !o.is_marker() {
break;
}
off += OBJ.len_utf8();
}
off
});
s.sel = Selection::caret(Pos { story: StoryRef::Body, path: Path::top(end + 1), off });
}
}
s.clamp_selection();
Ok(())
}
/// Replaces a TOC whose title sits above the section break its field's paragraph ends
/// (`title_above_break`): the field takes `v`'s settings, the title `v`'s `title` if one is given
/// (otherwise it is kept, as Word's Insert Table of Contents keeps it), and the entries are rebuilt.
+10 -1
View File
@@ -12,6 +12,7 @@ use crate::{CmdError, CmdResult, CommandSpec, Selection, Session, p};
mod changes;
mod comments;
mod proofing;
pub use proofing::thesaurus_word;
pub(crate) use changes::StyleTarget;
pub use changes::{
@@ -33,7 +34,9 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("review.editComment", "Edit Comment", "Review › Comments", edit_comment)
.params(r#"{"id": non-negative 32-bit JSON integer, "text": string}"#)
.when(comments_change),
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}"#),
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()))?;
@@ -59,6 +62,12 @@ pub fn specs() -> Vec<CommandSpec> {
.params(r#"{"next"?: bool (then select the next change)}"#),
CommandSpec::new("review.reject", "Reject", "Review › Changes", |s, v| resolve_sel_then(s, v, false))
.params(r#"{"next"?: bool (then select the next change)}"#),
CommandSpec::new("review.acceptAndNext", "Accept and Move to Next", "Review › Changes", |s, _| {
resolve_sel_then(s, &json!({"next": true}), true)
}),
CommandSpec::new("review.rejectAndNext", "Reject and Move to Next", "Review › Changes", |s, _| {
resolve_sel_then(s, &json!({"next": true}), false)
}),
CommandSpec::new("review.nextChange", "Next Change", "Review › Changes", |s, _| nav_change(s, 1)).pure(),
CommandSpec::new("review.previousChange", "Previous Change", "Review › Changes", |s, _| nav_change(s, -1)).pure(),
CommandSpec::new("review.markup", "Display for Review", "Review › Tracking", |s, v| {
+586 -6
View File
@@ -53,10 +53,11 @@ fn resolve_para(
}
// An inserted paragraph mark that is rejected, or a deleted one that is accepted, goes away:
// the next paragraph joins this one (the split is undone). A paragraph left empty goes away
// whole, so the next one keeps its own style and numbering, as in Word. The mark at the end
// of a story or cell can't go, so it just stops being a revision. An empty paragraph whose
// mark carries a section break goes whole too: its section joins the following one, as when
// the break is deleted (#5667). Joining instead gave the next paragraph its properties.
// whole, so the next one keeps its own style and numbering, as in Word. The end mark of a
// story or cell has no follower to join here; `resolve_all` removes the whole paragraph
// instead when one is left over (see `remove_trailing_para`). An empty paragraph whose mark
// carries a section break goes whole too: its section joins the following one, as when the
// break is deleted (#5667). Joining instead gave the next paragraph its properties.
if (del.is_some() && accept) || (ins.is_some() && !accept) {
let sectioned = story == StoryRef::Body
&& path.0.len() == 1
@@ -76,6 +77,23 @@ fn resolve_para(
Ok(())
}
/// Remove the whole paragraph at `path` when a whole-paragraph revision on its mark resolved to
/// removal and it is the last paragraph in its container and carries no section break: it goes
/// away, as long as the container keeps another paragraph (a story or cell must never end up
/// with none). `false`, changing nothing, otherwise.
fn remove_trailing_para(s: &mut Session, story: StoryRef, path: &wordcraft_doc::Path) -> Result<bool, CmdError> {
let Some(p) = s.doc.para(story, path) else { return Ok(false) };
if !p.is_empty() || p.section.is_some() {
return Ok(false);
}
let Some(container) = s.doc.container(story, path) else { return Ok(false) };
if container.iter().filter(|b| b.as_para().is_some()).count() <= 1 {
return Ok(false);
}
s.doc.remove_block(story, path)?;
Ok(true)
}
/// Accept or reject the changes of the table cell `path` is in: the table's, its row's and the
/// cell's own. Returns whether there were any.
fn resolve_cell(s: &mut Session, story: StoryRef, path: &wordcraft_doc::Path, accept: bool) -> Result<bool, CmdError> {
@@ -245,8 +263,16 @@ fn resolve_all(s: &mut Session, accept: bool) -> CmdResult {
let stories: Vec<StoryRef> = std::iter::once(StoryRef::Body).chain(s.doc.parts.keys().map(|k| StoryRef::Part(*k))).collect();
for st in stories {
for path in s.doc.para_paths(st).into_iter().rev() {
// A whole-paragraph mark that resolves to removal at the end of its container takes
// the paragraph with it (there is no follower for `resolve_para` to join). A paragraph
// followed by a table is not the end: removing it could make two tables adjacent.
let is_last = s.doc.block(st, &path.with_last(path.last().saturating_add(1))).is_none();
let trailing = is_last && s.doc.para(st, &path).is_some_and(|p| (p.mark.del.is_some() && accept) || (p.mark.ins.is_some() && !accept));
let len = s.doc.para(st, &path).map(|p| p.len()).unwrap_or(0);
resolve_para(s, st, &path, (0, len), (true, true), accept)?;
if trailing {
remove_trailing_para(s, st, &path)?;
}
}
}
// Tables, rows, cells, sections and style definitions.
@@ -267,11 +293,564 @@ fn resolve_all(s: &mut Session, accept: bool) -> CmdResult {
resolve_loose_blocks(blocks, accept)?;
}
}
s.doc.revisions.clear();
// Keep revision entries still referenced by surviving stories or metadata (e.g., Ruby or
// content-control run properties) and compact/remap the table; clear it directly when none
// survive.
retain_referenced_revisions(&mut s.doc);
s.clamp_selection();
sel_result(s)
}
fn lookup_rev(idx: u32, remap: &[Option<u32>]) -> Option<u32> {
remap.get(idx as usize).copied().flatten()
}
fn remap_opt_rev(slot: &mut Option<u32>, remap: &[Option<u32>]) -> bool {
let Some(old) = *slot else { return false };
let next = lookup_rev(old, remap);
if next != *slot {
*slot = next;
true
} else {
false
}
}
fn step_prop_change<'a, T>(
slot: &'a mut Option<Box<wordcraft_doc::props::PropChange<T>>>,
remap: &[Option<u32>],
changed: &mut bool,
) -> Option<&'a mut T> {
let old = slot.as_ref()?.rev;
let Some(new) = lookup_rev(old, remap) else {
*slot = None;
*changed = true;
return None;
};
let ch = slot.as_deref_mut()?;
if ch.rev != new {
ch.rev = new;
*changed = true;
}
Some(&mut ch.old)
}
fn collect_char(mut c: &wordcraft_doc::CharProps, f: &mut impl FnMut(u32) -> bool) {
loop {
if let Some(i) = c.ins {
f(i);
}
if let Some(i) = c.del {
f(i);
}
let Some(ch) = c.fmt_change.as_deref() else { break };
if !f(ch.rev) {
break;
}
c = &ch.old;
}
}
fn remap_char(mut c: &mut wordcraft_doc::CharProps, remap: &[Option<u32>]) -> bool {
let mut changed = false;
loop {
changed |= remap_opt_rev(&mut c.ins, remap);
changed |= remap_opt_rev(&mut c.del, remap);
let Some(old) = step_prop_change(&mut c.fmt_change, remap, &mut changed) else { break };
c = old;
}
changed
}
fn collect_para_props(mut p: &wordcraft_doc::ParaProps, f: &mut impl FnMut(u32) -> bool) {
loop {
if let Some(nc) = p.num_change.as_deref() {
f(nc.rev);
}
let Some(ch) = p.fmt_change.as_deref() else { break };
if !f(ch.rev) {
break;
}
p = &ch.old;
}
}
fn remap_para_props(mut p: &mut wordcraft_doc::ParaProps, remap: &[Option<u32>]) -> bool {
let mut changed = false;
loop {
if let Some(old) = p.num_change.as_deref().map(|nc| nc.rev) {
match lookup_rev(old, remap) {
Some(new) => {
if let Some(nc) = p.num_change.as_deref_mut()
&& nc.rev != new
{
nc.rev = new;
changed = true;
}
}
None => {
p.num_change = None;
changed = true;
}
}
}
let Some(old) = step_prop_change(&mut p.fmt_change, remap, &mut changed) else { break };
p = old;
}
changed
}
fn collect_section(mut s: &wordcraft_doc::SectionProps, f: &mut impl FnMut(u32) -> bool) {
while let Some(ch) = s.fmt_change.as_deref() {
if !f(ch.rev) {
break;
}
s = &ch.old;
}
}
fn remap_section(mut s: &mut wordcraft_doc::SectionProps, remap: &[Option<u32>]) -> bool {
let mut changed = false;
while let Some(old) = step_prop_change(&mut s.fmt_change, remap, &mut changed) {
s = old;
}
changed
}
fn collect_table_props(mut t: &wordcraft_doc::props::TableProps, f: &mut impl FnMut(u32) -> bool) {
while let Some(ch) = t.fmt_change.as_deref() {
if !f(ch.rev) {
break;
}
t = &ch.old;
}
}
fn remap_table_props(mut t: &mut wordcraft_doc::props::TableProps, remap: &[Option<u32>]) -> bool {
let mut changed = false;
while let Some(old) = step_prop_change(&mut t.fmt_change, remap, &mut changed) {
t = old;
}
changed
}
fn collect_row_props(mut r: &wordcraft_doc::props::RowProps, f: &mut impl FnMut(u32) -> bool) {
loop {
if let Some(ex) = r.exceptions.as_deref() {
collect_table_props(ex, f);
}
let Some(ch) = r.fmt_change.as_deref() else { break };
if !f(ch.rev) {
break;
}
r = &ch.old;
}
}
fn remap_row_props(mut r: &mut wordcraft_doc::props::RowProps, remap: &[Option<u32>]) -> bool {
let mut changed = false;
loop {
if let Some(ex) = r.exceptions.as_deref_mut() {
changed |= remap_table_props(ex, remap);
}
let Some(old) = step_prop_change(&mut r.fmt_change, remap, &mut changed) else { break };
r = old;
}
changed
}
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() {
if !f(ch.rev) {
break;
}
c = &ch.old;
}
}
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) {
c = old;
}
changed
}
fn collect_leaf_object(obj: &InlineObject, f: &mut impl FnMut(u32) -> bool) {
match obj {
InlineObject::Ruby { props, .. } => collect_char(props, f),
InlineObject::ControlStart { control } => {
if let Some(rp) = &control.run_props {
collect_char(rp, f);
}
}
_ => {}
}
}
fn collect_object(obj: &InlineObject, f: &mut impl FnMut(u32) -> bool) {
let InlineObject::Group { children, .. } = obj else {
collect_leaf_object(obj, f);
return;
};
let mut stack = Vec::new();
let mut cur = children.as_slice();
loop {
for ch in cur {
match &ch.obj {
InlineObject::Group { children: inner, .. } => {
if !inner.is_empty() {
stack.push(inner.as_slice());
}
}
other => collect_leaf_object(other, f),
}
}
let Some(next) = stack.pop() else { break };
cur = next;
}
}
fn remap_leaf_object(obj: &mut InlineObject, remap: &[Option<u32>]) -> bool {
match obj {
InlineObject::Ruby { props, .. } => remap_char(props, remap),
InlineObject::ControlStart { control } => control.run_props.as_mut().is_some_and(|rp| remap_char(rp, remap)),
_ => false,
}
}
fn remap_object(obj: &mut InlineObject, remap: &[Option<u32>]) -> bool {
let InlineObject::Group { children, .. } = obj else {
return remap_leaf_object(obj, remap);
};
let mut changed = false;
let mut stack = Vec::new();
let mut cur = children.as_mut_slice();
loop {
for ch in cur {
match &mut ch.obj {
InlineObject::Group { children: inner, .. } => {
if !inner.is_empty() {
stack.push(inner.as_mut_slice());
}
}
other => changed |= remap_leaf_object(other, remap),
}
}
let Some(next) = stack.pop() else { break };
cur = next;
}
changed
}
fn collect_controls(wrap: &wordcraft_doc::ControlWrap, f: &mut impl FnMut(u32) -> bool) {
for c in &wrap.open {
if let Some(rp) = &c.run_props {
collect_char(rp, f);
}
}
}
fn remap_controls(wrap: &mut wordcraft_doc::ControlWrap, remap: &[Option<u32>]) -> bool {
let mut changed = false;
for c in &mut wrap.open {
if let Some(rp) = &mut c.run_props {
changed |= remap_char(rp, remap);
}
}
changed
}
fn collect_para(p: &Paragraph, f: &mut impl FnMut(u32) -> bool) {
collect_para_props(&p.props, f);
for r in &p.runs {
collect_char(&r.props, f);
}
collect_char(&p.mark, f);
if let Some(sec) = p.section.as_deref() {
collect_section(sec, f);
}
for obj in &p.objects {
collect_object(obj, f);
}
}
fn collect_table(table: &wordcraft_doc::table::Table, f: &mut impl FnMut(u32) -> bool) {
let mut stack = Vec::new();
let mut cur = table;
loop {
collect_table_props(&cur.props, f);
collect_controls(&cur.controls, f);
for row in &cur.rows {
collect_row_props(&row.props, f);
collect_controls(&row.controls, f);
for cell in &row.cells {
collect_cell_props(&cell.props, f);
collect_controls(&cell.controls, f);
for b in &cell.blocks {
match b.as_ref() {
wordcraft_doc::Block::Para(p) => collect_para(p, f),
wordcraft_doc::Block::Table(nested) => stack.push(nested),
}
}
}
}
let Some(next) = stack.pop() else { break };
cur = next;
}
}
fn collect_block(block: &wordcraft_doc::Block, f: &mut impl FnMut(u32) -> bool) {
match block {
wordcraft_doc::Block::Para(p) => collect_para(p, f),
wordcraft_doc::Block::Table(t) => collect_table(t, f),
}
}
fn collect_blocks(blocks: &wordcraft_doc::Blocks, f: &mut impl FnMut(u32) -> bool) {
for b in blocks {
collect_block(b, f);
}
}
fn block_needs_rewrite(block: &wordcraft_doc::Block, remap: &[Option<u32>]) -> bool {
let mut needs = false;
collect_block(block, &mut |idx| {
let next = lookup_rev(idx, remap);
if next != Some(idx) {
needs = true;
}
next.is_some()
});
needs
}
fn remap_blocks(blocks: &mut wordcraft_doc::Blocks, remap: &[Option<u32>]) {
let mut stack: Vec<&mut std::sync::Arc<wordcraft_doc::Block>> = blocks.iter_mut().collect();
while let Some(arc_b) = stack.pop() {
if !block_needs_rewrite(arc_b, remap) {
continue;
}
match std::sync::Arc::make_mut(arc_b) {
wordcraft_doc::Block::Para(p) => {
let mut changed = remap_para_props(&mut p.props, remap);
for r in &mut p.runs {
changed |= remap_char(&mut r.props, remap);
}
changed |= remap_char(&mut p.mark, remap);
if let Some(sec) = p.section.as_deref_mut() {
changed |= remap_section(sec, remap);
}
for obj in &mut p.objects {
changed |= remap_object(obj, remap);
}
if changed {
p.touch();
}
}
wordcraft_doc::Block::Table(t) => {
remap_table_props(&mut t.props, remap);
remap_controls(&mut t.controls, remap);
for row in &mut t.rows {
remap_row_props(&mut row.props, remap);
remap_controls(&mut row.controls, remap);
for cell in &mut row.cells {
remap_cell_props(&mut cell.props, remap);
remap_controls(&mut cell.controls, remap);
stack.extend(cell.blocks.iter_mut());
}
}
}
}
}
}
fn collect_styles(styles: &wordcraft_doc::styles::StyleSheet, f: &mut impl FnMut(u32) -> bool) {
collect_char(&styles.default_chr, f);
collect_para_props(&styles.default_para, f);
for st in &styles.styles {
collect_para_props(&st.para, f);
collect_char(&st.chr, f);
if let Some(ch) = st.para_change.as_deref()
&& f(ch.rev)
{
collect_para_props(&ch.old, f);
}
if let Some(ch) = st.chr_change.as_deref()
&& f(ch.rev)
{
collect_char(&ch.old, f);
}
if let Some(tbl) = &st.table {
for c in [&tbl.header_chr, &tbl.band_chr, &tbl.first_col_chr, &tbl.total_chr, &tbl.last_col_chr, &tbl.col_band_chr] {
collect_char(c, f);
}
for pf in tbl.regions.values() {
collect_char(&pf.chr, f);
}
}
}
}
fn remap_styles(styles: &mut std::sync::Arc<wordcraft_doc::styles::StyleSheet>, remap: &[Option<u32>]) {
let mut needs = false;
collect_styles(styles, &mut |idx| {
let next = lookup_rev(idx, remap);
if next != Some(idx) {
needs = true;
}
next.is_some()
});
if !needs {
return;
}
let styles = std::sync::Arc::make_mut(styles);
remap_char(&mut styles.default_chr, remap);
remap_para_props(&mut styles.default_para, remap);
for st in &mut styles.styles {
remap_para_props(&mut st.para, remap);
remap_char(&mut st.chr, remap);
let mut dummy = false;
if let Some(old) = step_prop_change(&mut st.para_change, remap, &mut dummy) {
remap_para_props(old, remap);
}
if let Some(old) = step_prop_change(&mut st.chr_change, remap, &mut dummy) {
remap_char(old, remap);
}
if let Some(tbl) = &mut st.table {
for c in
[&mut tbl.header_chr, &mut tbl.band_chr, &mut tbl.first_col_chr, &mut tbl.total_chr, &mut tbl.last_col_chr, &mut tbl.col_band_chr]
{
remap_char(c, remap);
}
for pf in tbl.regions.values_mut() {
remap_char(&mut pf.chr, remap);
}
}
}
}
fn collect_numbering(numbering: &wordcraft_doc::numbering::Numbering, f: &mut impl FnMut(u32) -> bool) {
for abs in &numbering.abstracts {
for lvl in &abs.levels {
collect_char(&lvl.chr, f);
}
}
for num in &numbering.nums {
for (_, lvl) in &num.level_overrides {
collect_char(&lvl.chr, f);
}
}
}
fn remap_numbering(numbering: &mut std::sync::Arc<wordcraft_doc::numbering::Numbering>, remap: &[Option<u32>]) {
let mut needs = false;
collect_numbering(numbering, &mut |idx| {
let next = lookup_rev(idx, remap);
if next != Some(idx) {
needs = true;
}
next.is_some()
});
if !needs {
return;
}
let numbering = std::sync::Arc::make_mut(numbering);
for abs in &mut numbering.abstracts {
for lvl in &mut abs.levels {
remap_char(&mut lvl.chr, remap);
}
}
for num in &mut numbering.nums {
for (_, lvl) in &mut num.level_overrides {
remap_char(&mut lvl.chr, remap);
}
}
}
fn collect_doc_revisions(doc: &wordcraft_doc::Document, f: &mut impl FnMut(u32) -> bool) {
collect_blocks(&doc.body, f);
collect_section(&doc.last_section, f);
for part in doc.parts.values() {
collect_blocks(&part.blocks, f);
}
for sep in [&doc.footnote_separators, &doc.endnote_separators] {
for blocks in [&sep.separator, &sep.continuation_separator, &sep.continuation_notice].into_iter().flatten() {
collect_blocks(blocks, f);
}
}
for bb in &doc.glossary {
collect_blocks(&bb.blocks, f);
}
collect_styles(&doc.styles, f);
collect_numbering(&doc.numbering, f);
}
fn rewrite_doc_revisions(doc: &mut wordcraft_doc::Document, remap: &[Option<u32>]) {
remap_blocks(&mut doc.body, remap);
remap_section(&mut doc.last_section, remap);
for part in doc.parts.values_mut() {
remap_blocks(&mut part.blocks, remap);
}
for sep in [&mut doc.footnote_separators, &mut doc.endnote_separators] {
for blocks in [&mut sep.separator, &mut sep.continuation_separator, &mut sep.continuation_notice].into_iter().flatten() {
remap_blocks(blocks, remap);
}
}
for bb in &mut doc.glossary {
remap_blocks(&mut bb.blocks, remap);
}
remap_styles(&mut doc.styles, remap);
remap_numbering(&mut doc.numbering, remap);
}
/// Retain only revision entries still referenced by `doc`, compacting `doc.revisions` and remapping
/// surviving references (or clearing invalid out-of-bounds ones). On the common path with no
/// surviving references, the walk avoids heap allocation for paragraphs, non-nested tables, and
/// non-nested inline objects (an iterative stack allocates only for tables inside tables or groups
/// inside groups), `BTreeSet::new()` never allocates, and `doc.revisions.clear()` runs directly
/// without allocating `remap`/`kept` or running the rewrite pass.
fn retain_referenced_revisions(doc: &mut wordcraft_doc::Document) {
let old_len = doc.revisions.len();
let mut used = std::collections::BTreeSet::new();
let mut has_invalid = false;
// The callback returns whether the visited index is valid; PropChange walkers stop descending
// into `ch.old` when an outer `ch.rev` is out of bounds because `step_prop_change` discards the
// whole outer PropChange (including any nested indices buried inside it). That keeps the table
// at its exact fixed point in a single pass.
collect_doc_revisions(doc, &mut |idx| {
if (idx as usize) < old_len {
used.insert(idx);
true
} else {
has_invalid = true;
false
}
});
if used.is_empty() && !has_invalid {
doc.revisions.clear();
return;
}
if !has_invalid && used.len() == old_len {
return;
}
let mut remap = vec![None; old_len];
let mut kept = Vec::with_capacity(used.len());
let mut needs_rewrite = has_invalid;
for old in used {
let new = kept.len() as u32;
remap[old as usize] = Some(new);
if new != old {
needs_rewrite = true;
}
kept.push(doc.revisions[old as usize].clone());
}
doc.revisions = kept;
if needs_rewrite {
rewrite_doc_revisions(doc, &remap);
}
}
/// Accept or Reject All; with `stopTracking`, Track Changes is turned off as well.
pub(super) fn resolve_all_then(s: &mut Session, v: &Value, accept: bool) -> CmdResult {
let out = resolve_all(s, accept)?;
@@ -608,10 +1187,11 @@ pub(super) fn list_changes(s: &mut Session, _: &Value) -> CmdResult {
list.iter()
.map(|c| {
let rev = c.rev.and_then(|r| s.doc.revisions.get(r as usize));
// The date in UTC when it is known; a file's `w:date` without it is as read.
let mut v = json!({
"kind": c.kind, "start": pos_json(&c.a), "end": pos_json(&c.b),
"text": s.doc.copy_range(&c.a, &c.b).plain_text(),
"author": rev.map(|r| r.author.clone()), "date": rev.map(|r| r.date.clone()),
"author": rev.map(|r| r.author.clone()), "date": rev.map(|r| r.instant().to_string()),
});
if c.kind == "format" {
v["description"] = json!(fmt_revisions::describe(&c.props));
+11 -7
View File
@@ -163,17 +163,17 @@ fn remove_anchors(s: &mut Session, ids: &BTreeSet<u32>) -> Result<(), CmdError>
Ok(())
}
/// The comment and every reply below it, replies to replies included (#1345). A parent cycle
/// from a hostile file ends the walk instead of looping.
fn thread_of(s: &Session, id: u32) -> Vec<u32> {
/// The comments and every reply below them, replies to replies included (#1345), each once. A
/// parent cycle from a hostile file ends the walk instead of looping.
fn threads_of(s: &Session, roots: impl IntoIterator<Item = u32>) -> Vec<u32> {
let mut children: BTreeMap<u32, Vec<u32>> = BTreeMap::new();
for (k, c) in &s.doc.comments {
if let Some(parent) = c.parent {
children.entry(parent).or_default().push(*k);
}
}
let mut seen = BTreeSet::from([id]);
let mut ids = vec![id];
let mut seen = BTreeSet::new();
let mut ids: Vec<u32> = roots.into_iter().filter(|id| seen.insert(*id)).collect();
let mut i = 0;
while let Some(&at) = ids.get(i) {
for k in children.get(&at).into_iter().flatten() {
@@ -188,11 +188,15 @@ fn thread_of(s: &Session, id: u32) -> Vec<u32> {
pub(super) fn delete_comment(s: &mut Session, v: &Value) -> CmdResult {
validate_comment_id(v)?;
let ids: Vec<u32> = if p::bool(v, "all").unwrap_or(false) {
let ids: Vec<u32> = if p::bool(v, "resolved").unwrap_or(false) {
// Delete All Resolved Comments (#7818): each resolved comment goes with its replies.
let resolved: Vec<u32> = s.doc.comments.iter().filter(|(_, c)| c.resolved).map(|(k, _)| *k).collect();
threads_of(s, resolved)
} else if p::bool(v, "all").unwrap_or(false) {
s.doc.comments.keys().copied().collect()
} else {
let id = p::u64(v, "id").map(|x| x as u32).or_else(|| comment_at_caret(s)).ok_or_else(|| CmdError::Params("no comment here".into()))?;
thread_of(s, id)
threads_of(s, [id])
};
remove_anchors(s, &ids.iter().copied().collect())?;
for id in &ids {
+16 -4
View File
@@ -128,6 +128,20 @@ pub(super) fn suggestions(s: &mut Session, v: &Value) -> CmdResult {
}
}
/// The word at the caret that the thesaurus looks up and a chosen synonym replaces: the word unit
/// without the spaces after it or the quotes around it, so `‘good’` is `good` and its quotes stay
/// when it is replaced; an apostrophe inside a word (`don’t`) is kept (#6517).
pub fn thesaurus_word(s: &Session) -> Option<(Pos, Pos)> {
let f = &s.sel.focus;
let p = s.doc.para_at(f)?;
let (a, b) = p.word_at(f.off);
let w = p.text.get(a..b)?;
let edge = |c: char| c.is_whitespace() || matches!(c, '’' | '‘' | '\'');
let start = a + (w.len() - w.trim_start_matches(edge).len());
let end = (a + w.trim_end_matches(edge).len()).max(start);
Some((Pos { off: start, ..f.clone() }, Pos { off: end, ..f.clone() }))
}
/// A tiny built-in thesaurus of common words (our own list).
pub(super) fn thesaurus(s: &mut Session, v: &Value) -> CmdResult {
const T: &[(&str, &[&str])] = &[
@@ -164,10 +178,8 @@ pub(super) fn thesaurus(s: &mut Session, v: &Value) -> CmdResult {
let word = match p::str(v, "word") {
Some(w) => w.to_lowercase(),
None => {
let f = s.sel.focus.clone();
let p = s.doc.para_at(&f).ok_or_else(|| CmdError::Failed("no word".into()))?;
let (a, b) = p.word_at(f.off);
p.text.get(a..b).unwrap_or("").trim().to_lowercase()
let (a, b) = thesaurus_word(s).ok_or_else(|| CmdError::Failed("no word".into()))?;
s.doc.para_at(&a).and_then(|p| p.text.get(a.off..b.off)).unwrap_or("").to_lowercase()
}
};
let syn = T.iter().find(|(w, _)| *w == word).map(|(_, l)| l.to_vec()).unwrap_or_default();
+745 -1
View File
@@ -549,6 +549,135 @@ fn selected(s: &Session) -> (usize, usize) {
(a.off, b.off)
}
/// Two edits an hour apart in the repeated hour as daylight saving time ends are two changes,
/// though both were made at 01:30 local time: each keeps its UTC time (#6851). Rejecting one at
/// the caret leaves the other pending. Saved as DOCX or Word XML, both are dated 01:30, as Word
/// dates them, with their UTC times beside it (`w16du:dateUtc`), so they reopen as two changes,
/// and a second save writes them as read.
#[test]
fn edits_in_the_repeated_hour_stay_separate_changes() {
use crate::cmd::{TEST_NOW, TEST_ZONE};
struct Reset;
impl Drop for Reset {
fn drop(&mut self) {
TEST_NOW.with(|c| c.set(None));
TEST_ZONE.with(|z| z.set(None));
}
}
let _reset = Reset;
TEST_ZONE.with(|z| z.set(Some(crate::io_ext::tests::new_york)));
let mut s = Session::new(Document::new());
s.view.proofing = false;
s.run("document.setText", &json!({"text": "Draft."})).unwrap();
s.run("review.trackChanges", &json!({"value": true})).unwrap();
s.run("caret.docEnd", &json!({})).unwrap();
// 1 November 2026, 01:30 EDT (05:30 UTC) and then 01:30 EST (06:30 UTC).
for (now, text) in [(1_793_511_000, " One"), (1_793_514_600, " Two")] {
TEST_NOW.with(|c| c.set(Some(now)));
s.run("text.insert", &json!({"text": text})).unwrap();
}
assert_eq!(change_spans(&mut s), [("insert".into(), 6, 10), ("insert".into(), 10, 14)]);
let utc = ["2026-11-01T05:30:00Z", "2026-11-01T06:30:00Z"];
let instants = |d: &Document| d.revisions.iter().map(|r| r.instant().to_string()).collect::<Vec<_>>();
assert_eq!(instants(&s.doc), utc);
let listed = s.run("review.changes", &json!({})).unwrap();
assert_eq!(listed.as_array().map(|l| l.iter().map(|c| c["date"].clone()).collect::<Vec<_>>()), Some(vec![json!(utc[0]), json!(utc[1])]));
let local = |d: &Document| d.revisions.iter().map(|r| r.date.clone()).collect::<Vec<_>>();
for name in ["repeated.docx", "repeated.xml"] {
let bytes = crate::io::save_bytes(name, &s.doc).unwrap();
let read = |bytes: &[u8]| if name.ends_with(".xml") { wordcraft_docx::read_xml(bytes) } else { wordcraft_docx::read(bytes) }.unwrap();
let written = read(&bytes);
assert_eq!(local(&written), ["2026-11-01T01:30:00Z"; 2], "{name}");
assert_eq!(instants(&written), utc, "{name}");
let mut opened = Session::new(crate::io::open_bytes(name, &bytes).unwrap());
opened.view.proofing = false;
assert_eq!(change_spans(&mut opened), [("insert".into(), 6, 10), ("insert".into(), 10, 14)], "{name}");
// Saved again, the changes are written as read: their local time doesn't move.
let again = read(&crate::io::save_bytes(name, &opened.doc).unwrap());
assert_eq!((local(&again), instants(&again)), (local(&written), instants(&written)), "{name}");
opened.run("caret.set", &json!({"pos": {"block": 0, "off": 12}})).unwrap();
opened.run("review.reject", &json!({})).unwrap();
assert_eq!(opened.doc.plain_text(wordcraft_doc::StoryRef::Body), "Draft. One", "{name}");
assert_eq!(change_spans(&mut opened), [("insert".into(), 6, 10)], "{name}: the earlier insertion is still pending");
}
assert_eq!(instants(&s.doc), utc, "saving leaves the session's changes as they were");
s.run("caret.set", &json!({"pos": {"block": 0, "off": 12}})).unwrap();
s.run("review.reject", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(wordcraft_doc::StoryRef::Body), "Draft. One");
assert_eq!(change_spans(&mut s), [("insert".into(), 6, 10)], "the earlier insertion is still pending");
}
/// A change made at 08:33 UTC at UTC+8 is dated 16:33 in a Word file, as Word dates it, and 08:33
/// UTC in an OpenDocument file, whose `dc:date` is an instant (#6851).
#[test]
fn a_new_change_is_dated_in_utc_in_opendocument() {
use crate::cmd::{TEST_NOW, TEST_ZONE};
struct Reset;
impl Drop for Reset {
fn drop(&mut self) {
TEST_NOW.with(|c| c.set(None));
TEST_ZONE.with(|z| z.set(None));
}
}
let _reset = Reset;
TEST_ZONE.with(|z| z.set(Some(|_| 8 * 3600)));
TEST_NOW.with(|c| c.set(Some(1_794_818_004)));
let mut s = Session::new(Document::new());
s.view.proofing = false;
s.run("document.setText", &json!({"text": "Draft."})).unwrap();
s.run("review.trackChanges", &json!({"value": true})).unwrap();
s.run("caret.docEnd", &json!({})).unwrap();
s.run("text.insert", &json!({"text": " One"})).unwrap();
let utc = "2026-11-16T08:33:24Z";
let dates = |d: &Document| d.revisions.iter().map(|r| r.date.clone()).collect::<Vec<_>>();
for (name, date) in [("new.odt", utc), ("new.fodt", utc), ("new.docx", "2026-11-16T16:33:24Z"), ("new.xml", "2026-11-16T16:33:24Z")] {
let opened = crate::io::open_bytes(name, &crate::io::save_bytes(name, &s.doc).unwrap()).unwrap();
assert_eq!(dates(&opened), [date], "{name}");
assert!(opened.revisions.iter().all(|r| r.instant() == utc), "{name}: {:?}", opened.revisions);
}
}
/// A tracked change read from a file keeps its `w:date` and `w16du:dateUtc` as read through open
/// and save in another zone (#6851): one without a UTC time (an older Word, another program), whose
/// zone WordCraft doesn't guess, and one written in UTC, where the two are the same.
#[test]
fn a_file_date_is_written_as_read() {
use crate::cmd::TEST_ZONE;
struct Reset;
impl Drop for Reset {
fn drop(&mut self) {
TEST_ZONE.with(|z| z.set(None));
}
}
let _reset = Reset;
TEST_ZONE.with(|z| z.set(Some(|_| 8 * 3600)));
let date = "2026-11-16T08:33:24Z";
for utc in [None, Some(date)] {
let mut doc = Document::from_text("Draft.");
let mut rev = wordcraft_doc::Revision::new(wordcraft_doc::RevisionKind::Insert, "Ada", date);
rev.date_utc = utc.map(String::from);
doc.revisions.push(rev);
doc.para_mut(wordcraft_doc::StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap().mark.ins = Some(0);
let dates = |d: &Document| d.revisions.iter().map(|r| (r.date.clone(), r.date_utc.clone())).collect::<Vec<_>>();
let want = vec![(date.to_string(), utc.map(String::from))];
for name in ["file.docx", "file.xml"] {
let bytes = crate::io::save_bytes(name, &doc).unwrap();
let opened = crate::io::open_bytes(name, &bytes).unwrap();
assert_eq!(dates(&opened), want, "{name} {utc:?}: opened");
let saved = crate::io::save_bytes(name, &opened).unwrap();
let again = if name.ends_with(".xml") { wordcraft_docx::read_xml(&saved) } else { wordcraft_docx::read(&saved) }.unwrap();
assert_eq!(dates(&again), want, "{name} {utc:?}: saved again");
}
}
}
/// Accept and Move to Next, Reject and Move to Next: the change at the caret is resolved and
/// the next one is selected; without `next` the caret stays where the change was.
#[test]
@@ -574,6 +703,20 @@ fn accept_and_reject_can_move_to_the_next_change() {
}
}
#[test]
fn review_shortcut_commands_resolve_and_select_the_next_change_without_parameters() {
for (command, accept) in [("review.acceptAndNext", true), ("review.rejectAndNext", false)] {
let mut s = three_changes();
s.run("caret.docStart", &json!({})).unwrap();
s.run(command, &serde_json::Value::Null).unwrap();
let remaining = change_spans(&mut s);
assert_eq!(remaining.iter().map(|change| change.0.as_str()).collect::<Vec<_>>(), ["delete", "insert"], "{command}");
let (_, start, end) = remaining[0];
assert_eq!(selected(&s), (start as usize, end as usize), "{command}: the deletion is selected next");
assert_eq!(s.doc.plain_text(wordcraft_doc::StoryRef::Body).starts_with("new "), accept, "{command}");
}
}
/// With the caret on no change, Accept and Move to Next selects the next change without
/// resolving it, as Accept and Next Change do.
#[test]
@@ -796,6 +939,77 @@ fn deleting_a_comment_in_a_parent_cycle_ends() {
assert!(s.doc.comments.is_empty());
}
/// Comments on "one", "two" and "three" with a reply on the first; the ids, in that order.
fn three_commented_words(s: &mut Session) -> [u64; 4] {
s.view.proofing = false;
s.run("document.setText", &json!({"text": "one two three"})).unwrap();
let on = |s: &mut Session, word: &str| {
s.run("select.text", &json!({"text": word})).unwrap();
s.run("review.newComment", &json!({"text": word})).unwrap()["id"].as_u64().unwrap()
};
let (one, two, three) = (on(s, "one"), on(s, "two"), on(s, "three"));
let reply = s.run("review.reply", &json!({"id": one, "text": "reply"})).unwrap()["id"].as_u64().unwrap();
[one, reply, two, three]
}
/// #7818: Review › Delete › Delete All Resolved Comments deletes each resolved comment with its
/// replies and their text, and keeps the open ones with their anchors; Undo brings them back.
#[test]
fn delete_all_resolved_comments_keeps_the_open_ones() {
let mut s = Session::new(Document::new());
let [one, reply, two, three] = three_commented_words(&mut s);
for id in [one, three] {
s.run("review.resolveComment", &json!({"id": id, "value": true})).unwrap();
}
let part = |s: &Session, id: u64| s.doc.comments[&(id as u32)].part;
let kept_part = part(&s, two);
let gone_parts: Vec<u32> = [one, reply, three].iter().map(|id| part(&s, *id)).collect();
// The caret sits in the open comment, which Delete alone would take.
s.run("select.text", &json!({"text": "two"})).unwrap();
let depth = s.undo_depth();
let out = s.run("review.deleteComment", &json!({"resolved": true})).unwrap();
let mut deleted: Vec<u64> = out["deleted"].as_array().unwrap().iter().filter_map(|v| v.as_u64()).collect();
let mut want = vec![one, reply, three];
deleted.sort_unstable();
want.sort_unstable();
assert_eq!(deleted, want, "the resolved comments and the reply below one of them");
assert_eq!(s.doc.comments.keys().map(|k| u64::from(*k)).collect::<Vec<_>>(), vec![two], "the open comment stays");
assert!(s.doc.parts.contains_key(&kept_part));
assert!(gone_parts.iter().all(|p| !s.doc.parts.contains_key(p)), "the deleted comments' text parts are gone");
assert_eq!(anchors(&s), vec![(wordcraft_doc::StoryRef::Body, two as u32); 2], "only the open comment's anchors are left");
assert_eq!(s.undo_depth(), depth + 1, "one undo step");
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc.comments.len(), 4);
assert_eq!(anchors(&s).len(), 6);
}
/// #7818: with nothing resolved, Delete All Resolved Comments leaves every comment.
#[test]
fn delete_all_resolved_comments_without_resolved_ones_keeps_all() {
let mut s = Session::new(Document::new());
three_commented_words(&mut s);
let out = s.run("review.deleteComment", &json!({"resolved": true})).unwrap();
assert_eq!(out["deleted"], json!([]));
assert_eq!(s.doc.comments.len(), 4);
assert_eq!(anchors(&s).len(), 6);
}
/// #7818: Review › Delete › Delete All Comments in Document deletes every comment, reply and
/// anchor, resolved or not.
#[test]
fn delete_all_comments_in_document_deletes_every_comment() {
let mut s = Session::new(Document::new());
let [one, ..] = three_commented_words(&mut s);
s.run("review.resolveComment", &json!({"id": one, "value": true})).unwrap();
s.run("review.deleteComment", &json!({"all": true})).unwrap();
assert!(s.doc.comments.is_empty());
assert!(s.doc.parts.is_empty(), "no comment text is left: {:?}", s.doc.parts.keys());
assert!(anchors(&s).is_empty());
}
/// A very long reply chain (as a hostile file could hold) is deleted in one pass over the
/// comments, not one pass per reply: 50,000 replies would otherwise freeze the app.
#[test]
@@ -1048,7 +1262,7 @@ fn rtf_tracked_changes_accept_and_reject_after_opening_and_round_trip() {
let rtf: &[u8] = br"{\rtf1\ansi\deff0{\fonttbl{\f0 Arial;}}{\*\revtbl {Unknown;}{Alice;}{Bob;}}
\pard Keep {\revised\revauth1\revdttm-1480361314 added }text{\deleted\revauthdel2\revdttmdel-2016341499 gone} end{\revised\revauth1\revdttm-1480361314\deleted\revauthdel2\revdttmdel-2016341499 both}.\par}";
let opened = wordcraft_formats::rtf::import(rtf).unwrap();
let again = wordcraft_formats::rtf::import(wordcraft_formats::rtf::export(&opened).as_bytes()).unwrap();
let again = wordcraft_formats::rtf::import(wordcraft_formats::rtf::export(&opened).unwrap().as_bytes()).unwrap();
for doc in [opened, again] {
for (cmd, want) in [("review.acceptAll", "Keep added text end."), ("review.rejectAll", "Keep text gone end.")] {
let mut s = Session::new(doc.clone());
@@ -1206,3 +1420,533 @@ fn preexisting_table_with_redlined_cell_content_preserves_table_shell() {
assert!(s_rt.run("review.changes", &json!({})).unwrap().as_array().unwrap().is_empty());
}
}
/// Collect every revision reference `(location, idx, expected_kind)` surviving anywhere in `doc`
/// and assert that each resolves to an existing entry in `doc.revisions` of the expected kind.
fn assert_all_revision_refs_valid(doc: &Document, label: &str) -> usize {
use wordcraft_doc::{
Block, Blocks, CharProps, InlineObject, ParaProps, RevisionKind, SectionProps,
props::{CellProps, RowProps, TableProps},
};
fn check_idx(doc: &Document, label: &str, loc: &str, idx: u32, expected: RevisionKind, count: &mut usize) {
*count += 1;
let rev = doc.revisions.get(idx as usize).unwrap_or_else(|| {
panic!("{label}: dangling revision index {idx} at {loc} (revisions.len() == {})", doc.revisions.len());
});
assert_eq!(rev.kind, expected, "{label}: revision index {idx} at {loc} has kind {:?}, expected {expected:?}", rev.kind);
}
fn walk_char(doc: &Document, label: &str, loc: &str, c: &CharProps, count: &mut usize) {
if let Some(i) = c.ins {
check_idx(doc, label, &format!("{loc}.ins"), i, RevisionKind::Insert, count);
}
if let Some(i) = c.del {
check_idx(doc, label, &format!("{loc}.del"), i, RevisionKind::Delete, count);
}
if let Some(ch) = &c.fmt_change {
check_idx(doc, label, &format!("{loc}.fmt_change"), ch.rev, RevisionKind::Format, count);
walk_char(doc, label, &format!("{loc}.fmt_change.old"), &ch.old, count);
}
}
fn walk_para_props(doc: &Document, label: &str, loc: &str, p: &ParaProps, count: &mut usize) {
if let Some(nc) = &p.num_change {
check_idx(doc, label, &format!("{loc}.num_change"), nc.rev, RevisionKind::Format, count);
}
if let Some(ch) = &p.fmt_change {
check_idx(doc, label, &format!("{loc}.fmt_change"), ch.rev, RevisionKind::Format, count);
walk_para_props(doc, label, &format!("{loc}.fmt_change.old"), &ch.old, count);
}
}
fn walk_section(doc: &Document, label: &str, loc: &str, s: &SectionProps, count: &mut usize) {
if let Some(ch) = &s.fmt_change {
check_idx(doc, label, &format!("{loc}.fmt_change"), ch.rev, RevisionKind::Format, count);
walk_section(doc, label, &format!("{loc}.fmt_change.old"), &ch.old, count);
}
}
fn walk_table_props(doc: &Document, label: &str, loc: &str, t: &TableProps, count: &mut usize) {
if let Some(ch) = &t.fmt_change {
check_idx(doc, label, &format!("{loc}.fmt_change"), ch.rev, RevisionKind::Format, count);
walk_table_props(doc, label, &format!("{loc}.fmt_change.old"), &ch.old, count);
}
}
fn walk_row_props(doc: &Document, label: &str, loc: &str, r: &RowProps, count: &mut usize) {
if let Some(ex) = r.exceptions.as_deref() {
walk_table_props(doc, label, &format!("{loc}.exceptions"), ex, count);
}
if let Some(ch) = &r.fmt_change {
check_idx(doc, label, &format!("{loc}.fmt_change"), ch.rev, RevisionKind::Format, count);
walk_row_props(doc, label, &format!("{loc}.fmt_change.old"), &ch.old, count);
}
}
fn walk_cell_props(doc: &Document, label: &str, loc: &str, c: &CellProps, count: &mut usize) {
if let Some(ch) = &c.fmt_change {
check_idx(doc, label, &format!("{loc}.fmt_change"), ch.rev, RevisionKind::Format, count);
walk_cell_props(doc, label, &format!("{loc}.fmt_change.old"), &ch.old, count);
}
}
fn walk_object(doc: &Document, label: &str, loc: &str, obj: &InlineObject, count: &mut usize) {
match obj {
InlineObject::Ruby { props, .. } => walk_char(doc, label, &format!("{loc}.ruby.props"), props, count),
InlineObject::ControlStart { control } => {
if let Some(rp) = &control.run_props {
walk_char(doc, label, &format!("{loc}.control.run_props"), rp, count);
}
}
InlineObject::Group { children, .. } => {
for (i, ch) in children.iter().enumerate() {
walk_object(doc, label, &format!("{loc}.group[{i}]"), &ch.obj, count);
}
}
_ => {}
}
}
fn walk_blocks(doc: &Document, label: &str, loc: &str, blocks: &Blocks, count: &mut usize) {
for (bi, b) in blocks.iter().enumerate() {
match &**b {
Block::Para(p) => {
let ploc = format!("{loc}[{bi}]");
walk_para_props(doc, label, &format!("{ploc}.props"), &p.props, count);
for (ri, r) in p.runs.iter().enumerate() {
walk_char(doc, label, &format!("{ploc}.runs[{ri}]"), &r.props, count);
}
walk_char(doc, label, &format!("{ploc}.mark"), &p.mark, count);
if let Some(sec) = p.section.as_deref() {
walk_section(doc, label, &format!("{ploc}.section"), sec, count);
}
for (oi, obj) in p.objects.iter().enumerate() {
walk_object(doc, label, &format!("{ploc}.objects[{oi}]"), obj, count);
}
}
Block::Table(t) => {
let tloc = format!("{loc}[{bi}]");
walk_table_props(doc, label, &format!("{tloc}.props"), &t.props, count);
for (ci, ctl) in t.controls.open.iter().enumerate() {
if let Some(rp) = &ctl.run_props {
walk_char(doc, label, &format!("{tloc}.controls[{ci}].run_props"), rp, count);
}
}
for (ri, row) in t.rows.iter().enumerate() {
walk_row_props(doc, label, &format!("{tloc}.rows[{ri}].props"), &row.props, count);
for (ci, ctl) in row.controls.open.iter().enumerate() {
if let Some(rp) = &ctl.run_props {
walk_char(doc, label, &format!("{tloc}.rows[{ri}].controls[{ci}].run_props"), rp, count);
}
}
for (ci, cell) in row.cells.iter().enumerate() {
walk_cell_props(doc, label, &format!("{tloc}.rows[{ri}].cells[{ci}].props"), &cell.props, count);
for (ki, ctl) in cell.controls.open.iter().enumerate() {
if let Some(rp) = &ctl.run_props {
walk_char(doc, label, &format!("{tloc}.rows[{ri}].cells[{ci}].controls[{ki}].run_props"), rp, count);
}
}
walk_blocks(doc, label, &format!("{tloc}.rows[{ri}].cells[{ci}].blocks"), &cell.blocks, count);
}
}
}
}
}
}
let mut count = 0;
walk_blocks(doc, label, "body", &doc.body, &mut count);
walk_section(doc, label, "last_section", &doc.last_section, &mut count);
for (id, part) in &doc.parts {
walk_blocks(doc, label, &format!("part({:?}#{id})", part.kind), &part.blocks, &mut count);
}
for (sname, sep) in [("footnote_separators", &doc.footnote_separators), ("endnote_separators", &doc.endnote_separators)] {
for (fname, blocks) in [
("separator", &sep.separator),
("continuation_separator", &sep.continuation_separator),
("continuation_notice", &sep.continuation_notice),
] {
if let Some(bl) = blocks {
walk_blocks(doc, label, &format!("{sname}.{fname}"), bl, &mut count);
}
}
}
for (gi, bb) in doc.glossary.iter().enumerate() {
walk_blocks(doc, label, &format!("glossary[{gi}]"), &bb.blocks, &mut count);
}
walk_char(doc, label, "styles.default_chr", &doc.styles.default_chr, &mut count);
walk_para_props(doc, label, "styles.default_para", &doc.styles.default_para, &mut count);
for st in &doc.styles.styles {
walk_para_props(doc, label, &format!("styles[{}].para", st.id), &st.para, &mut count);
walk_char(doc, label, &format!("styles[{}].chr", st.id), &st.chr, &mut count);
if let Some(ch) = &st.para_change {
check_idx(doc, label, &format!("styles[{}].para_change", st.id), ch.rev, RevisionKind::Format, &mut count);
walk_para_props(doc, label, &format!("styles[{}].para_change.old", st.id), &ch.old, &mut count);
}
if let Some(ch) = &st.chr_change {
check_idx(doc, label, &format!("styles[{}].chr_change", st.id), ch.rev, RevisionKind::Format, &mut count);
walk_char(doc, label, &format!("styles[{}].chr_change.old", st.id), &ch.old, &mut count);
}
if let Some(tbl) = &st.table {
for (k, c) in [
("header_chr", &tbl.header_chr),
("band_chr", &tbl.band_chr),
("first_col_chr", &tbl.first_col_chr),
("total_chr", &tbl.total_chr),
("last_col_chr", &tbl.last_col_chr),
("col_band_chr", &tbl.col_band_chr),
] {
walk_char(doc, label, &format!("styles[{}].table.{k}", st.id), c, &mut count);
}
for (rk, pf) in &tbl.regions {
walk_char(doc, label, &format!("styles[{}].table.regions[{rk:?}].chr", st.id), &pf.chr, &mut count);
}
}
}
for (ai, abs) in doc.numbering.abstracts.iter().enumerate() {
for (li, lvl) in abs.levels.iter().enumerate() {
walk_char(doc, label, &format!("numbering.abstracts[{ai}].levels[{li}].chr"), &lvl.chr, &mut count);
}
}
for (ni, num) in doc.numbering.nums.iter().enumerate() {
for (li, (_, lvl)) in num.level_overrides.iter().enumerate() {
walk_char(doc, label, &format!("numbering.nums[{ni}].level_overrides[{li}].chr"), &lvl.chr, &mut count);
}
}
count
}
/// #8129: Accept All / Reject All must not invalidate revision references that survive in
/// preserved annotation properties (e.g., a Ruby guide in a header story carrying a Format record
/// into the document's own revision table).
#[test]
fn accept_and_reject_all_keep_surviving_header_ruby_revision_valid() {
use wordcraft_doc::{
CharProps, InlineObject, Paragraph, PartKind, Revision, RevisionKind, StoryRef, para::RubyAlign, para_block, props::PropChange,
};
let mut orig = Document::from_text("Original body text.");
// Populate indices 0..=4 so the header Ruby guide owns Format revision at index 4.
for i in 0..4 {
orig.revisions.push(Revision::new(RevisionKind::Insert, format!("Prior {i}"), "2026-11-28T00:00:00Z"));
}
orig.revisions.push(Revision::new(RevisionKind::Format, "HeaderOwner", "2026-11-29T00:00:00Z"));
let mut header_para = Paragraph::new();
let ruby = InlineObject::Ruby {
base: "漢字".into(),
ruby: "かんじ".into(),
align: RubyAlign::Center,
size: 6.0,
raise: 10.0,
base_size: 12.0,
lang: "ja-JP".into(),
props: Box::new(CharProps { bold: Some(true), fmt_change: PropChange::boxed(4, CharProps::default()), ..Default::default() }),
};
header_para.insert_object(0, ruby, &CharProps::default()).unwrap();
let header_id = orig.add_part(PartKind::Header, vec![para_block(header_para)]);
orig.last_section.headers.default = Some(header_id);
// Body-only edit compared against `orig`: compare preserves the header and its index-4 record.
let mut compared = Session::new(orig);
compared.run("review.compare", &json!({"text": "Revised body text.", "author": "Reviewer"})).unwrap();
assert!(assert_all_revision_refs_valid(&compared.doc, "after compare") >= 3);
for (cmd, want_body) in [("review.acceptAll", "Revised body text."), ("review.rejectAll", "Original body text.")] {
let mut s = Session::new(compared.doc.clone());
s.run(cmd, &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), want_body, "{cmd}: body endpoint");
let surviving = assert_all_revision_refs_valid(&s.doc, cmd);
assert_eq!(surviving, 1, "{cmd}: header Ruby revision reference survives");
let header = s.doc.parts.get(&header_id).expect("header preserved");
let hp = header.blocks[0].as_para().expect("header paragraph");
let InlineObject::Ruby { props, .. } = &hp.objects[0] else { panic!("expected Ruby") };
let rev_idx = props.fmt_change.as_ref().expect("Ruby fmt_change preserved").rev;
let rev = &s.doc.revisions[rev_idx as usize];
assert_eq!(rev.kind, RevisionKind::Format);
assert_eq!(rev.author, "HeaderOwner");
assert_eq!(rev.date, "2026-11-29T00:00:00Z");
}
}
/// #8129: Surviving revision references across footer, footnote, comment, and text-box stories
/// (including shared indices and ContentControl run_props) remain valid and compacted after both
/// Accept All and Reject All, and repeated resolution is idempotent.
#[test]
fn accept_and_reject_all_keep_surviving_refs_across_other_stories() {
use wordcraft_doc::{
CharProps, Comment, ContentControl, ControlKind, InlineObject, Paragraph, PartKind, Revision, RevisionKind, StoryRef,
para::{NoteKind, RubyAlign, ShapeKind},
para_block,
props::PropChange,
};
let make_ruby = |rev: u32| InlineObject::Ruby {
base: "漢".into(),
ruby: "かん".into(),
align: RubyAlign::Center,
size: 6.0,
raise: 10.0,
base_size: 12.0,
lang: "ja-JP".into(),
props: Box::new(CharProps { bold: Some(true), fmt_change: PropChange::boxed(rev, CharProps::default()), ..Default::default() }),
};
let mut doc = Document::from_text("");
// Indices 0..=7; only 2 (Footer/TextBox) and 5 (Footnote/Comment) survive resolution.
doc.revisions.push(Revision::new(RevisionKind::Insert, "Unused0", "2026-11-20T00:00:00Z"));
doc.revisions.push(Revision::new(RevisionKind::Delete, "Unused1", "2026-11-21T00:00:00Z"));
doc.revisions.push(Revision::new(RevisionKind::Format, "FooterOwner", "2026-11-22T00:00:00Z"));
doc.revisions.push(Revision::new(RevisionKind::Insert, "Unused3", "2026-11-23T00:00:00Z"));
doc.revisions.push(Revision::new(RevisionKind::Delete, "Unused4", "2026-11-24T00:00:00Z"));
doc.revisions.push(Revision::new(RevisionKind::Format, "FootnoteOwner", "2026-11-25T00:00:00Z"));
doc.revisions.push(Revision::new(RevisionKind::Insert, "Reviewer", "2026-11-29T00:00:00Z"));
doc.revisions.push(Revision::new(RevisionKind::Delete, "Reviewer", "2026-11-29T00:00:00Z"));
let mut footer_para = Paragraph::new();
footer_para.insert_object(0, make_ruby(2), &CharProps::default()).unwrap();
let footer_id = doc.add_part(PartKind::Footer, vec![para_block(footer_para)]);
doc.last_section.footers.default = Some(footer_id);
let mut footnote_para = Paragraph::new();
let mut ctl = ContentControl::new(ControlKind::RichText);
ctl.run_props = Some(CharProps { italic: Some(true), fmt_change: PropChange::boxed(5, CharProps::default()), ..Default::default() });
footnote_para.insert_object(0, InlineObject::ControlStart { control: Box::new(ctl) }, &CharProps::default()).unwrap();
footnote_para.insert_object(footnote_para.len(), InlineObject::ControlEnd, &CharProps::default()).unwrap();
let footnote_id = doc.add_part(PartKind::Footnote, vec![para_block(footnote_para)]);
let mut textbox_para = Paragraph::new();
textbox_para.insert_object(0, make_ruby(2), &CharProps::default()).unwrap();
let textbox_id = doc.add_part(PartKind::TextBox, vec![para_block(textbox_para)]);
let mut comment_para = Paragraph::new();
comment_para.insert_object(0, make_ruby(5), &CharProps::default()).unwrap();
let comment_id = doc.add_part(PartKind::Comment, vec![para_block(comment_para)]);
doc.comments.insert(1, Comment { author: "Alice".into(), part: comment_id, ..Default::default() });
let body_p = doc.para_mut(StoryRef::Body, &wordcraft_doc::Path(vec![0])).unwrap();
body_p.insert_text(body_p.len(), "Revised", &CharProps { ins: Some(6), ..Default::default() }).unwrap();
body_p.insert_text(body_p.len(), "Original", &CharProps { del: Some(7), ..Default::default() }).unwrap();
body_p.insert_text(body_p.len(), " body.", &CharProps::default()).unwrap();
body_p
.insert_object(
body_p.len(),
InlineObject::NoteRef { kind: NoteKind::Footnote, id: footnote_id, custom: String::new() },
&CharProps::default(),
)
.unwrap();
body_p
.insert_object(
body_p.len(),
InlineObject::Shape {
kind: ShapeKind::Rectangle,
w: 72.0,
h: 36.0,
fill: None,
stroke: None,
stroke_width: 0.0,
float: Default::default(),
story: Some(textbox_id),
freeform: None,
effects: Default::default(),
extra: Default::default(),
},
&CharProps::default(),
)
.unwrap();
body_p.insert_object(0, InlineObject::CommentStart { id: 1 }, &CharProps::default()).unwrap();
body_p.insert_object(body_p.len(), InlineObject::CommentEnd { id: 1 }, &CharProps::default()).unwrap();
assert_eq!(assert_all_revision_refs_valid(&doc, "before resolution"), 6);
for (cmd, want_body) in [("review.acceptAll", "Revised body."), ("review.rejectAll", "Original body.")] {
let mut s = Session::new(doc.clone());
s.run(cmd, &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), want_body, "{cmd}: body endpoint");
assert_eq!(assert_all_revision_refs_valid(&s.doc, cmd), 4, "{cmd}: 4 surviving references");
assert_eq!(s.doc.revisions.len(), 2, "{cmd}: compacted to 2 distinct referenced revisions");
let InlineObject::Ruby { props: footer_props, .. } = &s.doc.parts[&footer_id].blocks[0].as_para().unwrap().objects[0] else {
panic!("expected footer Ruby");
};
let InlineObject::ControlStart { control: fn_ctl } = &s.doc.parts[&footnote_id].blocks[0].as_para().unwrap().objects[0] else {
panic!("expected footnote ControlStart");
};
let InlineObject::Ruby { props: tb_props, .. } = &s.doc.parts[&textbox_id].blocks[0].as_para().unwrap().objects[0] else {
panic!("expected textbox Ruby");
};
let InlineObject::Ruby { props: cm_props, .. } = &s.doc.parts[&comment_id].blocks[0].as_para().unwrap().objects[0] else {
panic!("expected comment Ruby");
};
let footer_rev = footer_props.fmt_change.as_ref().unwrap().rev;
let tb_rev = tb_props.fmt_change.as_ref().unwrap().rev;
let fn_rev = fn_ctl.run_props.as_ref().unwrap().fmt_change.as_ref().unwrap().rev;
let cm_rev = cm_props.fmt_change.as_ref().unwrap().rev;
assert_eq!(footer_rev, tb_rev, "{cmd}: shared index preserved across footer and textbox");
assert_eq!(fn_rev, cm_rev, "{cmd}: shared index preserved across footnote and comment");
assert_eq!(s.doc.revisions[footer_rev as usize].author, "FooterOwner");
assert_eq!(s.doc.revisions[fn_rev as usize].author, "FootnoteOwner");
// Second pass must be idempotent.
let after_first = s.doc.clone();
s.run(cmd, &json!({})).unwrap();
assert_eq!(s.doc, after_first, "{cmd}: second pass must be a no-op");
}
}
/// #8129: Common path — when Accept All or Reject All leaves no surviving revision references
/// anywhere in the document, the revision table is cleared completely as before.
#[test]
fn accept_and_reject_all_clear_revision_table_when_no_refs_survive() {
use wordcraft_doc::{CharProps, Paragraph, PartKind, Revision, RevisionKind, StoryRef, para_block};
let mut doc = Document::from_text("Body ");
doc.revisions.push(Revision::new(RevisionKind::Insert, "Alice", "2026-11-29T00:00:00Z"));
doc.revisions.push(Revision::new(RevisionKind::Delete, "Bob", "2026-11-29T00:00:00Z"));
let body_p = doc.para_mut(StoryRef::Body, &wordcraft_doc::Path(vec![0])).unwrap();
body_p.insert_text(body_p.len(), "new", &CharProps { ins: Some(0), ..Default::default() }).unwrap();
body_p.insert_text(body_p.len(), "old", &CharProps { del: Some(1), ..Default::default() }).unwrap();
let mut header_p = Paragraph::with_text("Hdr ", CharProps::default());
header_p.insert_text(header_p.len(), "ins", &CharProps { ins: Some(0), ..Default::default() }).unwrap();
let header_id = doc.add_part(PartKind::Header, vec![para_block(header_p)]);
doc.last_section.headers.default = Some(header_id);
for (cmd, want_body, want_hdr) in [("review.acceptAll", "Body new", "Hdr ins"), ("review.rejectAll", "Body old", "Hdr ")] {
let mut s = Session::new(doc.clone());
s.run(cmd, &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), want_body, "{cmd}: body endpoint");
assert_eq!(s.doc.plain_text(StoryRef::Part(header_id)), want_hdr, "{cmd}: header endpoint");
assert_eq!(assert_all_revision_refs_valid(&s.doc, cmd), 0);
assert!(s.doc.revisions.is_empty(), "{cmd}: revision table cleared when no references survive");
}
}
/// #8129: Malformed input — an out-of-bounds outer `PropChange` burying a valid inner revision
/// index must reach its fixed point in a single Accept All / Reject All pass: the buried record
/// is discarded along with its invalid outer change, the table contains only records still
/// referenced, and a second resolution pass leaves the document identical.
#[test]
fn accept_and_reject_all_reach_fixed_point_with_buried_rev_in_invalid_outer_change() {
use wordcraft_doc::{
CharProps, InlineObject, Paragraph, PartKind, Revision, RevisionKind, StoryRef, para::RubyAlign, para_block, props::PropChange,
};
let make_ruby = |props: CharProps| InlineObject::Ruby {
base: "漢".into(),
ruby: "かん".into(),
align: RubyAlign::Center,
size: 6.0,
raise: 10.0,
base_size: 12.0,
lang: "ja-JP".into(),
props: Box::new(props),
};
// Case 1: Only surviving reference carrier is malformed (invalid outer rev 99 burying valid
// inner rev 0). One pass must clear both the malformed PropChange and the revision table.
let mut sole_doc = Document::from_text("");
sole_doc.revisions.push(Revision::new(RevisionKind::Format, "BuriedInner", "2026-11-28T00:00:00Z"));
sole_doc.revisions.push(Revision::new(RevisionKind::Insert, "Reviewer", "2026-11-29T00:00:00Z"));
sole_doc.revisions.push(Revision::new(RevisionKind::Delete, "Reviewer", "2026-11-29T00:00:00Z"));
let mut hdr_para = Paragraph::new();
let buried_props = CharProps {
bold: Some(true),
fmt_change: PropChange::boxed(99, CharProps { fmt_change: PropChange::boxed(0, CharProps::default()), ..Default::default() }),
..Default::default()
};
hdr_para.insert_object(0, make_ruby(buried_props), &CharProps::default()).unwrap();
let hdr_id = sole_doc.add_part(PartKind::Header, vec![para_block(hdr_para)]);
sole_doc.last_section.headers.default = Some(hdr_id);
let body_p = sole_doc.para_mut(StoryRef::Body, &wordcraft_doc::Path(vec![0])).unwrap();
body_p.insert_text(body_p.len(), "New", &CharProps { ins: Some(1), ..Default::default() }).unwrap();
body_p.insert_text(body_p.len(), "Old", &CharProps { del: Some(2), ..Default::default() }).unwrap();
for (cmd, want_body) in [("review.acceptAll", "New"), ("review.rejectAll", "Old")] {
let mut s = Session::new(sole_doc.clone());
s.run(cmd, &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), want_body, "{cmd} sole: body endpoint");
assert_eq!(assert_all_revision_refs_valid(&s.doc, &format!("{cmd} sole")), 0);
assert!(s.doc.revisions.is_empty(), "{cmd} sole: buried revision must not linger after pass 1");
let InlineObject::Ruby { props, .. } = &s.doc.parts[&hdr_id].blocks[0].as_para().unwrap().objects[0] else {
panic!("expected Ruby");
};
assert!(props.fmt_change.is_none(), "{cmd} sole: invalid outer fmt_change discarded");
let after_first = s.doc.clone();
s.run(cmd, &json!({})).unwrap();
assert_eq!(s.doc, after_first, "{cmd} sole: second pass must be a no-op");
}
// Case 2: Mixed malformed and valid surviving carriers, including a valid -> invalid -> valid
// chain. After one pass, only the genuinely surviving records remain and pass 2 is a no-op.
let mut mixed_doc = Document::from_text("");
mixed_doc.revisions.push(Revision::new(RevisionKind::Format, "BuriedInOuter", "2026-11-20T00:00:00Z"));
mixed_doc.revisions.push(Revision::new(RevisionKind::Format, "KeptOuter", "2026-11-21T00:00:00Z"));
mixed_doc.revisions.push(Revision::new(RevisionKind::Format, "BuriedInMid", "2026-11-22T00:00:00Z"));
mixed_doc.revisions.push(Revision::new(RevisionKind::Format, "KeptOther", "2026-11-23T00:00:00Z"));
mixed_doc.revisions.push(Revision::new(RevisionKind::Insert, "Reviewer", "2026-11-29T00:00:00Z"));
mixed_doc.revisions.push(Revision::new(RevisionKind::Delete, "Reviewer", "2026-11-29T00:00:00Z"));
let mut hdr_mixed = Paragraph::new();
// Ruby 0: invalid outer (99) burying valid rev 0.
let outer_invalid = CharProps {
fmt_change: PropChange::boxed(99, CharProps { ins: Some(0), fmt_change: PropChange::boxed(0, CharProps::default()), ..Default::default() }),
..Default::default()
};
// Ruby 1: valid outer (1) containing invalid middle (88) burying valid rev 2.
let nested_invalid = CharProps {
fmt_change: PropChange::boxed(
1,
CharProps {
fmt_change: PropChange::boxed(88, CharProps { fmt_change: PropChange::boxed(2, CharProps::default()), ..Default::default() }),
..Default::default()
},
),
..Default::default()
};
hdr_mixed.insert_object(0, make_ruby(outer_invalid), &CharProps::default()).unwrap();
hdr_mixed.insert_object(hdr_mixed.len(), make_ruby(nested_invalid), &CharProps::default()).unwrap();
let hdr_mixed_id = mixed_doc.add_part(PartKind::Header, vec![para_block(hdr_mixed)]);
mixed_doc.last_section.headers.default = Some(hdr_mixed_id);
let mut ftr_mixed = Paragraph::new();
let valid_other = CharProps { fmt_change: PropChange::boxed(3, CharProps::default()), ..Default::default() };
ftr_mixed.insert_object(0, make_ruby(valid_other), &CharProps::default()).unwrap();
let ftr_mixed_id = mixed_doc.add_part(PartKind::Footer, vec![para_block(ftr_mixed)]);
mixed_doc.last_section.footers.default = Some(ftr_mixed_id);
let body_m = mixed_doc.para_mut(StoryRef::Body, &wordcraft_doc::Path(vec![0])).unwrap();
body_m.insert_text(body_m.len(), "New", &CharProps { ins: Some(4), ..Default::default() }).unwrap();
body_m.insert_text(body_m.len(), "Old", &CharProps { del: Some(5), ..Default::default() }).unwrap();
for (cmd, want_body) in [("review.acceptAll", "New"), ("review.rejectAll", "Old")] {
let mut s = Session::new(mixed_doc.clone());
s.run(cmd, &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), want_body, "{cmd} mixed: body endpoint");
assert_eq!(assert_all_revision_refs_valid(&s.doc, &format!("{cmd} mixed")), 2);
let authors: Vec<&str> = s.doc.revisions.iter().map(|r| r.author.as_str()).collect();
assert_eq!(authors, vec!["KeptOuter", "KeptOther"], "{cmd} mixed: only genuinely referenced records retained");
let hdr_objs = &s.doc.parts[&hdr_mixed_id].blocks[0].as_para().unwrap().objects;
let InlineObject::Ruby { props: p0, .. } = &hdr_objs[0] else { panic!("expected Ruby 0") };
let InlineObject::Ruby { props: p1, .. } = &hdr_objs[1] else { panic!("expected Ruby 1") };
let InlineObject::Ruby { props: pf, .. } = &s.doc.parts[&ftr_mixed_id].blocks[0].as_para().unwrap().objects[0] else {
panic!("expected footer Ruby");
};
assert!(p0.fmt_change.is_none(), "{cmd} mixed: invalid outer discarded");
let p1_outer = p1.fmt_change.as_ref().expect("valid outer retained");
assert_eq!(s.doc.revisions[p1_outer.rev as usize].author, "KeptOuter");
assert!(p1_outer.old.fmt_change.is_none(), "{cmd} mixed: invalid middle and buried inner discarded");
let pf_outer = pf.fmt_change.as_ref().expect("valid footer ref retained");
assert_eq!(s.doc.revisions[pf_outer.rev as usize].author, "KeptOther");
let after_first = s.doc.clone();
s.run(cmd, &json!({})).unwrap();
assert_eq!(s.doc, after_first, "{cmd} mixed: second pass must be a no-op");
}
}
+1 -1
View File
@@ -26,7 +26,7 @@ use clear::{cell_prefix, guard_delete, text_spans};
use convert::{formula, from_text, quick_table, sort_table, to_text};
pub use convert::{text_table_cells, text_table_lines};
use layout::{autofit, borders, fix_caret, properties, set_column_widths};
pub(crate) use layout::{sync_cell_widths, text_direction, touch_cells};
pub(crate) use layout::{cell_block_borders, sync_cell_widths, text_direction, touch_cells};
pub(crate) use select::{extend_selection, grow_select_all, select_cell_first, select_range};
use select::{select_cells, select_column};
pub use structure::split_targets;
+182
View File
@@ -279,3 +279,185 @@ pub(super) fn borders(s: &mut Session, v: &Value) -> CmdResult {
}
})
}
/// Home › Paragraph › Borders with whole cells selected (the table, rows, columns or a block of
/// cells): the border goes on the cells as one block, as in Word, not on the paragraphs in them
/// (#7874). `all` borders every cell, `outside` the block's edges, `inside` the lines between its
/// cells, `none` clears every side, and one side toggles along that edge of the block. Other kinds
/// change nothing.
pub(crate) fn cell_block_borders(s: &mut Session, range: &crate::CellRange, kind: &str, b: Border) -> CmdResult {
let nil = Border { style: BorderStyle::None, width: 0.0, color: None, space: 0.0 };
let b = Border { space: 0.0, ..b };
let one_side = ["top", "left", "bottom", "right"].iter().position(|k| *k == kind);
if one_side.is_none() && !matches!(kind, "all" | "none" | "outside" | "inside") {
return sel_result(s);
}
let t = s.doc.table(range.story, &range.table).ok_or_else(|| CmdError::Disabled("the selection isn't in a table".into()))?;
let (g0, g1) = range.cols;
let picked = with_merge_runs(t, range.cells(t));
// The selected cells' grid columns, row by row from the block's first row.
let r0 = picked.iter().map(|&(r, _)| r).min().unwrap_or(range.rows.0);
let mut spans: Vec<Vec<(usize, usize)>> = Vec::new();
for &(r, c) in &picked {
let i = r.saturating_sub(r0);
if spans.len() <= i {
spans.resize_with(i + 1, Vec::new);
}
spans[i].push(super::grid_cols(t, r, c));
}
// Whether a selected cell in row `r` covers any of grid columns `a..=z`.
let picked_in = |r: Option<usize>, (a, z): (usize, usize)| {
r.and_then(|r| r.checked_sub(r0)).and_then(|i| spans.get(i)).is_some_and(|row| row.iter().any(|&(sa, sz)| sa <= z && sz >= a))
};
// Each selected cell, and which of its sides (top, left, bottom, right) are on the block's edge:
// above and below, where no selected cell lies across that side (a row that skips the selected
// grid columns with `w:gridBefore` leaves a gap in the block). A row's first and last cells are
// on it too when the row skips grid columns (`w:gridBefore`, `w:gridAfter`): the layout draws
// those as the table's outer edge.
let cells: Vec<(usize, usize, [bool; 4])> = picked
.iter()
.map(|&(r, c)| {
let (a, z) = super::grid_cols(t, r, c);
let last = t.rows.get(r).map_or(0, |row| row.cells.len().saturating_sub(1));
(r, c, [!picked_in(r.checked_sub(1), (a, z)), a <= g0 || c == 0, !picked_in(Some(r + 1), (a, z)), z >= g1 || c >= last])
})
.collect();
// Whether cell (`r`, `c`) draws a line on side `i`, its own or one the table or its style gives it.
let resolved = wordcraft_layout::CellBorders::new(&s.doc, t);
let draws = |r: usize, c: usize, i: usize| side(&resolved.of(r, c), i).is_some_and(|x| x.is_visible());
// One side is taken off when a line already shows all along that edge, drawn by the cells
// there or by cells beyond them that span the whole side, as the button toggles.
let shown = one_side.is_some_and(|i| {
cells.iter().filter(|(_, _, edge)| edge[i]).all(|&(r, c, _)| {
if draws(r, c, i) {
return true;
}
let across = beside(t, r, c, i, (g0, g1));
if matches!(i, 1 | 3) {
// The cell beside it in the row has the same height.
return !across.is_empty() && across.into_iter().all(|(nr, nc)| draws(nr, nc, (i + 2) % 4));
}
// Above or below: the cells drawing the facing line must cover the side's grid
// columns within the block, so a row that skips columns there leaves it uncovered.
let (a, z) = super::grid_cols(t, r, c);
let drawing = across.into_iter().filter(|&(nr, nc)| draws(nr, nc, (i + 2) % 4)).map(|(nr, nc)| super::grid_cols(t, nr, nc));
covers(drawing.collect(), (a.max(g0), z.min(g1)))
})
});
// The sides to set: (row, cell, side, border).
let mut writes: Vec<(usize, usize, usize, Border)> = Vec::new();
for (r, c, edge) in cells {
for (i, on_edge) in edge.into_iter().enumerate() {
let new = match kind {
"all" => Some(b),
"none" => Some(nil),
"outside" if on_edge => Some(b),
"inside" if !on_edge => Some(b),
_ if one_side == Some(i) && on_edge => Some(if shown { nil } else { b }),
_ => None,
};
let Some(new) = new else { continue };
writes.push((r, c, i, new));
// Each cell draws its own sides, so a line on the block's edge is also the facing
// side of the cell beyond it: that gets the same border, or No Border would leave
// the neighbour's line showing.
if on_edge {
writes.extend(beside(t, r, c, i, (g0, g1)).into_iter().map(|(nr, nc)| (nr, nc, (i + 2) % 4, new)));
}
}
}
let t = s.doc.table_mut(range.story, &range.table)?;
for (r, c, i, new) in writes {
let Some(cl) = t.rows.get_mut(r).and_then(|row| row.cells.get_mut(c)) else { continue };
let mut cur = cl.props.borders.unwrap_or_default();
*side_mut(&mut cur, i) = Some(new);
cl.props.borders = Some(cur);
}
touch_cells(s, &range.table)?;
sel_result(s)
}
/// Whether the grid column spans `parts` (first, last) cover every column of `a..=z`.
fn covers(mut parts: Vec<(usize, usize)>, (a, z): (usize, usize)) -> bool {
parts.sort_unstable();
let mut next = a;
for (pa, pz) in parts {
if pa > next {
break;
}
next = next.max(pz + 1);
}
next > z
}
/// `cells` with the rest of each vertically merged cell's run: the merged cell is one cell over
/// its rows, though selecting it from its first row takes in only that row.
fn with_merge_runs(t: &Table, mut cells: Vec<(usize, usize)>) -> Vec<(usize, usize)> {
// The cell starting at grid column `g` of row `r`, when there is one.
let at = |r: usize, g: usize| t.cell_at_grid(r, g).filter(|&c| t.grid_col(r, c) == g);
let continues =
|r: usize, c: usize| t.rows.get(r).and_then(|row| row.cells.get(c)).is_some_and(|x| x.props.vmerge == wordcraft_doc::props::VMerge::Continue);
let mut seen: std::collections::HashSet<(usize, usize)> = cells.iter().copied().collect();
let mut i = 0;
while let Some(&(r, c)) = cells.get(i) {
i += 1;
let g = t.grid_col(r, c);
let below = at(r + 1, g).filter(|&nc| continues(r + 1, nc)).map(|nc| (r + 1, nc));
let above = r.checked_sub(1).filter(|_| continues(r, c)).and_then(|pr| at(pr, g).map(|pc| (pr, pc)));
for next in [below, above].into_iter().flatten() {
if seen.insert(next) {
cells.push(next);
}
}
}
cells
}
/// The cells across side `i` (top, left, bottom, right) of cell (`r`, `c`) whose facing edge lies
/// wholly on that line. Above and below, only cells within grid columns `cols` (the selected
/// block's), so a wider cell's edge beyond the block keeps its line.
fn beside(t: &Table, r: usize, c: usize, i: usize, (g0, g1): (usize, usize)) -> Vec<(usize, usize)> {
let Some(row) = t.rows.get(r) else { return Vec::new() };
match i {
1 => c.checked_sub(1).map(|p| vec![(r, p)]).unwrap_or_default(),
3 => {
if c + 1 < row.cells.len() {
vec![(r, c + 1)]
} else {
Vec::new()
}
}
_ => {
let nr = if i == 0 { r.checked_sub(1) } else { Some(r + 1) };
let Some((nr, next)) = nr.and_then(|nr| t.rows.get(nr).map(|x| (nr, x))) else { return Vec::new() };
let (a, z) = super::grid_cols(t, r, c);
(0..next.cells.len())
.filter(|&nc| {
let (na, nz) = super::grid_cols(t, nr, nc);
na <= z && nz >= a && na >= g0 && nz <= g1
})
.map(|nc| (nr, nc))
.collect()
}
}
}
/// Side `i` of `b`: top, left, bottom, right.
fn side(b: &Borders, i: usize) -> Option<Border> {
match i {
0 => b.top,
1 => b.left,
2 => b.bottom,
_ => b.right,
}
}
/// Side `i` of `b` to set: top, left, bottom, right.
fn side_mut(b: &mut Borders, i: usize) -> &mut Option<Border> {
match i {
0 => &mut b.top,
1 => &mut b.left,
2 => &mut b.bottom,
_ => &mut b.right,
}
}
+4 -4
View File
@@ -18,7 +18,7 @@ pub(crate) use autoformat::smart_quote;
use delete::{backspace, delete, delete_sentence_back, delete_word_back, delete_word_fwd};
pub use enter_tab::MAX_TYPED_PARAGRAPHS;
use enter_tab::{back_tab, new_paragraph, tab};
use unicode::{ins_char, insert_code, toggle_unicode};
use unicode::{ins_char, insert_break, insert_code, toggle_unicode};
pub use unicode::{oem_code_page, system_code_pages, system_oem_code_page};
/// The text-entry commands: typing, Enter, breaks, Tab, deleting and typed symbols.
@@ -26,9 +26,9 @@ pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec::new("text.insert", "Type Text", "Editing", insert).params(r#"{"text": string, "raw"?: bool, "paragraphs"?: bool} (paragraphs: each line a paragraph, one undo step, at most 10000 lines)"#),
CommandSpec::new("text.newParagraph", "New Paragraph", "Editing", new_paragraph).key("Enter"),
CommandSpec::new("text.lineBreak", "Line Break", "Editing", |s, _| ins_char(s, '\n')).key("Shift+Enter"),
CommandSpec::new("text.pageBreak", "Page Break", "Insert › Pages", |s, _| ins_char(s, PAGE_BREAK)).key("Mod+Enter"),
CommandSpec::new("text.columnBreak", "Column Break", "Layout › Breaks", |s, _| ins_char(s, COLUMN_BREAK)).key("Mod+Shift+Enter"),
CommandSpec::new("text.lineBreak", "Line Break", "Editing", |s, _| insert_break(s, '\n')).key("Shift+Enter"),
CommandSpec::new("text.pageBreak", "Page Break", "Insert › Pages", |s, _| insert_break(s, PAGE_BREAK)).key("Mod+Enter"),
CommandSpec::new("text.columnBreak", "Column Break", "Layout › Breaks", |s, _| insert_break(s, COLUMN_BREAK)).key("Mod+Shift+Enter"),
CommandSpec::new("text.tab", "Tab", "Editing", tab).key("Tab"),
CommandSpec::new("text.backTab", "Shift+Tab", "Editing", back_tab).key("Shift+Tab"),
// A tab character even in a table cell, where Tab moves to the next cell (#3137); ⌥Tab on macOS.
+3 -2
View File
@@ -58,8 +58,9 @@ fn sample_text(s: &Session) -> Option<String> {
/// `text.newParagraph`: Enter, unless the selection is in a control that takes no paragraph break.
pub(super) fn new_paragraph(s: &mut Session, _: &Value) -> CmdResult {
// Enter in a one-line plain text control (or a check box or list) does nothing, as in Word.
if crate::cmd::controls::refuses_paragraph(s) {
// Enter in a one-line plain text control (or a check box or list), or on a selected picture or
// shape, does nothing, as in Word (#4126).
if crate::cmd::controls::refuses_paragraph(s) || crate::cmd::objects::object_selection(s).is_some() {
return sel_result(s);
}
enter(s, true)?;
+14
View File
@@ -110,3 +110,17 @@ pub(super) fn ins_char(s: &mut Session, c: char) -> CmdResult {
type_text(s, c.encode_utf8(&mut b))?;
sel_result(s)
}
/// A line, page or column break. On a selected picture or shape, Word puts the break in front of
/// it and keeps it selected, rather than replacing it (#4126).
pub(super) fn insert_break(s: &mut Session, c: char) -> CmdResult {
let Some(at) = crate::cmd::objects::object_selection(s).map(|(p, _)| p) else { return ins_char(s, c) };
s.sel = Selection::caret(at.clone());
ins_char(s, c)?;
// The break goes in front of the object, or of the content control around it.
let at = Pos { off: at.off + c.len_utf8(), ..at };
if s.doc.para_at(&at).and_then(|p| p.object_at(at.off)).is_some_and(|o| o.is_drawing()) {
crate::cmd::objects::select_object(s, &at);
}
sel_result(s)
}
+13 -1
View File
@@ -1,5 +1,10 @@
use super::{Arc, CmdError, CmdResult, Document, Pos, Selection, Session, StoryRef, Value, delete_selection, json, p, sel_result};
use crate::cmd::insert::MAX_TABLE_ROWS;
use crate::cmd::mailings::{CsvLimits, MAX_TEXT_BYTES};
use wordcraft_doc::CharProps;
use wordcraft_doc::table::MAX_COLS;
const TABLE_LIMITS: CsvLimits = CsvLimits { fields: MAX_COLS, cells: MAX_TABLE_ROWS * MAX_COLS, text: MAX_TEXT_BYTES };
/// Options › Language › Set as default: only the saved default proofing language (what future
/// blank documents are written in), as Word's Set as Preferred. A setting, like `file.options`: the
@@ -458,7 +463,14 @@ pub(super) fn customize_ribbon(s: &mut Session, v: &Value) -> CmdResult {
pub(super) fn spreadsheet_rows(v: &Value) -> Result<Vec<Vec<String>>, CmdError> {
// The CSV fallback is for an absent `values`; an explicit null is a malformed argument.
let Some(values) = v.get("values") else {
return Ok(crate::cmd::mailings::parse_csv(p::str(v, "csv").unwrap_or("A,B,C\n1,2,3\n4,5,6")));
let rows = crate::cmd::mailings::parse_csv(p::str(v, "csv").unwrap_or("A,B,C\n1,2,3\n4,5,6"), &TABLE_LIMITS)
.map_err(|e| CmdError::Failed(format!("{e}; a table holds at most {MAX_TABLE_ROWS} rows of {MAX_COLS} columns")))?;
// A table holds so many rows: a longer list would lose its records quietly, because
// the table the command inserts is shorter than the list.
if rows.len() > MAX_TABLE_ROWS {
return Err(CmdError::Failed(format!("a table holds at most {MAX_TABLE_ROWS} rows")));
}
return Ok(rows);
};
let list = values.as_array().ok_or_else(|| CmdError::Params("`values` must be an array of rows".into()))?;
if list.is_empty() || list.len() > 1000 {
+19 -7
View File
@@ -116,9 +116,9 @@ pub(super) fn compare(s: &mut Session, v: &Value) -> CmdResult {
}
std::mem::take(&mut revised.body)
};
s.doc.revisions.push(wordcraft_doc::Revision { kind: RevisionKind::Insert, author: author.clone(), date: date.clone(), move_name: None });
s.doc.revisions.push(crate::cmd::made_revision(RevisionKind::Insert, author.clone(), date.clone()));
let ins = (s.doc.revisions.len() - 1) as u32;
s.doc.revisions.push(wordcraft_doc::Revision { kind: RevisionKind::Delete, author: author.clone(), date: date.clone(), move_name: None });
s.doc.revisions.push(crate::cmd::made_revision(RevisionKind::Delete, author.clone(), date.clone()));
let del = (s.doc.revisions.len() - 1) as u32;
let mut char_fallbacks = 0usize;
let mut table_fallbacks = 0usize;
@@ -443,7 +443,11 @@ 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| c.del = Some(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))));
@@ -1437,10 +1441,10 @@ fn diff_table(
/// Find or create the formatting revision entry for `author` and `date`.
fn format_revision(doc: &mut Document, author: &str, date: &str) -> u32 {
if let Some(i) = doc.revisions.iter().rposition(|r| r.kind == RevisionKind::Format && r.author == author && r.date == date) {
if let Some(i) = doc.revisions.iter().rposition(|r| r.kind == RevisionKind::Format && r.author == author && r.instant() == date) {
return u32::try_from(i).unwrap_or(u32::MAX);
}
doc.revisions.push(wordcraft_doc::Revision { kind: RevisionKind::Format, author: author.to_string(), date: date.to_string(), move_name: None });
doc.revisions.push(crate::cmd::made_revision(RevisionKind::Format, author.to_string(), date.to_string()));
u32::try_from(doc.revisions.len().saturating_sub(1)).unwrap_or(u32::MAX)
}
@@ -1613,8 +1617,16 @@ fn block_text(b: &Block, depth: usize) -> String {
}
}
/// Returns a copy of `b` with all text runs and paragraph marks across all nested table cells
/// updated by `f` iteratively, without recursion or depth truncation.
/// A copy of the block with every run (in tables, every cell's) changed by `f`, and a paragraph's
/// mark along with them, so a whole inserted or deleted paragraph carries the revision even when
/// the paragraph is empty (`format` returns early for a length-0 range). Walks nested tables
/// iteratively, without recursion or depth truncation.
///
/// A whole-paragraph revision on the last paragraph of a story or cell is removed together with
/// the paragraph on Accept/Reject All (see `remove_trailing_para` in `review::changes`), except
/// where the paragraph carries a section break or is the container's only paragraph. A
/// non-terminal section-carrying paragraph is removed whole too: `resolve_para` removes the
/// section break first (#5734, issue #5667), so the following paragraph keeps its own properties.
fn mark_block(b: &Block, f: &dyn Fn(&mut CharProps)) -> Block {
let mut out = b.clone();
let mut todo = vec![&mut out];
+2 -2
View File
@@ -237,7 +237,7 @@ pub fn specs() -> Vec<CommandSpec> {
.params(r#"{"csv"?: string, "values"?: [[cell, …], …] (rows of equal length, at most 1000 rows × 63 columns; wins over csv), "header"?: bool (first row repeats on each page), "style"?: table style name (default GridTable1Light)}"#),
CommandSpec::new("layout.linkToPrevious", "Link to Previous", "Header & Footer › Navigation", |s, v| {
let header = p::bool(v, "footer").map(|f| !f).unwrap_or(true);
let block = s.sel.focus.path.0.first().copied().unwrap_or(0) as usize;
let block = crate::cmd::page::section_end_of_focus(s);
let sect = s.doc.section_mut(block);
if header {
sect.headers = Default::default();
@@ -252,7 +252,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("hf.previous", "Previous Section", "Header & Footer › Navigation", |s, _| hf_nav(s, -1)).pure(),
CommandSpec::new("hf.position", "Header/Footer Position", "Header & Footer › Position", |s, v| {
let (h, f) = (p::f32(v, "header"), p::f32(v, "footer"));
let block = s.sel.focus.path.0.first().copied().unwrap_or(0) as usize;
let block = crate::cmd::page::section_end_of_focus(s);
let sect = s.doc.section_mut(block);
if let Some(h) = h {
sect.header = h.clamp(0.0, 300.0);
+276
View File
@@ -11,6 +11,259 @@ fn compare_marks_changes() {
assert_eq!(s.doc.plain_text(StoryRef::Body), "The dog sat.\nKeep this.\nNew line here.");
}
/// Top-level body blocks that are empty paragraphs.
fn empty_paras(s: &Session) -> usize {
s.doc.body.iter().filter(|b| matches!(b.as_para(), Some(p) if p.is_empty())).count()
}
#[test]
fn compare_marks_a_whole_paragraph_and_its_mark() {
// A whole inserted paragraph carries the insertion on its mark, not just on its runs.
let mut s = Session::new(Document::from_text("A\nB"));
s.run("review.compare", &json!({"text": "A\nNEW\nB"})).unwrap();
assert_eq!(s.doc.body.len(), 3);
let mid = s.doc.body[1].as_para().unwrap();
assert_eq!(mid.plain_text(), "NEW");
assert!(mid.mark.ins.is_some(), "the inserted paragraph's mark is not marked inserted");
s.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
assert_eq!(s.doc.body.len(), 2);
assert_eq!(empty_paras(&s), 0, "rejecting an inserted paragraph left an empty paragraph behind");
let mut s = Session::new(Document::from_text("A\nB"));
s.run("review.compare", &json!({"text": "A\nNEW\nB"})).unwrap();
s.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nNEW\nB");
assert_eq!(s.doc.body.len(), 3);
assert_eq!(empty_paras(&s), 0, "accepting an inserted paragraph left an empty paragraph behind");
// A whole deleted paragraph carries the deletion on its mark.
let mut s = Session::new(Document::from_text("A\nOLD\nB"));
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
assert_eq!(s.doc.body.len(), 3);
let mid = s.doc.body[1].as_para().unwrap();
assert_eq!(mid.plain_text(), "OLD");
assert!(mid.mark.del.is_some(), "the deleted paragraph's mark is not marked deleted");
s.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
assert_eq!(s.doc.body.len(), 2);
assert_eq!(empty_paras(&s), 0, "accepting a deleted paragraph left an empty paragraph behind");
let mut s = Session::new(Document::from_text("A\nOLD\nB"));
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
s.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nOLD\nB");
assert_eq!(s.doc.body.len(), 3);
assert_eq!(empty_paras(&s), 0, "rejecting a deleted paragraph left an empty paragraph behind");
}
#[test]
fn compare_marks_an_empty_paragraphs_mark() {
// An empty inserted paragraph is stamped on its mark, though `format` skips its empty range.
let mut s = Session::new(Document::from_text("A\nB"));
s.run("review.compare", &json!({"text": "A\n\nB"})).unwrap();
assert_eq!(s.doc.body.len(), 3);
let empty = s.doc.body[1].as_para().unwrap();
assert!(empty.is_empty());
assert!(empty.mark.ins.is_some(), "the empty inserted paragraph's mark is not marked inserted");
s.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
assert_eq!(s.doc.body.len(), 2);
assert_eq!(empty_paras(&s), 0, "rejecting an empty inserted paragraph left it behind");
// An empty deleted paragraph is stamped on its mark too.
let mut s = Session::new(Document::from_text("A\n\nB"));
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
assert_eq!(s.doc.body.len(), 3);
let empty = s.doc.body[1].as_para().unwrap();
assert!(empty.is_empty());
assert!(empty.mark.del.is_some(), "the empty deleted paragraph's mark is not marked deleted");
s.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
assert_eq!(s.doc.body.len(), 2);
assert_eq!(empty_paras(&s), 0, "accepting an empty deleted paragraph left it behind");
}
#[test]
fn compare_keeps_another_authors_deletion_stamp() {
// A paragraph the original already carries as a tracked deletion by another author: Compare
// must keep that author's revision on its runs and on its paragraph mark, not re-attribute
// the block to its own deletion revision.
let mut doc = Document::from_text("A\nOLD\nB");
doc.revisions.push(wordcraft_doc::Revision::new(RevisionKind::Delete, "Alice", ""));
let p = doc.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(1)).unwrap();
for r in &mut p.runs {
r.props.del = Some(0);
}
p.mark.del = Some(0);
let mut s = Session::new(doc);
s.run("review.compare", &json!({"text": "A\nB", "author": "Bob"})).unwrap();
assert_eq!(s.doc.body.len(), 3);
let mid = s.doc.body[1].as_para().unwrap();
assert_eq!(mid.plain_text(), "OLD");
assert!(mid.runs.iter().all(|r| r.props.del == Some(0)), "the runs' deletion was re-stamped: {:?}", mid.runs);
assert_eq!(mid.mark.del, Some(0), "the paragraph mark's deletion was re-stamped");
assert_eq!(s.doc.revisions.first().map(|r| (r.kind, r.author.as_str())), Some((RevisionKind::Delete, "Alice")));
}
#[test]
fn compare_terminal_inserted_paragraph_resolves_fully() {
// A paragraph inserted at the very end is removed whole when rejected, leaving no empty
// paragraph behind.
let mut s = Session::new(Document::from_text("A\nB"));
s.run("review.compare", &json!({"text": "A\nB\nC"})).unwrap();
assert_eq!(s.doc.body.len(), 3);
s.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
assert_eq!(s.doc.body.len(), 2);
assert_eq!(empty_paras(&s), 0, "rejecting a terminal inserted paragraph left an empty paragraph behind");
}
#[test]
fn compare_terminal_deleted_paragraph_resolves_fully() {
// The mirror of `compare_terminal_inserted_paragraph_resolves_fully`: a paragraph deleted
// from the very end is removed whole when accepted, leaving no empty paragraph behind.
let mut s = Session::new(Document::from_text("A\nB\nC"));
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
assert_eq!(s.doc.body.len(), 3);
s.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
assert_eq!(s.doc.body.len(), 2);
assert_eq!(empty_paras(&s), 0, "accepting a terminal deleted paragraph left an empty paragraph behind");
}
#[test]
fn reject_all_keeps_an_empty_inserted_paragraph_between_tables() {
// An empty paragraph between two tables is not the container's last block: removing it
// would make the tables adjacent, and they would join into one on reopen. Reject All only
// clears its mark.
use wordcraft_doc::{Block, Paragraph, para_block};
let mut doc = Document::from_text("");
doc.revisions.push(wordcraft_doc::Revision::new(RevisionKind::Insert, "Alice", ""));
let table = || std::sync::Arc::new(Block::Table(wordcraft_doc::table::Table::new(1, 1, 100.0)));
let mut between = Paragraph::default();
between.mark.ins = Some(0);
doc.body = vec![table(), para_block(between), table(), para_block(Paragraph::with_text("end", Default::default()))];
let mut s = Session::new(doc);
s.run("review.rejectAll", &json!({})).unwrap();
let kinds: Vec<bool> = s.doc.body.iter().map(|b| matches!(**b, Block::Table(_))).collect();
assert_eq!(kinds, [true, false, true, false]);
let kept = s.doc.para(StoryRef::Body, &wordcraft_doc::Path::top(1)).unwrap();
assert!(kept.is_empty() && kept.mark.ins.is_none(), "{kept:?}");
}
#[test]
fn compare_pins_rejecting_an_inserted_section_keeps_the_next_paragraphs_style() {
// Pins the fixed behaviour for rejecting an inserted paragraph that carries a section
// break. This was a known limitation recorded on `mark_block` (compare.rs): `resolve`'s
// `remove_empty_para` refused paragraphs carrying a section, so once the inserted
// paragraph's text was rejected the empty paragraph was joined into the next one, which
// took its properties ("Body" came back Normal instead of its original Heading 1). Fixed
// on main by #5734 (issue #5667): `resolve_para` now removes the section break first, so
// the empty paragraph goes whole and the following paragraph keeps its own properties.
// After Reject All the original is restored exactly.
let mut original = Document::from_text("Intro\nBody");
original.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(1)).unwrap().props.style = Some("Heading1".into());
let mut s = Session::new(original);
let mut rev = Document::from_text("Intro\nAppendix\nBody");
{
let p = rev.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(1)).unwrap();
p.props.style = Some("Normal".into());
p.section = Some(Box::new(wordcraft_doc::section::SectionProps::default()));
}
rev.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(2)).unwrap().props.style = Some("Heading1".into());
let path = std::env::temp_dir().join(format!("wc-compare-section-{}.docx", std::process::id()));
crate::io::save_path(&path, &rev).unwrap();
s.run("review.compare", &json!({"path": path.to_string_lossy()})).unwrap();
let _ = std::fs::remove_file(&path);
s.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "Intro\nBody");
assert_eq!(s.doc.body.len(), 2);
let body = s.doc.body[1].as_para().unwrap();
assert_eq!(body.plain_text(), "Body");
assert_eq!(body.props.style.as_deref(), Some("Heading1"), "the following paragraph keeps its own properties (fixed on main by #5734)");
}
#[test]
fn compare_pins_accepting_a_deleted_section_keeps_the_next_paragraphs_style() {
// The Accept-side mirror of `compare_pins_rejecting_an_inserted_section_keeps_the_next_paragraphs_style`:
// compare deletes a paragraph that carries a section break whole (original `A`, `OLD`
// with a section break, `B`; revised `A`, `B`). Accept All goes through the same #5734
// branch in `resolve_para` as the reject case: the section break is removed first, so
// the emptied paragraph goes whole instead of being joined into the next one. After
// Accept All the revised text stands exactly and `B` keeps its own properties.
let mut original = Document::from_text("A\nOLD\nB");
{
let p = original.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(1)).unwrap();
p.props.style = Some("Normal".into());
p.section = Some(Box::new(wordcraft_doc::section::SectionProps::default()));
}
original.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(2)).unwrap().props.style = Some("Heading1".into());
let mut s = Session::new(original);
let mut rev = Document::from_text("A\nB");
rev.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(1)).unwrap().props.style = Some("Heading1".into());
let path = std::env::temp_dir().join(format!("wc-compare-section-accept-{}.docx", std::process::id()));
crate::io::save_path(&path, &rev).unwrap();
s.run("review.compare", &json!({"path": path.to_string_lossy()})).unwrap();
let _ = std::fs::remove_file(&path);
assert_eq!(s.doc.body.len(), 3);
let mid = s.doc.body[1].as_para().unwrap();
assert_eq!(mid.plain_text(), "OLD");
assert!(mid.mark.del.is_some(), "the deleted sectioned paragraph's mark is not marked deleted");
s.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
assert_eq!(s.doc.body.len(), 2);
assert_eq!(empty_paras(&s), 0, "accepting the deleted sectioned paragraph left it behind");
let body = s.doc.body[1].as_para().unwrap();
assert_eq!(body.plain_text(), "B");
assert_eq!(body.props.style.as_deref(), Some("Heading1"), "the following paragraph keeps its own properties (fixed on main by #5734)");
}
#[test]
fn compare_marks_the_last_paragraphs_mark() {
// Inserted last paragraph: rejecting removes it whole.
let mut s = Session::new(Document::from_text("A\nB"));
s.run("review.compare", &json!({"text": "A\nB\nNEW"})).unwrap();
assert_eq!(s.doc.body.len(), 3);
assert!(s.doc.body[2].as_para().unwrap().mark.ins.is_some());
s.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
assert_eq!(s.doc.body.len(), 2);
assert_eq!(empty_paras(&s), 0);
let mut s = Session::new(Document::from_text("A\nB"));
s.run("review.compare", &json!({"text": "A\nB\nNEW"})).unwrap();
s.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB\nNEW");
assert_eq!(s.doc.body.len(), 3);
assert_eq!(empty_paras(&s), 0);
// Deleted last paragraph: accepting removes it whole.
let mut s = Session::new(Document::from_text("A\nB\nOLD"));
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
assert_eq!(s.doc.body.len(), 3);
assert!(s.doc.body[2].as_para().unwrap().mark.del.is_some());
s.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
assert_eq!(s.doc.body.len(), 2);
assert_eq!(empty_paras(&s), 0);
let mut s = Session::new(Document::from_text("A\nB\nOLD"));
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
s.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB\nOLD");
assert_eq!(s.doc.body.len(), 3);
assert_eq!(empty_paras(&s), 0);
}
#[test]
fn compare_keeps_the_only_paragraphs_mark() {
let mut s = Session::new(Document::from_text(""));
s.doc.revisions.push(wordcraft_doc::Revision::new(RevisionKind::Insert, s.author.clone(), ""));
s.doc.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap().mark.ins = Some(0);
s.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s.doc.body.len(), 1);
assert!(s.doc.body[0].as_para().unwrap().mark.ins.is_none());
}
#[test]
fn compare_options_ignore_case_and_white_space() {
let original = "The Cat sat.\nTwo spaces here.";
@@ -1661,10 +1914,32 @@ fn spreadsheet_rejects_hostile_values() {
}
}
/// A CSV too wide or too long for a table is refused, not cut.
#[test]
fn insert_spreadsheet_refuses_a_csv_a_table_cannot_hold() {
use crate::cmd::insert::MAX_TABLE_ROWS;
use wordcraft_doc::table::MAX_COLS;
let mut s = Session::new(Document::new());
// Wider than a table's columns.
let wide = format!("{}\nvalue", "c,".repeat(MAX_COLS));
let e = s.run("insert.spreadsheet", &json!({"csv": wide})).unwrap_err();
assert!(e.to_string().contains(&format!("{MAX_COLS} columns")), "{e}");
// Longer than a table's rows: the records above the limit would be lost quietly.
let long = format!("value\n{}", "value\n".repeat(MAX_TABLE_ROWS));
let e = s.run("insert.spreadsheet", &json!({"csv": long})).unwrap_err();
assert!(e.to_string().contains(&format!("{MAX_TABLE_ROWS} rows")), "{e}");
// A table's own width and length are fine.
let ok = format!("{}\nvalue", "c,".repeat(MAX_COLS - 1));
s.run("insert.spreadsheet", &json!({"csv": ok})).unwrap();
let ok = "value\n".repeat(MAX_TABLE_ROWS);
s.run("insert.spreadsheet", &json!({"csv": ok})).unwrap();
}
/// The inspector's removals delete straight from the document, so they aren't tracked: on a
/// document that tracks changes the text would go with no revision to show for it, and the
/// revision trail would be broken behind the user's back. The removal is refused instead,
/// and the document is left as it was.
#[test]
fn inspect_removals_are_refused_while_the_document_tracks_changes() {
let mut s = Session::new(Document::from_text("Visible text.\nHidden text."));
@@ -2775,6 +3050,7 @@ fn compare_strips_source_revisions_from_adopted_notes() {
author: "Other".into(),
date: "2026-01-01T00:00:00Z".into(),
move_name: None,
date_utc: None,
});
for part in rev.doc.parts.values_mut() {
if part.kind == wordcraft_doc::PartKind::Footnote
+23
View File
@@ -337,6 +337,29 @@ mod tests {
let _ = std::fs::remove_dir_all(&d);
}
/// A document made from a template is created now, not when the template was: it has no
/// creation date until it is saved, so CREATEDATE in it shows today.
#[test]
fn new_from_template_has_no_creation_date_of_its_own_yet() {
let d = scratch("created");
let path = d.join("Dated.dotx");
let mut t = Session::new(wordcraft_doc::Document::new());
t.run("document.setText", &json!({"text": "Dated"})).unwrap();
t.doc.core.created = "2019-05-05T12:00:00Z".into();
crate::io::save_path(&path, &t.doc).unwrap();
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("file.newFromTemplate", &json!({"path": path.to_string_lossy()})).unwrap();
assert_eq!(s.doc.core.created, "");
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy""#, "result": "2019"})).unwrap();
s.run("references.updateFields", &json!({})).unwrap();
assert!(s.doc.plain_text(wordcraft_doc::StoryRef::Body).contains(&crate::cmd::insert::format_date("yyyy")));
// The template itself keeps its date.
let mut again = Session::new(wordcraft_doc::Document::new());
again.run("file.open", &json!({"path": path.to_string_lossy()})).unwrap();
assert_eq!(again.doc.core.created, "2019-05-05T12:00:00Z");
let _ = std::fs::remove_dir_all(&d);
}
/// #3433: a template the platform hands the app takes an untouched blank document's place
/// (`replaceBlank`), as a file `file.open` opens does; otherwise, and without the flag, the
/// new document opens beside the others, as File › New's does. Either way the template on
+6 -3
View File
@@ -284,14 +284,17 @@ fn import_chunk(c: &wordcraft_docx::AltChunk) -> Option<Document> {
|| matches!(ext.as_str(), "mht" | "mhtml")
|| mht::is_mht(b)
{
mht::import(b)
mht::import(b).map_err(|e| log::warn!("altChunk {}: the MHT cannot be read: {e}", c.part)).ok()?
} else if ct.contains("rtf") || ext == "rtf" || b.starts_with(b"{\\rtf") {
rtf::import(b).ok()?
rtf::import(b).map_err(|e| log::warn!("altChunk {}: the RTF cannot be read: {e}", c.part)).ok()?
} else if ct.contains("html") || matches!(ext.as_str(), "html" | "htm" | "xhtml") {
html::import_page(&html::decode_as(b, charset), &|_| None)
.map_err(|e| log::warn!("altChunk {}: the HTML cannot be read: {e}", c.part))
.ok()?
} else if ct == "text/plain" || ext == "txt" {
txt::import(b)
} else {
log::warn!("altChunk {}: its type ({ct}) is not one WordCraft reads", c.part);
return None;
};
// shortcut: pictures fit the chunk's default page, not the section it lands in; fit them there if wide pictures in chunks overflow narrow sections.
@@ -496,7 +499,7 @@ pub fn open_path_in(path: &std::path::Path, password: Option<&str>, region: &wor
// Pictures referenced by a relative path load from beside the HTML file.
let images = LocalImages::new(path.parent().unwrap_or(std::path::Path::new("")));
let html = wordcraft_formats::html::decode(&bytes);
let mut doc = wordcraft_formats::html::import_on(&html, &|src| images.load(src), &region_page(region));
let mut doc = wordcraft_formats::html::import_on(&html, &|src| images.load(src), &region_page(region))?;
fit_pictures(&mut doc);
opened(&mut doc);
return Ok((doc, false));
+46 -1
View File
@@ -98,6 +98,15 @@ pub fn save(ext: &str, doc: &Document, opts: &crate::io::ExportOptions) -> Optio
}
}
/// A UTC date and time (a `Z` or an offset) as Word writes `w:date`: the wall-clock time in the
/// zone `zone` gives for an instant (seconds east of UTC), with a `Z` Word writes but doesn't
/// mean. Word read the UTC dates WordCraft wrote as local time, shifted by the user's offset from
/// UTC (#6851). None for anything else (no zone or no time of day, before 1970, unreadable).
pub(crate) fn word_date(date: &str, zone: impl Fn(u64) -> i64) -> Option<String> {
let utc = u64::try_from(chrono::DateTime::parse_from_rfc3339(date.trim()).ok()?.timestamp()).ok()?;
Some(crate::cmd::iso_from_unix_secs(utc.checked_add_signed(zone(utc))?))
}
/// How a page image is drawn: the printed page, headers and footers at full strength, tracked
/// changes marked as Track Changes Options mark them. One place for `file.exportPng`,
/// `file.strictReport`'s page check and a downloaded page image.
@@ -134,9 +143,45 @@ pub fn render_png(doc: &Document, page: usize, scale: f32, opts: &crate::io::Exp
}
#[cfg(test)]
mod tests {
pub(crate) mod tests {
use super::*;
/// New York in 2026: daylight saving time from 8 March 07:00 UTC to 1 November 06:00 UTC.
pub(crate) fn new_york(t: u64) -> i64 {
if (1_772_953_200..1_793_512_800).contains(&t) { -4 * 3600 } else { -5 * 3600 }
}
/// Word dates `w:date` in local wall-clock time with a `Z`; the change keeps UTC (#6851).
#[test]
fn word_dates_tracked_changes_in_local_time() {
let plus8 = |_| 8 * 3600;
// The issue's edit: 08:33:24 UTC at UTC+8, which Word showed as 8:33 AM.
assert_eq!(word_date("2026-11-16T08:33:24Z", plus8).as_deref(), Some("2026-11-16T16:33:24Z"));
// A date naming its offset is that instant, whatever the zone.
assert_eq!(word_date("2026-11-16T16:33:24+08:00", plus8).as_deref(), Some("2026-11-16T16:33:24Z"));
// West of UTC, the date can go back a day.
assert_eq!(word_date("2026-01-01T03:00:00Z", new_york).as_deref(), Some("2025-12-31T22:00:00Z"));
// The repeated hour: 05:30 and 06:30 UTC are both 01:30 in New York; `dateUtc` keeps them
// apart. Either side of a change of offset takes the offset at that instant.
assert_eq!(word_date("2026-11-01T05:30:00Z", new_york).as_deref(), Some("2026-11-01T01:30:00Z"));
assert_eq!(word_date("2026-11-01T06:30:00Z", new_york).as_deref(), Some("2026-11-01T01:30:00Z"));
assert_eq!(word_date("2026-11-01T04:30:00Z", new_york).as_deref(), Some("2026-11-01T00:30:00Z"));
assert_eq!(word_date("2026-11-01T07:30:00Z", new_york).as_deref(), Some("2026-11-01T02:30:00Z"));
assert_eq!(word_date("2026-03-08T06:30:00Z", new_york).as_deref(), Some("2026-03-08T01:30:00Z"));
assert_eq!(word_date("2026-03-08T07:30:00Z", new_york).as_deref(), Some("2026-03-08T03:30:00Z"));
// Anything else is left as it is: no zone, no time of day, before 1970, not a date.
for date in ["", "2026-11-16T08:33:24", "2026-11-16", "1969-12-31T23:00:00Z", "yesterday", "2026-13-01T00:00:00Z"] {
assert_eq!(word_date(date, plus8), None, "{date:?}");
}
// A hostile zone or a far date doesn't overflow.
for zone in [i64::MAX, i64::MIN] {
let _ = word_date("2026-11-16T08:33:24Z", |_| zone);
}
assert!(word_date("9999-12-31T23:59:59Z", plus8).is_some());
}
/// A page image is the printed page: headers and footers draw at full strength (#6267).
#[test]
fn a_page_image_draws_headers_at_full_strength() {
+1
View File
@@ -16,6 +16,7 @@ pub mod io;
mod io_ext;
pub mod keymap;
pub(crate) mod locale;
pub mod malloc_tuning;
pub mod math_gallery;
pub mod packs;
pub(crate) mod prefs;
+80
View File
@@ -0,0 +1,80 @@
//! glibc malloc tuning for native binaries (adapted from Storytold's `photocraft` #8743).
//!
//! With glibc's defaults, transient large buffers (page render targets, autofit tables, decoded
//! images) raise glibc's dynamic `mmap` and `trim` thresholds (up to 32 MiB on 64-bit), so later
//! heap allocations stay in glibc arenas instead of returning freed pages to the OS. Fixing
//! `MALLOC_TRIM_THRESHOLD_` at 128 KiB (`131072`) disables dynamic threshold growth so freed
//! pages above 128 KiB are returned cleanly while preserving multi-arena allocation throughput.
//!
//! Because glibc reads its malloc environment variables once at process start and mutating the
//! process environment in Rust requires `unsafe` (forbidden workspace-wide) and happens after glibc
//! initialization, [`apply`] re-executes the current executable via `exec` when no malloc tuning
//! variable is already set (keeping PID, argv, `argv[0]`, and environment). Setting any `MALLOC_*`
//! variable or `glibc.malloc.*` tunable opts out.
use std::ffi::OsString;
/// The glibc environment variable [`apply`] sets.
pub const TRIM_THRESHOLD_VAR: &str = "MALLOC_TRIM_THRESHOLD_";
/// Fixed trim threshold (128 KiB, glibc's initial default) to disable dynamic threshold escalation.
pub const TRIM_THRESHOLD: &str = "131072";
/// glibc malloc variables that indicate callers or wrappers already configured malloc tuning.
const MALLOC_VARS: [&str; 5] = [TRIM_THRESHOLD_VAR, "MALLOC_MMAP_THRESHOLD_", "MALLOC_TOP_PAD_", "MALLOC_MMAP_MAX_", "MALLOC_ARENA_MAX"];
/// Whether startup should re-execute with [`TRIM_THRESHOLD_VAR`] set, given an environment reader:
/// true only when no malloc variable or `glibc.malloc.*` tunable is present.
pub fn needs_restart(var: impl Fn(&str) -> Option<OsString>) -> bool {
if MALLOC_VARS.iter().any(|v| var(v).is_some()) {
return false;
}
!var("GLIBC_TUNABLES").is_some_and(|t| t.to_string_lossy().contains("glibc.malloc."))
}
/// Re-execute this binary with [`TRIM_THRESHOLD_VAR`] set when [`needs_restart`] is true.
///
/// Must be called early in `main()` before worker threads start or logs/crash hooks initialize.
/// Returns immediately if tuning variables are already present or if `exec` fails.
#[cfg(all(target_os = "linux", target_env = "gnu"))]
pub fn apply() {
use std::io::Write;
use std::os::unix::process::CommandExt;
if !needs_restart(|k| std::env::var_os(k)) {
return;
}
let Ok(exe) = std::env::current_exe() else { return };
let mut args = std::env::args_os();
let mut cmd = std::process::Command::new(exe);
if let Some(argv0) = args.next() {
cmd.arg0(argv0);
}
// `exec` replaces the current process in place and only returns on error.
let err = cmd.args(args).env(TRIM_THRESHOLD_VAR, TRIM_THRESHOLD).exec();
let _ = writeln!(std::io::stderr(), "wordcraft: could not restart with {TRIM_THRESHOLD_VAR} set ({err})");
}
/// No-op on platforms without Linux glibc.
#[cfg(not(all(target_os = "linux", target_env = "gnu")))]
pub fn apply() {}
#[cfg(test)]
mod tests {
use super::*;
fn env<'a>(vars: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<OsString> + 'a {
move |k| vars.iter().find(|(n, _)| *n == k).map(|(_, v)| OsString::from(v))
}
#[test]
fn restarts_only_without_malloc_tuning() {
assert!(needs_restart(env(&[])));
assert!(needs_restart(env(&[("HOME", "/home/a"), ("GLIBC_TUNABLES", "glibc.cpu.hwcaps=-AVX2")])));
assert!(!needs_restart(env(&[(TRIM_THRESHOLD_VAR, TRIM_THRESHOLD)])), "re-executed process stops");
assert!(!needs_restart(env(&[(TRIM_THRESHOLD_VAR, "")])), "any explicit value opts out");
assert!(!needs_restart(env(&[("MALLOC_MMAP_THRESHOLD_", "1048576")])));
assert!(!needs_restart(env(&[("MALLOC_ARENA_MAX", "2")])));
assert!(!needs_restart(env(&[("GLIBC_TUNABLES", "glibc.malloc.trim_threshold=0")])));
}
}
+5
View File
@@ -149,6 +149,8 @@ pub struct Session {
/// ([`Session::why_disabled`]): computed once per document, revision and author instead of
/// for every button on every frame.
protect_facts: std::sync::Mutex<Option<((u64, u64, String), crate::cmd::protect::Facts)>>,
/// Cached result of [`crate::cmd::format::cached_state`] and the state key it was made for.
pub(crate) format_state: std::sync::Mutex<Option<crate::cmd::format::StateCache>>,
/// How many times the document's body was replaced under the same [`Self::document_id`]
/// (`document.setText`, version restore, compare, Undo/Redo). It is the body's IME
/// replacement epoch: a composition must not survive the swap, even when the new body has
@@ -228,6 +230,9 @@ pub struct Session {
pub editing_lang: Option<String>,
/// Editing inside an equation: which one and the caret in it.
pub math: Option<MathEdit>,
/// The running command left the equation being edited before it ran (see [`Session::run`]),
/// so Left/Right don't open the equation the caret now sits next to (#4138).
pub(crate) math_left: bool,
/// Equations are typed in LaTeX rather than the linear format.
pub math_latex: bool,
/// Text typed into equations is normal (non-math) text.

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