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

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

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

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

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

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

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

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

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

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

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

Resolved the only conflict, in crates/layout/src/tests.rs, by keeping the PR's a_body_text_frame_respects_its_anchors test together with main's env_hash_memoizes_styles_and_invalidates_on_change and evict_unused_caps_stale_entries_across_repeated_edits tests, and closing the first test's brace. No conflict markers remain and cargo fmt --check is clean. I ran two of the three tests and both pass; I did not run the third (evict_unused_caps_stale_entries_across_repeated_edits) or the rest of the layout suite.
2026-12-03 01:41:20 +00:00
batistalucasv 1a05479d99 fix(keys): use fired modifiers for paste-format fallback across windows 2026-12-02 22:28:50 -03:00
batistalucasv fc0acd93b9 fix(keys): preserve paste suppression order and Mod+Shift+V origin 2026-12-02 22:28:50 -03:00
batistalucasv 5c2e7eb296 fix(keys): ignore paired browser paste after Mod+Shift+V (#7608) 2026-12-02 22:28:50 -03:00
batistalucasv cc7f9e2688 test(keys): restore the_ignored_paste_event_never_reaches_an_open_equation test (#7317) 2026-12-02 22:27:11 -03:00
autocraft-bot[bot] 3c5aeef936 Merge pull request #6732 2026-12-03 01:20:17 +00:00
autocraft-bot[bot] bcf2aa3b03 The formats crate's tests failed to compile on merged main: main's craft
The formats crate's tests failed to compile on merged main: main's craft-libs update (rev d73e274) puts craft_ods::testing behind craft-ods's test-support feature, and nothing enables it. The tests in crates/formats/src/sheet.rs now use a small local spreadsheet() helper that builds the same .ods package with craft_odf::PackageWriter (craft-odf is already a normal dependency); no dependency or Cargo.toml change, and no test or assertion weakened. cargo test -p wordcraft-formats sheet passes (9 tests), clippy -p wordcraft-formats --all-targets -D warnings is clean, and rustfmt --check on sheet.rs is clean. The CI logs were empty, so I did not run the Print job's own commands (cargo test and clippy on wordcraft and wordcraft-ui-egui), and the Print failure may have another cause.
2026-12-03 01:08:48 +00:00
autocraft-bot[bot] 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
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 78b0a6929c Layout: the right-tab rule applies to right tabs only, and not beside a float
A decimal tab keeps main's fit: its digits after the point run on to the right
of the stop, so taking text up to the stop let a number run past the margin.
Where a floating object narrows the line, text after a right tab keeps to the
narrowed edge instead of running into the object.
2026-12-02 16:05:51 +03:00
dfgodvan 870bec1839 Merge main into fix/right-tab-beyond-indent 2026-12-02 16:02:02 +03:00
dfgodvan e819a03435 Layout: the list-number kerning test loads the test fonts; Word for Mac in the comments
The test now uses the test fonts, whose kerning pairs make it fail without the
change whatever fonts the machine has. The comments name Word for Mac, where the
measurement was made, as the description does; the Kerning parity row mentions
list numbers.
2026-12-02 15:56:26 +03:00
dfgodvan 77c0a29922 Merge main into w1/list-number-no-kern
# Conflicts:
#	crates/layout/src/para/paragraph.rs
#	docs/layout-parity.md
2026-12-02 15:55:52 +03:00
dfgodvan d66a7d3bf9 Layout: the layout cache follows a change of compatibility mode
Paragraph layout depends on the compatibility mode (widow control in table
cells before Word 2013 layout), so the mode is part of the cache environment.
2026-12-02 15:52:51 +03:00
dfgodvan 5efc89e5ea Tests: cells of a table without a style drop widow control before Word 2013 layout too
The cell layout gives every cell's paragraphs a cell text environment, an empty
one when the table has no style (boxes.rs), so the compatibility-mode rule
applies to tables without w:tblStyle as well.
2026-12-02 15:51:51 +03:00
dfgodvan 010134fb8e Merge main into fix/legacy-tables-at-page-foot
# Conflicts:
#	crates/layout/src/tests.rs
2026-12-02 15:51:46 +03:00
codeiouandClaude Code 08b8d71ece docs: distinguish deferred input replies from completed edits
A deferred control reply can arrive during the final input pass, before
that pass updates the document. Describe the observed deferral without
promising that the edit has already been applied. Keep the queued typing
example and tell clients to check the resulting state without replaying
an edit merely because its effect is not yet visible.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-21 06:40:13 +07:00
Michael Higgins ce2f7789f4 Merge storytold/wordcraft main into fix/6516-toggle-first-character 2026-11-20 17:05:13 -05:00
Michael Higgins 539d9ce9d6 Merge storytold/wordcraft main into fix/6517-typographic-apostrophe-word 2026-11-20 17:05:09 -05:00
Michael Higgins ccf6340262 Merge storytold/wordcraft main into fix/6517-typographic-apostrophe-word 2026-11-20 09:45:38 -05:00
dfgodvan 41e2164cd0 Merge branch 'main' into w1/list-number-no-kern 2026-11-19 23:22:36 +03:00
dfgodvan 861bed3fdd Merge main into fix/legacy-tables-at-page-foot 2026-11-19 23:17:29 +03:00
jayzed80 6010893891 Merge branch 'agyreview/6446' into HEAD
# Conflicts:
#	crates/ui-egui/src/app/commands.rs
2026-11-19 16:25:25 +00:00
jayzed80 8427de0edb Address review: require explicit path for copies and compare host copy basename (#6131) 2026-11-19 16:14:05 +00:00
jayzed80 1789fd7b4d #6463: an all-blank row keeps its TR and cells in a tagged table 2026-11-19 16:07:59 +00:00
jayzed80 83676d584a Merge remote-tracking branch 'upstream/main' into fix/pdf-table-tags-6463 2026-11-19 15:49:47 +00:00
jayzed80 ec29711caf Merge branch 'agyreview/6628' into HEAD
# Conflicts:
#	docs/layout-parity.md
2026-11-19 10:25:31 +00:00
jayzed80 2bce6ed613 Docs: qualify wrapped-tab float-skip parity entry with 50-span limit (#6577) 2026-11-19 10:09:54 +00:00
jayzed80 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 2e9699c519 Merge remote-tracking branch 'upstream/main' into HEAD
# Conflicts:
#	docs/layout-parity.md
2026-11-18 21:30:04 +00: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 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
Martin Ball af9dca95de Merge branch 'main' into fix/right-tab-beyond-indent 2026-11-17 16:59:34 +01:00
Mauro MazzieriandClaude Opus 5.5 6eb03bf4ea Merge storytold/wordcraft main
Resolves the docs/layout-parity.md status line and revision history.

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

Floats and booleans read their values again, dates and times read as
ISO 8601 (a duration's days counted as hours), strings, percentages
and currencies keep their text, and a covered cell is blank. A value
that is not a valid date, time or duration falls back to the text.
2026-11-14 13:12:47 -08:00
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 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 <[email protected]>
2026-11-13 11:08:43 -05:00
Michael HigginsandClaude Opus 5.5 824a5e2c1d #6516: pin that a selection from an empty paragraph follows its first text
Word ignores an empty paragraph's mark at the start of the selection and
decides from the first text character (review on #6519).

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 10:36:33 +01:00
104 changed files with 10049 additions and 733 deletions
Generated
+111 -125
View File
@@ -1173,7 +1173,7 @@ dependencies = [
[[package]]
name = "craft"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"craft-automation",
"craft-behavior",
@@ -1214,7 +1214,7 @@ dependencies = [
[[package]]
name = "craft-appkit"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"block2 0.6.2",
"objc2 0.6.5",
@@ -1226,7 +1226,7 @@ dependencies = [
[[package]]
name = "craft-atomic"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"rustix 1.1.6",
]
@@ -1234,7 +1234,7 @@ dependencies = [
[[package]]
name = "craft-automation"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"base64 0.23.1",
"craft-behavior",
@@ -1259,7 +1259,7 @@ dependencies = [
[[package]]
name = "craft-behavior"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"accesskit",
"bitflags 2.13.2",
@@ -1277,7 +1277,7 @@ dependencies = [
[[package]]
name = "craft-browse"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"craft-behavior",
"craft-docpath",
@@ -1295,12 +1295,12 @@ dependencies = [
[[package]]
name = "craft-cfb"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
[[package]]
name = "craft-cloud-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"egui",
]
@@ -1308,7 +1308,7 @@ dependencies = [
[[package]]
name = "craft-cms"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"md-5",
"rayon",
@@ -1317,12 +1317,12 @@ dependencies = [
[[package]]
name = "craft-codepage"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
[[package]]
name = "craft-color"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"serde",
]
@@ -1330,7 +1330,7 @@ dependencies = [
[[package]]
name = "craft-color-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"craft-behavior",
"craft-cms",
@@ -1350,7 +1350,7 @@ dependencies = [
[[package]]
name = "craft-control"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"craft-control-protocol",
"craft-platform",
@@ -1361,7 +1361,7 @@ dependencies = [
[[package]]
name = "craft-control-protocol"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"getrandom 0.3.4",
"serde_json",
@@ -1371,7 +1371,7 @@ dependencies = [
[[package]]
name = "craft-dds"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"rayon",
]
@@ -1379,7 +1379,7 @@ dependencies = [
[[package]]
name = "craft-dialogs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"block2 0.6.2",
"craft-appkit",
@@ -1405,7 +1405,7 @@ dependencies = [
[[package]]
name = "craft-doc-binary"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"chrono",
"craft-cfb",
@@ -1422,7 +1422,7 @@ dependencies = [
[[package]]
name = "craft-docpath"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"serde",
]
@@ -1430,7 +1430,7 @@ dependencies = [
[[package]]
name = "craft-docx"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"base64 0.23.1",
"chrono",
@@ -1450,7 +1450,7 @@ dependencies = [
[[package]]
name = "craft-draw"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"craft-behavior",
"craft-color-ui",
@@ -1469,7 +1469,7 @@ dependencies = [
[[package]]
name = "craft-drawingml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"chrono",
"craft-xml",
@@ -1481,7 +1481,7 @@ dependencies = [
[[package]]
name = "craft-flow"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"craft-wordmodel",
"image",
@@ -1491,7 +1491,7 @@ dependencies = [
[[package]]
name = "craft-font-catalog"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"fontique",
"harfrust 0.13.3",
@@ -1506,7 +1506,7 @@ dependencies = [
[[package]]
name = "craft-font-manager"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"craft-behavior",
"craft-font-catalog",
@@ -1525,7 +1525,7 @@ dependencies = [
[[package]]
name = "craft-font-os-windows"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"windows-registry",
"windows-sys 0.61.2",
@@ -1534,7 +1534,7 @@ dependencies = [
[[package]]
name = "craft-font-store"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"cap-primitives",
"craft-atomic",
@@ -1557,7 +1557,7 @@ dependencies = [
[[package]]
name = "craft-font-subset"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"brotli 9.1.3",
"harfbuzz-subset-sys",
@@ -1570,7 +1570,7 @@ dependencies = [
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"craft-font-subset",
]
@@ -1578,7 +1578,7 @@ dependencies = [
[[package]]
name = "craft-gpu"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"egui-wgpu",
"log",
@@ -1590,7 +1590,7 @@ dependencies = [
[[package]]
name = "craft-host"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"bitflags 2.13.2",
"craft-i18n",
@@ -1603,7 +1603,7 @@ dependencies = [
[[package]]
name = "craft-html"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"craft-codepage",
"craft-flow",
@@ -1616,7 +1616,7 @@ dependencies = [
[[package]]
name = "craft-i18n"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"brotli 9.1.3",
"brotli-decompressor 6.3.1",
@@ -1646,7 +1646,7 @@ dependencies = [
[[package]]
name = "craft-image-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"craft-dds",
"craft-jpeg",
@@ -1673,7 +1673,7 @@ dependencies = [
[[package]]
name = "craft-imaging"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"craft-behavior",
"craft-color-ui",
@@ -1691,7 +1691,7 @@ dependencies = [
[[package]]
name = "craft-jpeg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"thiserror 2.0.21",
]
@@ -1699,7 +1699,7 @@ dependencies = [
[[package]]
name = "craft-keymap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"craft-host",
"craft-i18n",
@@ -1714,7 +1714,7 @@ dependencies = [
[[package]]
name = "craft-latex"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"craft-flow",
"craft-math",
@@ -1725,7 +1725,7 @@ dependencies = [
[[package]]
name = "craft-markdown"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"craft-flow",
"craft-html",
@@ -1735,7 +1735,7 @@ dependencies = [
[[package]]
name = "craft-math"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"craft-xml",
"roxmltree",
@@ -1745,7 +1745,7 @@ dependencies = [
[[package]]
name = "craft-mcp-server"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"serde_json",
]
@@ -1753,7 +1753,7 @@ dependencies = [
[[package]]
name = "craft-menu"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"craft-behavior",
"craft-host",
@@ -1771,7 +1771,7 @@ dependencies = [
[[package]]
name = "craft-metadata"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"brotli-decompressor 6.3.1",
"chrono",
@@ -1783,7 +1783,7 @@ dependencies = [
[[package]]
name = "craft-metafile"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"encoding_rs",
"image",
@@ -1794,7 +1794,7 @@ dependencies = [
[[package]]
name = "craft-mime"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"chardetng",
"chrono",
@@ -1805,7 +1805,7 @@ dependencies = [
[[package]]
name = "craft-nightly"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"uds_windows",
"winsafe",
@@ -1814,7 +1814,7 @@ dependencies = [
[[package]]
name = "craft-odf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"aes",
"base64 0.23.1",
@@ -1840,7 +1840,7 @@ dependencies = [
[[package]]
name = "craft-ods"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"craft-odf",
"craft-sheet",
@@ -1851,7 +1851,7 @@ dependencies = [
[[package]]
name = "craft-offcrypto"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"aes",
"base64 0.23.1",
@@ -1868,7 +1868,7 @@ dependencies = [
[[package]]
name = "craft-opc"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"craft-xml",
"craft-zip",
@@ -1879,7 +1879,7 @@ dependencies = [
[[package]]
name = "craft-pages"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"craft-behavior",
"craft-keymap",
@@ -1895,7 +1895,7 @@ dependencies = [
[[package]]
name = "craft-pdf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"krilla",
"serde",
@@ -1905,7 +1905,7 @@ dependencies = [
[[package]]
name = "craft-platform"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"arboard",
"async-channel",
@@ -1943,7 +1943,7 @@ dependencies = [
[[package]]
name = "craft-print"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"craft-behavior",
"craft-host",
@@ -1967,7 +1967,7 @@ dependencies = [
[[package]]
name = "craft-proof"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"log",
"miniz_oxide 0.9.1",
@@ -1978,7 +1978,7 @@ dependencies = [
[[package]]
name = "craft-quit"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"dispatch2",
"egui",
@@ -1991,7 +1991,7 @@ dependencies = [
[[package]]
name = "craft-review"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"base64 0.23.1",
"craft-behavior",
@@ -2010,7 +2010,7 @@ dependencies = [
[[package]]
name = "craft-rtf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"craft-codepage",
"craft-flow",
@@ -2023,7 +2023,7 @@ dependencies = [
[[package]]
name = "craft-settings"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"craft-atomic",
"craft-host",
@@ -2040,17 +2040,17 @@ dependencies = [
[[package]]
name = "craft-sheet"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
[[package]]
name = "craft-ssip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
[[package]]
name = "craft-svg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"craft-xml",
"flate2",
@@ -2067,7 +2067,7 @@ dependencies = [
[[package]]
name = "craft-table"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"craft-behavior",
"craft-keymap",
@@ -2079,7 +2079,7 @@ dependencies = [
[[package]]
name = "craft-text"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2103,7 +2103,7 @@ dependencies = [
[[package]]
name = "craft-theme"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"bitflags 2.13.2",
"craft-tracked",
@@ -2118,7 +2118,7 @@ dependencies = [
[[package]]
name = "craft-theme-store"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"craft-atomic",
"craft-behavior",
@@ -2133,7 +2133,7 @@ dependencies = [
[[package]]
name = "craft-tiff"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -2143,7 +2143,7 @@ dependencies = [
[[package]]
name = "craft-time"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -2152,7 +2152,7 @@ dependencies = [
[[package]]
name = "craft-timeline"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"craft-behavior",
"craft-keymap",
@@ -2167,12 +2167,12 @@ dependencies = [
[[package]]
name = "craft-tracked"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"craft-cloud-ui",
"craft-ui-canvas",
@@ -2186,7 +2186,7 @@ dependencies = [
[[package]]
name = "craft-ui-canvas"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"craft-behavior",
"craft-font-catalog",
@@ -2203,7 +2203,7 @@ dependencies = [
[[package]]
name = "craft-ui-contract"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"accesskit",
"craft-behavior",
@@ -2241,7 +2241,7 @@ dependencies = [
[[package]]
name = "craft-ui-macros"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"proc-macro-crate",
"proc-macro2",
@@ -2252,7 +2252,7 @@ dependencies = [
[[package]]
name = "craft-ui-panels"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2270,7 +2270,7 @@ dependencies = [
[[package]]
name = "craft-ui-patterns"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2291,7 +2291,7 @@ dependencies = [
[[package]]
name = "craft-ui-shell"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2312,7 +2312,7 @@ dependencies = [
[[package]]
name = "craft-ui-test-kit"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2323,7 +2323,7 @@ dependencies = [
[[package]]
name = "craft-ui-widgets"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2342,7 +2342,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"base64 0.22.1",
"chrono",
@@ -2374,7 +2374,7 @@ dependencies = [
[[package]]
name = "craft-web-api"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"js-sys",
"serde_json",
@@ -2385,7 +2385,7 @@ dependencies = [
[[package]]
name = "craft-web-host"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"craft-host",
"craft-platform",
@@ -2397,7 +2397,7 @@ dependencies = [
[[package]]
name = "craft-win32"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"winsafe",
]
@@ -2405,7 +2405,7 @@ dependencies = [
[[package]]
name = "craft-window"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"craft-appkit",
"craft-atomic",
@@ -2437,7 +2437,7 @@ dependencies = [
[[package]]
name = "craft-wordmodel"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"base64 0.23.1",
"craft-math",
@@ -2451,7 +2451,7 @@ dependencies = [
[[package]]
name = "craft-xls"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"craft-cfb",
"craft-sheet",
@@ -2464,7 +2464,7 @@ dependencies = [
[[package]]
name = "craft-xlsx"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"craft-drawingml",
"craft-opc",
@@ -2476,7 +2476,7 @@ dependencies = [
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"quick-xml 0.41.0",
"serde",
@@ -2486,7 +2486,7 @@ dependencies = [
[[package]]
name = "craft-zip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"flate2",
"thiserror 2.0.21",
@@ -2842,7 +2842,7 @@ checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
[[package]]
name = "ecolor"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
source = "git+https://github.com/storytold/egui.git?rev=07b014397ff2ff86a3570e472552d527be9e588a#07b014397ff2ff86a3570e472552d527be9e588a"
dependencies = [
"bytemuck",
"emath",
@@ -2875,7 +2875,7 @@ dependencies = [
[[package]]
name = "eframe"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
source = "git+https://github.com/storytold/egui.git?rev=07b014397ff2ff86a3570e472552d527be9e588a#07b014397ff2ff86a3570e472552d527be9e588a"
dependencies = [
"ahash",
"bytemuck",
@@ -2910,7 +2910,7 @@ dependencies = [
[[package]]
name = "egui"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
source = "git+https://github.com/storytold/egui.git?rev=07b014397ff2ff86a3570e472552d527be9e588a#07b014397ff2ff86a3570e472552d527be9e588a"
dependencies = [
"accesskit",
"ahash",
@@ -2929,7 +2929,7 @@ dependencies = [
[[package]]
name = "egui-wgpu"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
source = "git+https://github.com/storytold/egui.git?rev=07b014397ff2ff86a3570e472552d527be9e588a#07b014397ff2ff86a3570e472552d527be9e588a"
dependencies = [
"ahash",
"bytemuck",
@@ -2948,7 +2948,7 @@ dependencies = [
[[package]]
name = "egui-winit"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
source = "git+https://github.com/storytold/egui.git?rev=07b014397ff2ff86a3570e472552d527be9e588a#07b014397ff2ff86a3570e472552d527be9e588a"
dependencies = [
"accesskit_winit",
"arboard",
@@ -2974,7 +2974,7 @@ dependencies = [
[[package]]
name = "egui_extras"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
source = "git+https://github.com/storytold/egui.git?rev=07b014397ff2ff86a3570e472552d527be9e588a#07b014397ff2ff86a3570e472552d527be9e588a"
dependencies = [
"ahash",
"egui",
@@ -2987,7 +2987,7 @@ dependencies = [
[[package]]
name = "egui_glow"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
source = "git+https://github.com/storytold/egui.git?rev=07b014397ff2ff86a3570e472552d527be9e588a#07b014397ff2ff86a3570e472552d527be9e588a"
dependencies = [
"bytemuck",
"egui",
@@ -3000,7 +3000,7 @@ dependencies = [
[[package]]
name = "egui_kittest"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
source = "git+https://github.com/storytold/egui.git?rev=07b014397ff2ff86a3570e472552d527be9e588a#07b014397ff2ff86a3570e472552d527be9e588a"
dependencies = [
"dify",
"eframe",
@@ -3026,7 +3026,7 @@ checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
[[package]]
name = "emath"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
source = "git+https://github.com/storytold/egui.git?rev=07b014397ff2ff86a3570e472552d527be9e588a#07b014397ff2ff86a3570e472552d527be9e588a"
dependencies = [
"bytemuck",
]
@@ -3107,7 +3107,7 @@ dependencies = [
[[package]]
name = "epaint"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
source = "git+https://github.com/storytold/egui.git?rev=07b014397ff2ff86a3570e472552d527be9e588a#07b014397ff2ff86a3570e472552d527be9e588a"
dependencies = [
"ahash",
"bytemuck",
@@ -3133,7 +3133,7 @@ dependencies = [
[[package]]
name = "epaint_default_fonts"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
source = "git+https://github.com/storytold/egui.git?rev=07b014397ff2ff86a3570e472552d527be9e588a#07b014397ff2ff86a3570e472552d527be9e588a"
dependencies = [
"brotli 9.1.3",
"brotli-decompressor 6.3.1",
@@ -3866,7 +3866,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
[[package]]
name = "hayro-cmap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"brotli 8.0.4",
"hayro-postscript",
@@ -3875,7 +3875,7 @@ dependencies = [
[[package]]
name = "hayro-interpret"
version = "0.7.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"bitflags 2.13.2",
"hayro-cmap",
@@ -3893,7 +3893,7 @@ dependencies = [
[[package]]
name = "hayro-jbig2"
version = "0.3.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"fearless_simd",
"hayro-ccitt",
@@ -3911,12 +3911,12 @@ dependencies = [
[[package]]
name = "hayro-postscript"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
[[package]]
name = "hayro-syntax"
version = "0.7.2"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"flate2",
"hayro-ccitt",
@@ -4645,7 +4645,7 @@ dependencies = [
[[package]]
name = "krilla"
version = "0.8.2"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"base64 0.22.1",
"bumpalo",
@@ -4784,7 +4784,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
[[package]]
name = "linesweeper"
version = "0.5.0"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
dependencies = [
"arrayvec",
"kurbo",
@@ -8454,19 +8454,6 @@ dependencies = [
"wayland-scanner",
]
[[package]]
name = "wayland-protocols-plasma"
version = "0.3.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b6d8cf1eb2c1c31ed1f5643c88a6e53538129d4af80030c8cabd1f9fa884d91"
dependencies = [
"bitflags 2.13.2",
"wayland-backend",
"wayland-client",
"wayland-protocols",
"wayland-scanner",
]
[[package]]
name = "wayland-protocols-wlr"
version = "0.3.12"
@@ -8991,7 +8978,7 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "winit"
version = "0.30.13"
source = "git+https://github.com/storytold/winit.git?rev=0dfcec0eb62fda5904137a63a6dd0c3d83295f45#0dfcec0eb62fda5904137a63a6dd0c3d83295f45"
source = "git+https://github.com/storytold/winit.git?rev=3fd7ae64762f82a73b78bd24f453f82c4291067d#3fd7ae64762f82a73b78bd24f453f82c4291067d"
dependencies = [
"ahash",
"android-activity",
@@ -9030,7 +9017,6 @@ dependencies = [
"wayland-backend",
"wayland-client",
"wayland-protocols",
"wayland-protocols-plasma",
"web-sys",
"web-time",
"windows-sys 0.52.0",
@@ -10051,19 +10037,19 @@ dependencies = [
[[patch.unused]]
name = "egui_demo_lib"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
source = "git+https://github.com/storytold/egui.git?rev=07b014397ff2ff86a3570e472552d527be9e588a#07b014397ff2ff86a3570e472552d527be9e588a"
[[patch.unused]]
name = "egui_inspection"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
source = "git+https://github.com/storytold/egui.git?rev=07b014397ff2ff86a3570e472552d527be9e588a#07b014397ff2ff86a3570e472552d527be9e588a"
[[patch.unused]]
name = "egui_system_font_provider"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
source = "git+https://github.com/storytold/egui.git?rev=07b014397ff2ff86a3570e472552d527be9e588a#07b014397ff2ff86a3570e472552d527be9e588a"
[[patch.unused]]
name = "hayro"
version = "0.7.1"
source = "git+https://github.com/storytold/craft-libs?rev=d73e274a01408ef433a291a667e6014937d72165#d73e274a01408ef433a291a667e6014937d72165"
source = "git+https://github.com/storytold/craft-libs?rev=98a66a56550b027cc8cdcd689ab7d3239c71427e#98a66a56550b027cc8cdcd689ab7d3239c71427e"
+54 -54
View File
@@ -37,22 +37,22 @@ wordcraft-pdf = { path = "crates/pdf" }
# reads the ca-valencia pack), #589 (French elision suggestions first), #497 (flag-based
# compounding), #496 (review follow-ups, en-AU) and the merged #482–#490/#495 stack; the font
# store's `language-pack` kind is #486 (CP4.1).
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "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 = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", default-features = false }
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "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"] }
@@ -85,28 +85,28 @@ wuff = "0.2.9"
brotli-decompressor = "5"
vello_cpu = "0.2"
image = { version = "0.25", default-features = false }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", default-features = false, features = ["write"] }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "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 = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", features = ["doc"] }
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", features = ["text"] }
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", features = ["flow"] }
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", features = ["detect"] }
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "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"
@@ -174,27 +174,27 @@ debug = 0
# The framework's patches, which Cargo does not carry over to dependents: its vendored crates from craft-libs,
# and the egui and winit forks it builds with.
[patch.crates-io]
krilla = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
hayro = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
emath = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
winit = { git = "https://github.com/storytold/winit.git", rev = "0dfcec0eb62fda5904137a63a6dd0c3d83295f45" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "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" }
+4
View File
@@ -74,6 +74,10 @@ winit = { version = "0.30", default-features = false, features = ["x11", "waylan
x11-dl = "2.21"
xkbcommon-dl = { version = "0.4.2", features = ["x11"] }
# Name the window supplied by eframe's attachment hook on targets that otherwise use winit indirectly.
[target.'cfg(any(target_os = "macos", windows))'.dependencies]
winit = { version = "0.30", default-features = false }
[target.'cfg(windows)'.dependencies]
# The update helper: a copy of this program started with `--finish-update`
# (`craft::update::self_update::finish`).
+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()));
}
}
+234 -187
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
@@ -616,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.
@@ -653,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({
@@ -673,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"))]
@@ -705,147 +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());
// Drawn by the processor (WARP, llvmpipe; #2221), animations that follow the system stop.
if let Some(state) = &cc.wgpu_render_state {
let info = state.adapter.get_info();
let software = info.device_type == eframe::wgpu::DeviceType::Cpu;
if software {
log::warn!("graphics: drawing in software on {} ({:?}): animations that follow the system are off", info.name, info.backend);
}
app.set_software_drawing(software);
app.set_software_drawing(software);
}
// PLAN: writer note 9 puts `with_settings` after `with_control`; it comes first here because
// the region check below reads the saved region the settings apply.
if std::env::var("WORDCRAFT_FILE_DIALOG").is_ok_and(|v| v.trim().eq_ignore_ascii_case("builtin")) {
app = app.with_fallback_chooser(true);
}
if nightly {
// The Launcher installs Nightly; Help › Check for Updates says so instead.
app.use_launcher_updates();
} else {
app.set_startup_update_check(true);
// After the preferences, so the reason it gives is in the interface language.
if updates_unsafe {
app.disable_self_update();
}
// PLAN: writer note 9 puts `with_settings` after `with_control`; it comes first here because
// the region check below reads the saved region the settings apply.
if std::env::var("WORDCRAFT_FILE_DIALOG").is_ok_and(|v| v.trim().eq_ignore_ascii_case("builtin")) {
app = app.with_fallback_chooser(true);
}
// Language packs from the suite's font store; an Install click is the person's own.
// Nightly keeps its own store in the profile, so a pack installed there is not a
// change to the stable apps' shared fonts.
match launch_profile::current().root() {
Some(root) => wordcraft_engine::packs::use_font_store_in(root.join("FontStore"), true),
None => {
wordcraft_engine::packs::use_font_store(true);
}
if nightly {
// The Launcher installs Nightly; Help › Check for Updates says so instead.
app.use_launcher_updates();
} else {
app.set_startup_update_check(true);
// After the preferences, so the reason it gives is in the interface language.
if updates_unsafe {
app.disable_self_update();
}
}
// A region chosen in File › Options replaces the system's for the first blank
// document too (#838).
if !sample && app.session.prefs.region.is_some() {
let doc = app.session.blank_document();
app.replace_startup_document(doc);
}
app.tell_about_font_downloads();
if prefs::enabled()
&& let Some(dir) = wordcraft_control_key::settings_dir()
{
let ctx = ctx.clone();
if let Err(e) = app.session.enable_recovery(dir.join("recovery"), Arc::new(move || ctx.request_repaint())) {
log::warn!("local recovery unavailable: {e}");
}
// Language packs from the suite's font store; an Install click is the person's own.
// Nightly keeps its own store in the profile, so a pack installed there is not a
// change to the stable apps' shared fonts.
match launch_profile::current().root() {
Some(root) => wordcraft_engine::packs::use_font_store_in(root.join("FontStore"), true),
None => {
wordcraft_engine::packs::use_font_store(true);
}
}
let mut control_server = None;
if !nightly
&& let Some(port) = control.port
&& let Some((rx, started)) = control_server::start(&control, port, WindowHost::of(&ctx), wordcraft_control_key::settings_dir().as_deref())
{
app = app.with_control(ControlChannel::new(rx));
control_server = Some(started);
}
// Nothing to open (no files, no sample, no control channel driving the editor): start
// on File › Home, as Word does (#766), unless the Start screen option is off. Files
// the OS hands over later open on top of it and close it.
if files.is_empty() && other_files.is_empty() && !sample && control.port.is_none() {
app.start_screen();
}
// A Word template named here starts a new document based on it (#3433).
for f in files {
if let Err(e) = app.open_from_platform(&f, None) {
app.report_open_failure(&f, &e);
}
// A region chosen in File › Options replaces the system's for the first blank
// document too (#838).
if !sample && app.session.prefs.region.is_some() {
let doc = app.session.blank_document();
app.replace_startup_document(doc);
}
app.tell_about_font_downloads();
if prefs::enabled()
&& let Some(dir) = wordcraft_control_key::settings_dir()
{
let ctx = ctx.clone();
if let Err(e) = app.session.enable_recovery(dir.join("recovery"), Arc::new(move || ctx.request_repaint())) {
log::warn!("local recovery unavailable: {e}");
}
}
let mut control_server = None;
if !nightly
&& let Some(port) = control.port
&& let Some((rx, started)) =
control_server::start(&control, port, WindowHost::of(&ctx), wordcraft_control_key::settings_dir().as_deref())
{
app = app.with_control(ControlChannel::new(rx));
control_server = Some(started);
}
// Nothing to open (no files, no sample, no control channel driving the editor): start
// on File › Home, as Word does (#766), unless the Start screen option is off. Files
// the OS hands over later open on top of it and close it.
if files.is_empty() && other_files.is_empty() && !sample && control.port.is_none() {
app.start_screen();
}
// A Word template named here starts a new document based on it (#3433).
for f in files {
if let Err(e) = app.open_from_platform(&f, None) {
app.report_open_failure(&f, &e);
}
}
for f in other_files {
open_non_unicode(&mut app, &f);
}
// The personal agent files, the session record and the control token all live in the
// profile; the app's own services are built with the nightly rule in mind.
if let Some(warning) = &session_health_warning {
app.status_long(warning.clone());
}
if previous_nightly_unclean {
app.status_long(
}
for f in other_files {
open_non_unicode(&mut app, &f);
}
// The personal agent files, the session record and the control token all live in the
// profile; the app's own services are built with the nightly rule in mind.
if let Some(warning) = &session_health_warning {
app.status_long(warning.clone());
}
if previous_nightly_unclean {
app.status_long(
"The previous WordCraft Nightly session did not finish normally. You can report a problem from Help › About. No diagnostics have been sent.",
);
noticed_in_window.store(true, std::sync::atomic::Ordering::Relaxed);
}
Ok(Box::new(App {
#[cfg(target_os = "macos")]
native_menu: native_menu::install(&ctx, &app),
app,
panels,
drops,
settings,
spool,
control: control_server,
exit: Some(Box::new(move || {
nightly_session::finish_once(&session_for_exit, noticed_for_exit.load(std::sync::atomic::Ordering::Relaxed));
})),
}))
}),
);
noticed_in_window.store(true, std::sync::atomic::Ordering::Relaxed);
}
Ok(Box::new(App {
#[cfg(target_os = "macos")]
native_menu: native_menu::install(&ctx, &app),
app,
panels,
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.
@@ -1009,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;
@@ -1056,6 +1102,7 @@ mod smoke {
native_menu: None,
app,
panels,
document_windows: Default::default(),
drops,
settings,
spool,
+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");
}
}
+17 -1
View File
@@ -619,7 +619,8 @@ impl Paragraph {
/// The word around `off` (double-click): (start, end) without trailing space.
pub fn word_at(&self, off: usize) -> (usize, usize) {
let off = self.clamp(off);
let is_w = |c: char| crate::bidi::is_word_char(c);
// Word's word unit takes a typographic apostrophe (’) like `'`, at either end too (#6517).
let is_w = |c: char| crate::bidi::is_word_char(c) || c == '’';
let mut a = off;
for (i, c) in self.text.get(..off).unwrap_or("").char_indices().rev() {
if !is_w(c) {
@@ -852,6 +853,21 @@ mod tests {
assert_eq!(p.prev_boundary(0), 0);
}
#[test]
fn word_at_takes_a_typographic_apostrophe_like_a_straight_one() {
// Byte offsets: `’` is three bytes. Word: `don’t ` (#6517).
let p = Paragraph::with_text("don’t stop", CharProps::default());
assert_eq!(p.word_at(1), (0, 8));
assert_eq!(p.word_at(2), (0, 8));
let p = Paragraph::with_text("the dogs’ bone", CharProps::default());
assert_eq!(p.word_at(5), (4, 12));
let p = Paragraph::with_text("’tis here", CharProps::default());
assert_eq!(p.word_at(3), (0, 7));
assert_eq!(p.word_at(4), (0, 7));
let p = Paragraph::with_text("well-known", CharProps::default());
assert_eq!(p.word_at(1), (0, 4));
}
proptest::proptest! {
#[test]
fn edits_keep_runs_consistent(ops in proptest::collection::vec((0u8..4, 0usize..40, 0usize..40, "[a-zé ]{0,5}"), 0..40)) {
+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]
+21
View File
@@ -703,3 +703,24 @@ fn a_math_name_is_corrected_by_any_character_that_cannot_continue_it() {
s.run("equation.type", &json!({"text": r"\alpha+"})).unwrap();
assert_eq!(linear(&s), r"\alpha+");
}
/// Paste Formatting keeps an open equation open (matching other formatting commands and
/// `cmd::column`), whereas content-pasting commands leave the equation first.
#[test]
fn paste_formatting_keeps_an_open_equation_open() {
let mut s = session();
s.run("text.insert", &json!({"text": "source "})).unwrap();
s.run("select.text", &json!({"text": "source"})).unwrap();
s.run("format.bold", &json!({})).unwrap();
s.run("edit.copyFormat", &json!({})).unwrap();
s.run("caret.docEnd", &json!({})).unwrap();
s.run("insert.equation", &json!({"linear": "x"})).unwrap();
let before = s.math.clone();
assert!(before.is_some());
s.run("edit.pasteFormat", &json!({})).unwrap();
assert_eq!(s.math, before, "edit.pasteFormat keeps the open equation open");
s.run("edit.pasteText", &json!({"text": "y"})).unwrap();
assert!(s.math.is_none(), "edit.pasteText closes the open equation");
}
+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.
+14 -3
View File
@@ -209,7 +209,8 @@ fn target(s: &Session) -> Option<(Pos, Pos)> {
return Some((a, b));
}
let p = s.doc.para_at(&a)?;
let is_w = |c: char| c.is_alphanumeric() || c == '\'' || c == '_';
// Word takes a typographic apostrophe (’) like `'` here (#6517).
let is_w = |c: char| c.is_alphanumeric() || matches!(c, '\'' | '’' | '_');
let before = p.text.get(..a.off)?.chars().next_back();
let after = p.text.get(a.off..)?.chars().next();
if before.is_some_and(is_w) && after.is_some_and(is_w) {
@@ -351,6 +352,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 {
@@ -366,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))
}
@@ -376,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))
+1 -1
View File
@@ -21,7 +21,7 @@ pub use items::{
};
use items::{cover_page, date_time, drop_cap, drop_cap_off, field, page_number, symbol};
use links::{bookmark, delete_bookmark, link, link_targets};
pub use links::{bookmark_name_ok, bookmark_range, bookmark_span};
pub use links::{bookmark_name_ok, bookmark_range, bookmark_span, selection_is_one_line};
pub use objects::{MAX_TABLE_ROWS, base64_decode, base64_encode};
use objects::{icon, shape, table, text_box};
pub(crate) use objects::{image_ext, picture};
+88 -11
View File
@@ -205,21 +205,26 @@ pub fn format_date_at_in(fmt: &str, lang: Option<&str>, unix: u64, offset_secs:
format_date_parts_in(fmt, lang, y, m as usize, d, hms, days)
}
/// Month and weekday names of a language, as Word writes them in date fields: full names, the
/// three-letter forms (`MMM`, `ddd`) being their first three letters, without a full stop.
/// Weekdays start on Thursday (1970-01-01).
/// Month and weekday names of a language, as Word writes them in date fields: full names and the
/// abbreviations used by `MMM` and `ddd`. Weekdays start on Thursday (1970-01-01).
struct DateNames {
/// Full month names (January through December).
months: [&'static str; 12],
/// Abbreviated month names for `MMM` (January through December).
months_short: [&'static str; 12],
/// Weekday names starting on Thursday (1970-01-01).
days: [&'static str; 7],
/// Abbreviated weekday names for `ddd`, starting on Thursday (1970-01-01).
days_short: [&'static str; 7],
/// The picture of a `DATE` field without `\@`.
default: &'static str,
}
const ENGLISH: DateNames = DateNames {
months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
months_short: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
days: ["Thursday", "Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday"],
days_short: ["Thu", "Fri", "Sat", "Sun", "Mon", "Tue", "Wed"],
default: "M/d/yyyy",
};
@@ -227,14 +232,46 @@ const ENGLISH: DateNames = DateNames {
/// `ddd` = `qui`, and `dd/MM/yyyy` for a field without a picture.
const PORTUGUESE: DateNames = DateNames {
months: ["janeiro", "fevereiro", "março", "abril", "maio", "junho", "julho", "agosto", "setembro", "outubro", "novembro", "dezembro"],
months_short: ["jan", "fev", "mar", "abr", "mai", "jun", "jul", "ago", "set", "out", "nov", "dez"],
days: ["quinta-feira", "sexta-feira", "sábado", "domingo", "segunda-feira", "terça-feira", "quarta-feira"],
days_short: ["qui", "sex", "sáb", "dom", "seg", "ter", "qua"],
default: "dd/MM/yyyy",
};
/// Choose month and weekday names according to the primary language subtag.
/// German (Word's Windows NLS forms): `MMMM` = `März`, `MMM` = `Mrz`, `ddd` = `Fr` (two
/// letters), and `dd.MM.yyyy` for a field without a picture. Covers de-DE, de-CH and bare `de`.
const GERMAN: DateNames = DateNames {
months: ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
months_short: ["Jan", "Feb", "Mrz", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"],
days: ["Donnerstag", "Freitag", "Samstag", "Sonntag", "Montag", "Dienstag", "Mittwoch"],
days_short: ["Do", "Fr", "Sa", "So", "Mo", "Di", "Mi"],
default: "dd.MM.yyyy",
};
/// Austrian Standard German: January is `Jänner`, abbreviated `Jän` (Österreichisches
/// Wörterbuch; Windows NLS `de-AT`). Every other month and weekday matches [`GERMAN`].
const GERMAN_AUSTRIA: DateNames = DateNames {
months: ["Jänner", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
months_short: ["Jän", "Feb", "Mrz", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"],
days: ["Donnerstag", "Freitag", "Samstag", "Sonntag", "Montag", "Dienstag", "Mittwoch"],
days_short: ["Do", "Fr", "Sa", "So", "Mo", "Di", "Mi"],
default: "dd.MM.yyyy",
};
/// Choose month and weekday names from the language tag: the primary subtag picks the language,
/// and a region subtag refines it (`de-AT` writes `Jänner`). Tags compare case-insensitively, as
/// `w:lang` values do.
fn date_names(lang: Option<&str>) -> &'static DateNames {
let primary = lang.and_then(|l| l.trim().split(['-', '_']).next()).unwrap_or("");
if primary.eq_ignore_ascii_case("pt") { &PORTUGUESE } else { &ENGLISH }
let mut subtags = lang.unwrap_or("").trim().split(['-', '_']);
let primary = subtags.next().unwrap_or("");
if primary.eq_ignore_ascii_case("pt") {
&PORTUGUESE
} else if primary.eq_ignore_ascii_case("de") {
// Austria keeps `Jänner` / `Jän`; Germany and Switzerland keep `Januar` / `Jan`.
if subtags.any(|region| region.eq_ignore_ascii_case("AT")) { &GERMAN_AUSTRIA } else { &GERMAN }
} else {
&ENGLISH
}
}
/// The picture Word gives a `DATE` field that has no `\@` switch, in the field's language.
@@ -252,9 +289,12 @@ pub fn format_date_parts(fmt: &str, y: i64, m: usize, d: u32, hms: (u32, u32, u3
#[allow(clippy::too_many_arguments)]
pub fn format_date_parts_in(fmt: &str, lang: Option<&str>, y: i64, m: usize, d: u32, (hh, mm, ss): (u32, u32, u32), days_since: i64) -> String {
let names = date_names(lang);
let month = names.months.get(m.saturating_sub(1)).copied().unwrap_or(names.months[0]);
let day = names.days.get(days_since.rem_euclid(7) as usize).copied().unwrap_or(names.days[0]);
let three = |s: &str| -> String { s.chars().take(3).collect() };
let mi = m.saturating_sub(1);
let di = days_since.rem_euclid(7) as usize;
let month = names.months.get(mi).copied().unwrap_or(names.months[0]);
let month_short = names.months_short.get(mi).copied().unwrap_or(names.months_short[0]);
let day = names.days.get(di).copied().unwrap_or(names.days[0]);
let day_short = names.days_short.get(di).copied().unwrap_or(names.days_short[0]);
let mut out = String::new();
let chars: Vec<char> = fmt.chars().collect();
let mut i = 0;
@@ -296,11 +336,11 @@ pub fn format_date_parts_in(fmt: &str, lang: Option<&str>, y: i64, m: usize, d:
('y' | 'Y', 4..) => out.push_str(&format!("{y:04}")),
('y' | 'Y', _) => out.push_str(&format!("{:02}", y % 100)),
('M', 4..) => out.push_str(month),
('M', 3) => out.push_str(&three(month)),
('M', 3) => out.push_str(month_short),
('M', 2) => out.push_str(&format!("{m:02}")),
('M', 1) => out.push_str(&m.to_string()),
('d' | 'D', 4..) => out.push_str(day),
('d' | 'D', 3) => out.push_str(&three(day)),
('d' | 'D', 3) => out.push_str(day_short),
('d' | 'D', 2) => out.push_str(&format!("{d:02}")),
('d' | 'D', 1) => out.push_str(&d.to_string()),
('H', 2..) => out.push_str(&format!("{hh:02}")),
@@ -574,6 +614,43 @@ mod date_time_locale_tests {
assert_eq!(format("MMMM", 20), "outubro");
}
/// German month and weekday names, and the default picture, are chosen by the language tag
/// (de-DE, de-AT, de-CH), as in Word (#7146).
#[test]
fn german_date_names_render_for_de() {
assert_eq!(format_date_parts_in("dddd, d. MMMM yyyy", Some("de-DE"), 2026, 11, 21, (12, 0, 0), 2), "Samstag, 21. November 2026");
assert_eq!(default_date_picture(Some("de-CH")), "dd.MM.yyyy");
}
/// Windows NLS short forms: two-letter weekdays (`Mo`, `Di`…) and `Mrz` for March, with no
/// trailing full stop (#7146).
#[test]
fn german_short_names_match_windows_nls() {
let format = |pic| format_date_parts_in(pic, Some("de-DE"), 2026, 3, 15, (12, 0, 0), 3);
assert_eq!(format("ddd, d. MMM yyyy"), "So, 15. Mrz 2026");
assert_eq!(format("dddd"), "Sonntag");
assert_eq!(format("MMM"), "Mrz");
}
/// Austrian Standard German writes January as `Jänner` (`Jän`), while Germany, Switzerland
/// and bare `de` keep `Januar` (`Jan`); every other name is shared (#7146).
#[test]
fn austrian_german_january_is_jaenner() {
let january = |lang, pic| format_date_parts_in(pic, Some(lang), 2026, 1, 15, (12, 0, 0), 0);
assert_eq!(january("de-AT", "MMMM"), "Jänner");
assert_eq!(january("de-AT", "MMM"), "Jän");
assert_eq!(january("de_at", "MMMM"), "Jänner", "region subtags compare case-insensitively");
for lang in ["de-DE", "de-CH", "de"] {
assert_eq!(january(lang, "MMMM"), "Januar", "{lang}");
assert_eq!(january(lang, "MMM"), "Jan", "{lang}");
}
// Only January differs: February and March read the same in Austria and Germany.
for month in [2, 3] {
let names = |lang| format_date_parts_in("MMMM MMM", Some(lang), 2026, month, 1, (12, 0, 0), 0);
assert_eq!(names("de-AT"), names("de-DE"));
}
}
/// A pt-BR dynamic field keeps its result after DOCX round-trip and refresh.
#[test]
fn pt_br_date_time_dialog_inserts_dynamic_field() {
+30 -10
View File
@@ -84,25 +84,45 @@ pub(super) fn link(s: &mut Session, v: &Value) -> CmdResult {
sel_result(s)
}
/// The `text` to retype a selection with before linking it: only when it differs from the selected
/// text and both fit in one line of one paragraph without pictures or fields, outside any field's
/// result. Otherwise (as Word shows `<<Selection in Document>>`) the selection keeps its text.
fn retyped_text(s: &Session, v: &Value) -> Option<String> {
/// What can't stand in one line of text: breaks, and pictures or fields.
const NOT_ONE_LINE: [char; 7] = {
use wordcraft_doc::para::{COLUMN_BREAK, LINE_BREAK, OBJ, PAGE_BREAK};
/// What can't stand in one line of text: breaks, and pictures or fields.
const NOT_ONE_LINE: [char; 7] = [LINE_BREAK, '\r', '\u{2029}', '\u{b}', PAGE_BREAK, COLUMN_BREAK, OBJ];
let text = p::str(v, "text").filter(|t| !t.is_empty() && t.len() <= 4096)?;
if text.contains(NOT_ONE_LINE) {
[LINE_BREAK, '\r', '\u{2029}', '\u{b}', PAGE_BREAK, COLUMN_BREAK, OBJ]
};
/// The raw text of the selection when it is one run of one paragraph without breaks, pictures or fields.
fn one_line_selection(s: &Session) -> Option<&str> {
// A column (block) selection has both ends in one paragraph but holds a piece of each line it
// covers: it isn't one line of text (#8581).
if s.column_segments().is_some_and(|segs| !segs.is_empty()) {
return None;
}
let (a, b) = s.sel.ordered();
if a.story != b.story || a.path != b.path {
return None;
}
let shown = s.doc.para(a.story, &a.path)?.text.get(a.off..b.off)?;
if shown.contains(NOT_ONE_LINE) || shown == text {
s.doc.para(a.story, &a.path)?.text.get(a.off..b.off).filter(|t| !t.contains(NOT_ONE_LINE))
}
/// Whether the selection is plain text in one line of one paragraph: otherwise (as Word shows
/// `<<Selection in Document>>`) Text to display can't show it and linking keeps its content (#8286).
pub fn selection_is_one_line(s: &Session) -> bool {
one_line_selection(s).is_some()
}
/// The `text` to retype a selection with before linking it: only when it differs from the selected
/// text and both fit in one line of one paragraph without pictures or fields, outside any field's
/// result. Otherwise (as Word shows `<<Selection in Document>>`) the selection keeps its text.
fn retyped_text(s: &Session, v: &Value) -> Option<String> {
let text = p::str(v, "text").filter(|t| !t.is_empty() && t.len() <= 4096)?;
if text.contains(NOT_ONE_LINE) {
return None;
}
let shown = one_line_selection(s)?;
if shown == text {
return None;
}
let (a, b) = s.sel.ordered();
// A selection in a field's result (between its markers, which it doesn't hold) is retyped by
// the next update of the field, not here.
if s.doc.field_ranges(a.story).iter().any(|r| r.start < b && a <= r.end) {
+37 -8
View File
@@ -373,21 +373,22 @@ pub fn merge_formatting(s: &Session, frag: &mut Fragment) {
p.props = para.clone();
for run in &mut p.runs {
let src = std::mem::replace(&mut run.props, base.clone());
// Emphasis in either script is kept for both, as the Bold and Italic buttons set
// it: text pasted into a run marked `w:cs` (Thai from a WPS or Word file) is drawn
// with the complex-script bold and italic.
if src.bold == Some(true) || src.bold_cs == Some(true) {
let e = emphasis_of(s, &src);
// Emphasis the source shows in either script is kept for both, as the Bold and
// Italic buttons set it: text pasted into a run marked `w:cs` (Thai from a WPS or
// Word file) is drawn with the complex-script bold and italic.
if shown(e.bold, e.bold_cs, &e) {
run.props.bold = Some(true);
run.props.bold_cs = Some(true);
}
if src.italic == Some(true) || src.italic_cs == Some(true) {
if shown(e.italic, e.italic_cs, &e) {
run.props.italic = Some(true);
run.props.italic_cs = Some(true);
}
if src.underline.is_some_and(|u| u != wordcraft_doc::props::Underline::None) {
run.props.underline = src.underline;
if e.underline.is_some_and(|u| u != wordcraft_doc::props::Underline::None) {
run.props.underline = e.underline;
}
if src.strike == Some(true) {
if e.strike == Some(true) {
run.props.strike = Some(true);
}
run.props.link = src.link;
@@ -400,6 +401,34 @@ pub fn merge_formatting(s: &Session, frag: &mut Fragment) {
}
}
/// The formatting a pasted run's emphasis is judged by: its own, over its character style
/// chain's. Word keeps the bold, italic, underline and strikethrough a character style gives the
/// source, as direct formatting, but not a paragraph style's (measured in Word for Windows), so
/// the paragraph style isn't consulted.
fn emphasis_of(s: &Session, src: &wordcraft_doc::CharProps) -> wordcraft_doc::CharProps {
use wordcraft_doc::styles::StyleKind;
let mut e = wordcraft_doc::CharProps::default();
if let Some(id) = src.style.as_deref() {
for st in s.doc.styles.chain(id) {
if st.kind == StyleKind::Character || st.kind == StyleKind::Paragraph {
e.overlay(&st.chr);
}
}
}
e.overlay(&wordcraft_doc::CharProps { style: None, ..src.clone() });
e
}
/// Whether a run with these Latin and complex-script values of a toggle (bold or italic) shows
/// it anywhere, as the resolved formatting draws it: a run marked `w:cs` or `w:rtl` draws all
/// its text with the complex-script value, which borrows the Latin one unless the run is marked
/// `w:cs`; other runs draw their Latin text with the Latin value.
fn shown(latin: Option<bool>, complex: Option<bool>, run: &wordcraft_doc::CharProps) -> bool {
let complex_shown = complex.or(latin.filter(|_| run.cs != Some(true))) == Some(true);
let all_complex = run.cs == Some(true) || run.rtl == Some(true);
complex_shown || (!all_complex && latin == Some(true))
}
/// Paste `frag` at the selection. A copied table pasted with the caret in a table cell goes the way
/// Word's Paste does it (rows inserted or cells overwritten, #6739; see [`super::paste_cells`]);
/// anything else is [`insert_as_is`].
+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() }
+50
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"));
+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::{
+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();
+23
View File
@@ -337,6 +337,29 @@ mod tests {
let _ = std::fs::remove_dir_all(&d);
}
/// A document made from a template is created now, not when the template was: it has no
/// creation date until it is saved, so CREATEDATE in it shows today.
#[test]
fn new_from_template_has_no_creation_date_of_its_own_yet() {
let d = scratch("created");
let path = d.join("Dated.dotx");
let mut t = Session::new(wordcraft_doc::Document::new());
t.run("document.setText", &json!({"text": "Dated"})).unwrap();
t.doc.core.created = "2019-05-05T12:00:00Z".into();
crate::io::save_path(&path, &t.doc).unwrap();
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("file.newFromTemplate", &json!({"path": path.to_string_lossy()})).unwrap();
assert_eq!(s.doc.core.created, "");
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy""#, "result": "2019"})).unwrap();
s.run("references.updateFields", &json!({})).unwrap();
assert!(s.doc.plain_text(wordcraft_doc::StoryRef::Body).contains(&crate::cmd::insert::format_date("yyyy")));
// The template itself keeps its date.
let mut again = Session::new(wordcraft_doc::Document::new());
again.run("file.open", &json!({"path": path.to_string_lossy()})).unwrap();
assert_eq!(again.doc.core.created, "2019-05-05T12:00:00Z");
let _ = std::fs::remove_dir_all(&d);
}
/// #3433: a template the platform hands the app takes an untouched blank document's place
/// (`replaceBlank`), as a file `file.open` opens does; otherwise, and without the flag, the
/// new document opens beside the others, as File › New's does. Either way the template on
+4 -1
View File
@@ -35,7 +35,10 @@ impl Session {
fn leave_math_for_command(&mut self, id: &str) {
self.math_left = false;
if self.math.is_some()
&& (id.starts_with("text.") || id.starts_with("caret.") || id.starts_with("select.") || id.starts_with("edit.paste"))
&& (id.starts_with("text.")
|| id.starts_with("caret.")
|| id.starts_with("select.")
|| (id.starts_with("edit.paste") && id != "edit.pasteFormat"))
&& let Some(m) = self.math.take()
{
let off = m.at.off + wordcraft_doc::para::OBJ.len_utf8();
+271
View File
@@ -293,6 +293,15 @@ fn custom_dictionary_words_persist_through_their_file() {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn confined_sessions_test_is_native_only() {
let source = include_str!("tests.rs");
assert!(source.contains(
"#[cfg(not(target_arch = \"wasm32\"))]\n#[test]\nfn confined_sessions_neither_save_the_dictionary_nor_choose_folders_outside_their_roots()"
));
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn confined_sessions_neither_save_the_dictionary_nor_choose_folders_outside_their_roots() {
let _guard = crate::custom_dict::DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
@@ -1043,6 +1052,128 @@ fn bold_toggles_selection_and_caret_word() {
assert_eq!(p.props_of_char(9).italic, None);
}
/// A partly formatted selection toggles by its first character, as Word does (#6516).
#[test]
fn toggles_on_mixed_selection_follow_first_character() {
// `Abc abc` with `fmt` set by `cmd`, then `cmd` with `v` on the selection `from` → `to`.
let toggled = |cmd: &str, fmt: (usize, usize), from: usize, to: usize, v: serde_json::Value| -> String {
let mut s = s();
run(&mut s, "text.insert", json!({"text": "Abc abc"}));
let sel = |s: &mut Session, a: usize, b: usize| {
run(s, "select.range", json!({"anchor": {"block": 0, "off": a}, "focus": {"block": 0, "off": b}}));
};
sel(&mut s, fmt.0, fmt.1);
run(&mut s, cmd, json!({"value": true}));
sel(&mut s, from, to);
run(&mut s, cmd, v);
let p = s.doc.para_at(&Pos::body(0, 0)).unwrap();
(0..7)
.map(|i| {
let c = p.props_of_char(i);
match cmd {
"format.italic" => c.italic == Some(true),
"format.underline" => c.underline.is_some_and(|u| u != wordcraft_doc::props::Underline::None),
_ => c.bold == Some(true),
}
})
.map(|on| if on { 'F' } else { '.' })
.collect()
};
let t = || json!({});
for cmd in ["format.bold", "format.italic", "format.underline"] {
// `FFF....`: a selection starting on formatted text removes the format from all of it.
assert_eq!(toggled(cmd, (0, 3), 2, 5, t()), "FF.....", "{cmd}");
assert_eq!(toggled(cmd, (0, 3), 0, 7, t()), ".......", "{cmd}");
assert_eq!(toggled(cmd, (0, 3), 1, 7, t()), "F......", "{cmd}");
// Made right to left: still the first character in document order.
assert_eq!(toggled(cmd, (0, 3), 5, 2, t()), "FF.....", "{cmd}");
assert_eq!(toggled(cmd, (0, 3), 7, 0, t()), ".......", "{cmd}");
// `....FFF`: a selection starting on plain text applies it to all of it.
assert_eq!(toggled(cmd, (4, 7), 0, 7, t()), "FFFFFFF", "{cmd}");
// An explicit value still sets.
assert_eq!(toggled(cmd, (0, 3), 0, 7, json!({"value": true})), "FFFFFFF", "{cmd}");
assert_eq!(toggled(cmd, (4, 7), 0, 7, json!({"value": false})), ".......", "{cmd}");
}
}
/// A selection that starts in an empty paragraph: Word decides from the first text character, not
/// from the empty paragraph's mark (observed in Word for Windows, #6516 review).
#[test]
fn toggle_on_a_selection_from_an_empty_paragraph_follows_the_first_text() {
let toggled = |mark_bold: bool, text_bold: bool| -> Option<bool> {
let mut s = s();
run(&mut s, "text.newParagraph", json!({}));
run(&mut s, "text.insert", json!({"text": "abc"}));
let first = Pos::body(0, 0);
s.doc.para_mut(first.story, &first.path).unwrap().mark.bold = Some(mark_bold);
run(&mut s, "select.range", json!({"anchor": {"block": 1, "off": 0}, "focus": {"block": 1, "off": 3}}));
run(&mut s, "format.bold", json!({"value": text_bold}));
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 0}, "focus": {"block": 1, "off": 3}}));
run(&mut s, "format.bold", json!({}));
s.doc.para_at(&Pos::body(1, 0)).unwrap().props_of_char(0).bold
};
// A bold empty paragraph before plain text: Bold goes on.
assert_eq!(toggled(true, false), Some(true));
// A plain empty paragraph before bold text: Bold comes off.
assert_eq!(toggled(false, true), Some(false));
}
#[test]
fn bold_at_a_caret_takes_a_word_with_a_typographic_apostrophe() {
// Word bolds `don’t` and `dogs’` whole: `’` is part of the word like `'` (#6517).
let bold_word = |text: &str, caret: usize| {
let mut s = s();
run(&mut s, "text.insert", json!({"text": text}));
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": caret}}));
run(&mut s, "format.bold", json!({}));
let p = s.doc.para_at(&Pos::body(0, 0)).unwrap().clone();
p.text.char_indices().filter(|&(i, _)| p.props_of_char(i).bold == Some(true)).map(|(_, c)| c).collect::<String>()
};
assert_eq!(bold_word("don’t stop", 1), "don’t");
assert_eq!(bold_word("the dogs’ bone", 5), "dogs’");
assert_eq!(bold_word("’tis here", 3), "’tis");
}
#[test]
fn select_word_takes_a_typographic_apostrophe() {
let mut s = s();
run(&mut s, "text.insert", json!({"text": "don’t stop"}));
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": 1}}));
run(&mut s, "select.word", json!({}));
let (a, b) = s.sel.ordered();
assert_eq!((a.off, b.off), (0, 8), "`don’t ` with its trailing space, as Word selects it (#6517)");
}
#[test]
fn thesaurus_at_a_caret_looks_up_a_quoted_word_without_its_quotes() {
// The word unit now takes `’`, so `‘good’` gives `good’`; the lookup drops enclosing quotes.
let mut s = s();
run(&mut s, "text.insert", json!({"text": "a ‘good’ day"}));
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": 6}}));
let r = run(&mut s, "review.thesaurus", json!({}));
assert_eq!(r["word"], json!("good"));
assert!(r["synonyms"].as_array().is_some_and(|a| !a.is_empty()), "{r}");
}
#[test]
fn a_synonym_replaces_the_word_and_keeps_its_quotes() {
// The range a chosen synonym replaces (the context menu's): the word without its quotes or the
// space after it, while an apostrophe inside a word stays part of it (#6517).
let word = |text: &str, caret: usize| {
let mut s = s();
run(&mut s, "text.insert", json!({"text": text, "raw": true}));
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": caret}}));
let (a, b) = crate::cmd::review::thesaurus_word(&s).unwrap();
s.set_selection(crate::Selection { anchor: a, focus: b });
run(&mut s, "text.insert", json!({"text": "fine", "raw": true}));
s.doc.plain_text(StoryRef::Body)
};
assert_eq!(word("a ‘good’ day", 6), "a ‘fine’ day");
assert_eq!(word("a 'good' day", 4), "a 'fine' day");
assert_eq!(word("a good day", 3), "a fine day");
assert_eq!(word("don’t go", 1), "fine go");
}
#[test]
fn border_toggles_and_saves() {
use wordcraft_doc::props::Border;
@@ -2054,6 +2185,88 @@ fn paste_merge_formatting_keeps_bold_and_italic_in_a_complex_script_run() {
assert!(r.bold_cs, "drawn bold as complex script");
}
#[test]
fn paste_merge_formatting_leaves_plain_what_the_source_draws_plain() {
// #4852 review: a run marked `w:cs` is bold and italic only by `w:bCs` and `w:iCs`, so one
// with `w:b` and `w:i` alone is drawn plain and pastes plain; one with `w:bCs` pastes bold.
let mut s = s();
run(&mut s, "document.setText", json!({"text": "x"}));
run(&mut s, "caret.docEnd", json!({}));
let pasted = |s: &Session, props: wordcraft_doc::CharProps| {
let mut frag = wordcraft_doc::edit::Fragment::from_text("ไทย");
for b in &mut frag.blocks {
crate::cmd::paste::each_para(b, 0, &mut |p| p.runs.iter_mut().for_each(|r| r.props = props.clone()));
}
crate::cmd::paste::merge_formatting(s, &mut frag);
let mut out = Vec::new();
for b in &mut frag.blocks {
crate::cmd::paste::each_para(b, 0, &mut |p| out.extend(p.runs.iter().map(|r| s.doc.styles.resolve_char(None, &r.props))));
}
out
};
let cs = wordcraft_doc::CharProps { cs: Some(true), bold: Some(true), italic: Some(true), ..Default::default() };
for r in pasted(&s, cs.clone()) {
assert!(!r.bold && !r.bold_cs && !r.italic && !r.italic_cs, "{r:?}");
}
for r in pasted(&s, wordcraft_doc::CharProps { bold_cs: Some(true), ..cs }) {
assert!(r.bold && r.bold_cs && !r.italic_cs, "{r:?}");
}
// An unmarked run shows `w:b` in both scripts.
for r in pasted(&s, wordcraft_doc::CharProps { bold: Some(true), ..Default::default() }) {
assert!(r.bold && r.bold_cs, "{r:?}");
}
}
#[test]
fn paste_merge_formatting_keeps_a_character_styles_emphasis_not_a_paragraph_styles() {
// #7177 review, measured in Word for Windows: Merge Formatting keeps the bold, italic,
// underline and strikethrough a character style gives the source, as direct formatting, but
// drops a paragraph style's.
use wordcraft_doc::props::Underline;
use wordcraft_doc::styles::{Style, StyleKind};
let mut s = s();
run(&mut s, "document.setText", json!({"text": "x"}));
run(&mut s, "caret.docEnd", json!({}));
let on = wordcraft_doc::CharProps {
bold: Some(true),
bold_cs: Some(true),
italic: Some(true),
italic_cs: Some(true),
underline: Some(Underline::Single),
strike: Some(true),
..Default::default()
};
let sheet = Arc::make_mut(&mut s.doc.styles);
sheet.upsert(Style { id: "ChEmph".into(), name: "ChEmph".into(), kind: StyleKind::Character, chr: on.clone(), ..Default::default() });
sheet.upsert(Style { id: "PEmph".into(), name: "PEmph".into(), kind: StyleKind::Paragraph, chr: on, ..Default::default() });
let pasted = |s: &Session, para_style: Option<&str>, props: wordcraft_doc::CharProps| {
let mut frag = wordcraft_doc::edit::Fragment::from_text("ไทย Thai");
for b in &mut frag.blocks {
crate::cmd::paste::each_para(b, 0, &mut |p| {
p.props.style = para_style.map(str::to_string);
p.runs.iter_mut().for_each(|r| r.props = props.clone());
});
}
crate::cmd::paste::merge_formatting(s, &mut frag);
let mut out = Vec::new();
for b in &mut frag.blocks {
crate::cmd::paste::each_para(b, 0, &mut |p| {
out.extend(p.runs.iter().map(|r| s.doc.styles.resolve_char(p.props.style.as_deref(), &r.props)));
});
}
out
};
for cs in [None, Some(true)] {
for r in pasted(&s, None, wordcraft_doc::CharProps { style: Some("ChEmph".into()), cs, ..Default::default() }) {
assert!(r.bold && r.bold_cs && r.italic && r.italic_cs && r.strike, "character style, cs {cs:?}: {r:?}");
assert_eq!(r.underline, Underline::Single, "character style, cs {cs:?}");
}
for r in pasted(&s, Some("PEmph"), wordcraft_doc::CharProps { cs, ..Default::default() }) {
assert!(!r.bold && !r.bold_cs && !r.italic && !r.italic_cs && !r.strike, "paragraph style, cs {cs:?}: {r:?}");
assert_eq!(r.underline, Underline::None, "paragraph style, cs {cs:?}");
}
}
}
#[test]
fn pasted_rtf_sections_link_their_headers_to_the_previous() {
// #1378: the RTF's own header part ids mean nothing in this document; a pasted section
@@ -7301,6 +7514,64 @@ fn saving_a_text_file_over_itself_saves_the_document() {
let _ = std::fs::remove_dir_all(&dir);
}
/// #6131: File › Export to DOCX, ODT or RTF writes a copy (`copy: true`). It made the copy the
/// document's file and cleared its unsaved changes, so the next Save went to the copy and the
/// original kept its old text. The copy has the edits; the document keeps its file, its changes
/// and its save stamps.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn exporting_a_copy_keeps_the_documents_file() {
let dir = std::env::temp_dir().join(format!("wordcraft-engine-export-copy-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let body = |p: &std::path::Path| crate::io::open_path(p).unwrap().plain_text(wordcraft_doc::StoryRef::Body);
for ext in ["docx", "odt", "rtf"] {
let original = dir.join(format!("a-{ext}.docx"));
let mut s = Session::new(wordcraft_doc::Document::new());
run(&mut s, "text.insert", json!({"text": "first"}));
run(&mut s, "file.save", json!({"path": original.to_string_lossy()}));
run(&mut s, "text.insert", json!({"text": " edited"}));
let stamps = (s.doc.core.revision, s.doc.core.modified.clone());
let copy = dir.join(format!("copy.{ext}"));
let r = run(&mut s, "file.saveAs", json!({"path": copy.to_string_lossy(), "copy": true}));
assert_eq!(r["saved"], true, "{ext}");
assert_eq!(body(&copy), "first edited", "{ext}: the copy has the edits");
assert_eq!(s.path.as_deref(), Some(original.as_path()), "{ext}: the document keeps its file");
assert!(s.dirty, "{ext}: the document keeps its unsaved changes");
assert_eq!((s.doc.core.revision, s.doc.core.modified.clone()), stamps, "{ext}: the document's save stamps are untouched");
run(&mut s, "file.save", json!({}));
assert_eq!(body(&original), "first edited", "{ext}: Save still writes the original");
assert!(!s.dirty);
}
let _ = std::fs::remove_dir_all(&dir);
}
/// A copy with no path would open the Save As picker on an untitled document (whose answer is an
/// ordinary save that adopts the file) or fall back to the open file's path and overwrite it while
/// leaving the document dirty: refused in both cases (#6131 review).
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_copy_without_a_path_is_refused() {
let mut s = Session::new(wordcraft_doc::Document::new());
run(&mut s, "text.insert", json!({"text": "first"}));
let e = s.run("file.save", &json!({"copy": true})).unwrap_err();
assert!(e.to_string().contains("copy"), "{e}");
assert!(s.ui_requests.is_empty(), "no picker opens");
let dir = std::env::temp_dir().join(format!("wordcraft-engine-copy-no-path-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let original = dir.join("doc.docx");
run(&mut s, "file.save", json!({"path": original.to_string_lossy()}));
run(&mut s, "text.insert", json!({"text": " edited"}));
let e = s.run("file.save", &json!({"copy": true})).unwrap_err();
assert!(e.to_string().contains("copy"), "{e}");
assert!(s.dirty, "the document keeps its unsaved changes");
let on_disk = crate::io::open_path(&original).unwrap().plain_text(wordcraft_doc::StoryRef::Body);
assert_eq!(on_disk, "first", "the original file on disk was not overwritten");
let _ = std::fs::remove_dir_all(&dir);
}
/// A Markdown file saved as another Markdown file is that file from now on: the next save goes
/// there and the first file stays as it was. Other formats keep the #2376 rule.
#[cfg(not(target_arch = "wasm32"))]
+32
View File
@@ -1653,6 +1653,38 @@ fn a_link_keeps_a_selection_it_cannot_retype() {
assert_eq!(s.doc.field_ranges(StoryRef::Body).len(), 1);
}
#[test]
fn a_column_selection_in_one_paragraph_is_not_one_line() {
// A column (block) selection over the wrapped lines of one paragraph: both its ends are in
// that paragraph, but it holds a piece of each line, so Word shows <<Selection in Document>>
// for it and the text to display can't retype it (#8581).
let mut s = typed("alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron pi rho sigma tau");
let (first, second) = {
let l = s.layout();
let len = s.doc.para_at(&Pos::body(0, 0)).unwrap().text.len();
let mut top = None;
let mut first = None;
let mut second = None;
for off in 0..=len {
let Some(c) = l.caret_on(&Pos::body(0, off), 0) else { continue };
if top.is_some_and(|t| t != c.top) && second.is_none() {
second = Some(off + 10);
break;
}
if top.is_none() {
top = Some(c.top);
first = Some(off);
}
}
(first.expect("the paragraph is laid out"), second.expect("the paragraph wraps"))
};
run(&mut s, "select.column", json!({"anchor": Pos::body(0, first), "focus": Pos::body(0, second)}));
let segs = s.column_segments().expect("the block is one paragraph's lines").to_vec();
assert_eq!(segs.len(), 2, "the block holds a piece of each of the paragraph's two lines");
assert!(segs.iter().all(|(a, b)| a.path == segs[0].0.path && b.path == segs[0].0.path), "both pieces are in one paragraph");
assert!(!crate::cmd::insert::selection_is_one_line(&s), "a column selection is not one line of text");
}
#[test]
fn typing_then_selecting_then_typing_are_two_undo_steps() {
// #419: a selection that moves the insertion point ends the typing group, like a caret move.
+99
View File
@@ -129,6 +129,105 @@ fn a_date_field_in_a_header_is_refreshed_too() {
assert_eq!(found, [today], "the header's field is refreshed as well as the body's");
}
/// A document whose `docDefaults` set `lang`, so a field run that names no language inherits it,
/// as a German Word document does.
fn open_body_in_lang(lang: &str, body: &str) -> wordcraft_doc::Document {
let rels = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
let doc_rels = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rIdStyles" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>"#;
let styles = format!(
r#"<?xml version="1.0" encoding="UTF-8"?><w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:docDefaults><w:rPrDefault><w:rPr><w:lang w:val="{lang}"/></w:rPr></w:rPrDefault></w:docDefaults><w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style></w:styles>"#
);
let doc = format!(
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
);
wordcraft_engine::io::open_bytes(
"d.docx",
&zip(&[("_rels/.rels", rels), ("word/document.xml", &doc), ("word/_rels/document.xml.rels", doc_rels), ("word/styles.xml", &styles)]),
)
.expect("opens")
}
/// German documents carry their language in `docDefaults`, not on each field run. A `DATE` field
/// without `\@` therefore uses `dd.MM.yyyy`, and `MMMM`/`dddd` name the day in German, on open
/// and on an explicit refresh, for `de-DE`, `de-AT` and `de-CH` (#7146).
#[test]
fn german_date_fields_inherit_the_document_default_language() {
const PICTURE: &str = "dddd, d. MMMM yyyy";
for lang in ["de-DE", "de-AT", "de-CH"] {
let d = open_body_in_lang(
lang,
&format!(
"<w:p>{}</w:p><w:p>{}</w:p>",
field(&format!(r#"DATE \@ "{PICTURE}""#), "Wednesday, 1 January 2020", false),
field("DATE", "1/1/2020", false)
),
);
let expected = wordcraft_engine::cmd::insert::format_date_in(PICTURE, Some(lang));
let got = fields(&d);
assert_eq!(got.len(), 2, "{lang}");
assert_eq!(got[0].1, expected, "{lang}: weekday and month names come from docDefaults");
assert_ne!(got[0].1, wordcraft_engine::cmd::insert::format_date_in(PICTURE, None), "{lang}: not the English names");
assert_eq!(
got[1].1,
wordcraft_engine::cmd::insert::format_date_in("dd.MM.yyyy", Some(lang)),
"{lang}: a DATE field without a picture uses the German default"
);
// Saving and reopening keeps the inherited language, and an explicit refresh does not
// fall back to English.
let written = wordcraft_docx::write(&d).unwrap();
let mut reopened = wordcraft_engine::io::open_bytes("reopened.docx", &written).unwrap();
wordcraft_engine::cmd::references::refresh_date_fields(&mut reopened);
let got = fields(&reopened);
assert_eq!(got[0].1, expected, "{lang}: after round-trip");
assert_eq!(got[1].1, wordcraft_engine::cmd::insert::format_date_in("dd.MM.yyyy", Some(lang)), "{lang}: after round-trip");
}
}
/// `MMM` and `ddd` use Word's Windows NLS short forms for German: two-letter weekdays (`So`,
/// `Mo`…) and `Mrz` for March, with no trailing full stop (#7146).
#[test]
fn a_german_short_date_field_uses_windows_nls_abbreviations() {
const PICTURE: &str = "ddd, d. MMM yyyy";
let d = open_body_in_lang("de-DE", &format!("<w:p>{}</w:p>", field(&format!(r#"DATE \@ "{PICTURE}""#), "Wed, 1 Jan 2020", false)));
let got = fields(&d);
assert_eq!(got[0].1, wordcraft_engine::cmd::insert::format_date_in(PICTURE, Some("de-DE")));
// The abbreviations at a fixed date, independent of when the test runs.
assert_eq!(wordcraft_engine::cmd::insert::format_date_parts_in(PICTURE, Some("de-DE"), 2026, 3, 15, (12, 0, 0), 3), "So, 15. Mrz 2026");
}
/// A `TIME` field whose picture carries German name tokens inherits the language too, so the
/// English result cached in the fixture is replaced with German weekday and month names.
#[test]
fn a_german_time_field_uses_german_names() {
const PICTURE: &str = "dddd, d. MMMM yyyy 'um' HH:mm";
let d =
open_body_in_lang("de-DE", &format!("<w:p>{}</w:p>", field(&format!(r#"TIME \@ "{PICTURE}""#), "Wednesday, 1 January 2020 um 00:00", false)));
let got = fields(&d);
assert_eq!(got[0].0, format!(r#"TIME \@ "{PICTURE}""#));
assert_eq!(got[0].1, wordcraft_engine::cmd::insert::format_date_in(PICTURE, Some("de-DE")));
}
/// Austrian Standard German writes January as `Jänner` (`Jän`), while Germany, Switzerland and
/// bare `de` keep `Januar` (`Jan`), as in Windows NLS (#7146). A `de-AT` document reads German
/// through `docDefaults`; the refresh always uses the real clock, so the January names are asked
/// of the same formatter at a fixed January instant.
#[test]
fn austrian_german_documents_use_jaenner() {
const PICTURE: &str = "dddd, d. MMMM yyyy";
let d = open_body_in_lang("de-AT", &format!("<w:p>{}</w:p>", field(&format!(r#"DATE \@ "{PICTURE}""#), "Wednesday, 1 January 2020", false)));
let got = fields(&d);
assert_eq!(got[0].1, wordcraft_engine::cmd::insert::format_date_in(PICTURE, Some("de-AT")), "an Austrian document reads German");
let january = |lang: &str, picture: &str| wordcraft_engine::cmd::insert::format_date_parts_in(picture, Some(lang), 2026, 1, 15, (12, 0, 0), 0);
assert_eq!(january("de-AT", "MMMM"), "Jänner");
assert_eq!(january("de-AT", "MMM"), "Jän");
assert_eq!(january("de-AT", PICTURE), "Donnerstag, 15. Jänner 2026");
for lang in ["de-DE", "de-CH", "de"] {
assert_eq!(january(lang, "MMMM"), "Januar", "{lang}");
assert_eq!(january(lang, "MMM"), "Jan", "{lang}");
}
}
/// A minimal Word 97-2003 file whose only paragraph holds a `DATE` field cached as " 2001":
/// FIB, one compressed text piece, and the Clx that points at it.
fn binary_doc_with_stale_date() -> Vec<u8> {
+1 -1
View File
@@ -25,7 +25,7 @@ mod lookup;
mod names;
use face::{BUNDLED, FontBytes};
pub use face::{FALLBACK_FAMILY, FaceRef, FontFace, bundled};
pub use face::{FALLBACK_FAMILY, FaceRef, FontFace, bundled, bundled_inter};
#[cfg(test)]
use fallback_data::{Coverage, RUN_FALLBACK_CACHE_CHARS, SYS_FALLBACK_MAX_FILE, file_coverage, ranges_hold};
#[cfg(not(target_arch = "wasm32"))]
+12 -2
View File
@@ -13,6 +13,16 @@ pub fn bundled() -> &'static [&'static [u8]] {
BUNDLED
}
/// The bundled Inter Regular and SemiBold, each with its style name: the same bytes as in [`bundled`], so a caller
/// adds no second copy to the binary. The interface draws with them behind the suite's Inter, which is cut to Latin,
/// Greek and Cyrillic.
pub fn bundled_inter() -> [(&'static str, &'static [u8]); 2] {
[("Regular", INTER_REGULAR), ("SemiBold", INTER_SEMIBOLD)]
}
static INTER_REGULAR: &[u8] = include_bytes!("../../../../assets/fonts/Inter-Regular.ttf");
static INTER_SEMIBOLD: &[u8] = include_bytes!("../../../../assets/fonts/Inter-SemiBold.ttf");
pub(super) static BUNDLED: &[&[u8]] = &[
include_bytes!("../../../../assets/fonts/SourceSans3-Regular.ttf"),
include_bytes!("../../../../assets/fonts/SourceSans3-Semibold.ttf"),
@@ -23,9 +33,9 @@ pub(super) static BUNDLED: &[&[u8]] = &[
include_bytes!("../../../../assets/fonts/SourceSerif4-Semibold.ttf"),
include_bytes!("../../../../assets/fonts/SourceSerif4-Bold.ttf"),
include_bytes!("../../../../assets/fonts/SourceSerif4-BoldIt.ttf"),
include_bytes!("../../../../assets/fonts/Inter-Regular.ttf"),
INTER_REGULAR,
include_bytes!("../../../../assets/fonts/Inter-Medium.ttf"),
include_bytes!("../../../../assets/fonts/Inter-SemiBold.ttf"),
INTER_SEMIBOLD,
include_bytes!("../../../../assets/fonts/JetBrainsMono-Regular.ttf"),
];
+1 -1
View File
@@ -17,7 +17,7 @@ pub mod word;
pub use fontdb::{
FALLBACK_FAMILY, FONT_FILE_EXTS, FaceRef, FontDb, FontFace, FontFormat, Installed, LocalName, MAX_FONT_FILE_BYTES, UserFont, UserFontError,
base_style, bundled, decode_font_file, is_font_file_name, name_language_matches, sniff, system_font_dirs,
base_style, bundled, bundled_inter, decode_font_file, is_font_file_name, name_language_matches, sniff, system_font_dirs,
};
pub use harfrust::Feature;
use harfrust::{Direction, ShapeOptions, ShapePlan, ShapePlanKey, Shaper, Tag, UnicodeBuffer};
+337 -9
View File
@@ -95,15 +95,7 @@ pub fn read_rows(bytes: &[u8], pick: Pick<'_>) -> Result<(Vec<String>, Vec<Vec<S
let names: Vec<String> = book.sheets.iter().map(|s| s.name.clone()).collect();
let i = resolve(&names, pick)?;
let sheet = &book.sheets[i];
let rows = cells_to_rows(&sheet.cells, |c| {
if !c.text.is_empty() {
clamp_cell(c.text.clone())
} else if let Some(v) = c.value() {
format_value(&v)
} else {
String::new()
}
});
let rows = cells_to_rows(&sheet.cells, ods_value);
return Ok((names, rows));
}
Err("not an Excel or OpenDocument spreadsheet".into())
@@ -178,6 +170,187 @@ fn format_value(v: &Value) -> String {
}
}
/// An OpenDocument cell's display string, from `office:value-type`: floats from `office:value`,
/// dates and times from `office:date-value` / `office:time-value` in ISO 8601 form (`yyyy-mm-dd`,
/// `yyyy-mm-dd hh:mm[:ss]`, `hh:mm[:ss]`), booleans as `TRUE`/`FALSE`, and strings, percentages
/// and currencies as the cell's text (their value when the text is blank). A value that does not
/// parse falls back to the text. A covered cell under a merged cell is blank.
///
/// A float merges its value, not the text its number format shows: a ZIP code `01234` shown
/// through the format `00000` merges as `1234`, and `1,234` shown with a thousands separator
/// merges as `1234`.
fn ods_value(c: &craft_ods::Cell) -> String {
use craft_ods::ValueType as T;
if c.covered {
return String::new();
}
let typed = match (c.value_type, c.raw.as_deref().map(str::trim)) {
(Some(T::Float | T::Boolean), Some(_)) => c.value().map(|v| format_value(&v)),
(Some(T::Date), Some(v)) => iso_datetime(v),
(Some(T::Time), Some(v)) => iso_time(v),
(Some(T::Percentage | T::Currency | T::String), Some(_)) if c.text.is_empty() => c.value().map(|v| format_value(&v)),
_ => None,
};
typed.map(clamp_cell).unwrap_or_else(|| clamp_cell(c.text.clone()))
}
/// An ISO 8601 date or date-time (`2024-03-05`, `2024-03-05T13:45:00.000`) as `yyyy-mm-dd`,
/// with ` hh:mm[:ss]` when the time isn't midnight. `None` unless the whole value is a valid
/// calendar date and clock time.
fn iso_datetime(v: &str) -> Option<String> {
use chrono::Datelike;
let v = v.trim();
let (date, time) = match v.split_once('T') {
Some((date, time)) => (date, Some(time)),
None => (v, None),
};
// A date alone may carry a zone (`Z` or `±hh:mm`), which is left out.
let date = match (time, date.strip_suffix('Z')) {
(None, Some(d)) => d,
(None, None) if date.len() > 6 && date.get(date.len() - 6..).is_some_and(|z| z.starts_with(['+', '-']) && z.get(3..4) == Some(":")) => {
zone_offset(date.get(date.len() - 5..)?)?;
date.get(..date.len() - 6)?
}
_ => date,
};
let date = chrono::NaiveDate::parse_from_str(date, "%Y-%m-%d").ok()?;
let mut out = format!("{:04}-{:02}-{:02}", date.year(), date.month(), date.day());
if let Some(time) = time {
let (clock, fraction) = clock_time(time)?;
if clock != chrono::NaiveTime::MIN || !fraction.is_empty() {
out.push(' ');
out.push_str(&hh_mm((clock, fraction)));
}
}
Some(out)
}
/// A clock time `hh:mm[:ss[.s…]]` with an optional `Z` or `±hh:mm` zone (one, not both), which is
/// left out. The seconds' fraction comes back as its digits as written, trailing zeros dropped,
/// so a fraction finer than a nanosecond is kept.
fn clock_time(t: &str) -> Option<(chrono::NaiveTime, String)> {
let t = match (t.strip_suffix('Z'), t.rfind(['+', '-'])) {
(Some(t), _) => t,
(None, Some(i)) => {
zone_offset(t.get(i + 1..)?)?;
t.get(..i)?
}
(None, None) => t,
};
let (clock, fraction) = match t.split_once('.') {
// A fraction needs whole seconds before it.
Some((t, frac)) => {
if frac.is_empty() || !frac.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
(chrono::NaiveTime::parse_from_str(t, "%H:%M:%S").ok()?, frac.trim_end_matches('0'))
}
None => (chrono::NaiveTime::parse_from_str(t, "%H:%M:%S").or_else(|_| chrono::NaiveTime::parse_from_str(t, "%H:%M")).ok()?, ""),
};
// A leap second (`23:59:60`) is not a time a cell holds.
(chrono::Timelike::nanosecond(&clock) < 1_000_000_000).then(|| (clock, fraction.to_string()))
}
/// A zone offset's `hh:mm`, two digits each and at most `14:00` as XML Schema allows.
fn zone_offset(z: &str) -> Option<()> {
use chrono::Timelike;
let two_digit = z.len() == 5 && z.bytes().enumerate().all(|(i, b)| if i == 2 { b == b':' } else { b.is_ascii_digit() });
if !two_digit {
return None;
}
let z = chrono::NaiveTime::parse_from_str(z, "%H:%M").ok()?;
(z.hour() < 14 || (z.hour() == 14 && z.minute() == 0)).then_some(())
}
/// `hh:mm`, with `:ss` when the seconds aren't zero and their fraction when it isn't.
fn hh_mm((t, fraction): (chrono::NaiveTime, String)) -> String {
use chrono::Timelike;
let (h, m, s) = (t.hour(), t.minute(), t.second());
if !fraction.is_empty() {
format!("{h:02}:{m:02}:{s:02}.{fraction}")
} else if s == 0 {
format!("{h:02}:{m:02}")
} else {
format!("{h:02}:{m:02}:{s:02}")
}
}
/// An ISO 8601 duration (`PT13H45M00S`, `P1DT2H`, `-PT1H`) or clock time (`13:45[:00]`) as
/// `hh:mm[:ss]`, a duration's days counted as hours and a negative one with a leading `-`.
/// `None` for anything else, years and months included.
fn iso_time(v: &str) -> Option<String> {
let t = v.trim();
let (negative, t) = match t.strip_prefix('-') {
Some(rest) => (true, rest),
None => (false, t),
};
let Some(t) = t.strip_prefix('P') else {
return if negative { None } else { clock_time(t).map(hh_mm) };
};
let (days, t, has_t) = match t.split_once('T') {
Some((days, time)) => (days, time, true),
None => (t, "", false),
};
// A `T` needs a time after it.
if has_t && t.is_empty() {
return None;
}
let mut any = !days.is_empty();
let days: u64 = if days.is_empty() { 0 } else { days.strip_suffix('D')?.parse().ok()? };
let (mut h, mut m, mut s) = (0u64, 0u64, 0u64);
// The seconds' fraction digits, kept as written.
let mut fraction = String::new();
let mut num = String::new();
// Units come in the order H, M, S, each at most once.
let mut next_unit = 0;
for c in t.chars() {
let unit = match c {
'H' => 1,
'M' => 2,
'S' => 3,
'0'..='9' | '.' if num.len() < 20 => {
num.push(c);
continue;
}
_ => return None,
};
if unit <= next_unit {
return None;
}
next_unit = unit;
let n = std::mem::take(&mut num);
match unit {
1 => h = n.parse().ok()?,
2 => m = n.parse().ok()?,
_ => {
let (whole, frac) = n.split_once('.').unwrap_or((&n, ""));
if whole.is_empty() || (n.contains('.') && frac.is_empty()) || !frac.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
s = whole.parse().ok()?;
fraction = frac.trim_end_matches('0').to_string();
}
}
any = true;
}
if !any || !num.is_empty() {
return None;
}
// A duration too long to count in hours is not a time.
m = m.checked_add(s / 60)?;
s %= 60;
h = h.checked_add(m / 60)?.checked_add(days.checked_mul(24)?)?;
m %= 60;
let sign = if negative && ((h, m, s) != (0, 0, 0) || !fraction.is_empty()) { "-" } else { "" };
Some(if !fraction.is_empty() {
format!("{sign}{h:02}:{m:02}:{s:02}.{fraction}")
} else if s == 0 {
format!("{sign}{h:02}:{m:02}")
} else {
format!("{sign}{h:02}:{m:02}:{s:02}")
})
}
fn cells_to_rows<C>(cells: &BTreeMap<CellRef, C>, fmt: impl Fn(&C) -> String) -> Vec<Vec<String>> {
let mut grid: BTreeMap<(u32, u32), String> = BTreeMap::new();
for (r, c) in cells {
@@ -208,3 +381,158 @@ fn grid_to_rows(grid: &BTreeMap<(u32, u32), String>) -> Vec<Vec<String>> {
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
/// An `.ods` package whose body is `tables` (`table:table` elements).
fn spreadsheet(tables: &str) -> Result<Vec<u8>, craft_odf::Error> {
let content = format!(
r#"<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"><office:body><office:spreadsheet>{tables}</office:spreadsheet></office:body></office:document-content>"#
);
let mut w = craft_odf::PackageWriter::new(craft_odf::mime::SPREADSHEET);
w.file("content.xml", "text/xml", content.as_bytes());
w.finish()
}
#[test]
fn ods_cells_read_their_typed_values() {
let book = spreadsheet(
r#"<table:table table:name="Guests">
<table:table-row><table:table-cell office:value-type="string"><text:p>Name</text:p></table:table-cell><table:table-cell table:number-columns-repeated="2"/><table:table-cell office:value-type="string"><text:p>When</text:p></table:table-cell><table:table-cell office:value-type="string" table:number-columns-repeated="2"><text:p>Tag</text:p></table:table-cell></table:table-row>
<table:table-row table:number-rows-repeated="2"><table:table-cell office:value-type="string" table:number-columns-spanned="2"><text:p>Ada<text:s text:c="2"/>L</text:p><text:p>x</text:p><office:annotation><text:p>note</text:p></office:annotation></table:table-cell><table:covered-table-cell office:value-type="string"><text:p>hidden</text:p></table:covered-table-cell><table:table-cell office:value-type="float" office:value="3.50"><text:p>3,5</text:p></table:table-cell><table:table-cell office:value-type="date" office:date-value="2024-03-05T00:00:00"><text:p>05/03/24</text:p></table:table-cell><table:table-cell office:value-type="boolean" office:boolean-value="false"><text:p>NO</text:p></table:table-cell><table:table-cell office:value-type="time" office:time-value="PT13H45M00S"><text:p>01:45 PM</text:p></table:table-cell></table:table-row>
<table:table-row><table:table-cell office:value-type="date" office:date-value="2024-03-05T13:45:30"><text:p>Tue</text:p></table:table-cell><table:table-cell office:value-type="date" office:date-value="not a date"><text:p>someday</text:p></table:table-cell><table:table-cell office:value-type="percentage" office:value="0.25"><text:p>25%</text:p></table:table-cell><table:table-cell office:value-type="currency" office:value="9"/></table:table-row>
</table:table>"#,
)
.unwrap();
let (_, rows) = read_rows(&book, Pick::Name("Guests")).unwrap();
assert_eq!(rows.len(), 4);
assert_eq!(rows[0], ["Name", "", "", "When", "Tag", "Tag"]);
assert_eq!(rows[1], ["Ada L\nx", "", "3.5", "2024-03-05", "FALSE", "13:45"]);
assert_eq!(rows[1], rows[2]);
assert_eq!(rows[3], ["2024-03-05 13:45:30", "someday", "25%", "9"]);
}
#[test]
fn an_ods_date_with_two_zones_reads_its_text() {
let book = spreadsheet(
r#"<table:table table:name="Dates">
<table:table-row><table:table-cell office:value-type="date" office:date-value="2024-03-05T13:45:00+02:00Z"><text:p>offset then Z</text:p></table:table-cell><table:table-cell office:value-type="date" office:date-value="2024-03-05T13:45:00Z+02:00"><text:p>Z then offset</text:p></table:table-cell><table:table-cell office:value-type="date" office:date-value="2024-03-05T13:45:00+02:00"><text:p>one zone</text:p></table:table-cell></table:table-row>
</table:table>"#,
)
.unwrap();
let (_, rows) = read_rows(&book, Pick::Name("Dates")).unwrap();
assert_eq!(rows, [["offset then Z", "Z then offset", "2024-03-05 13:45"]]);
}
#[test]
fn ods_dates_and_durations() {
assert_eq!(iso_time("PT1H59M59.6S").as_deref(), Some("01:59:59.6"));
assert_eq!(iso_time("PT0.25S").as_deref(), Some("00:00:00.25"));
assert_eq!(iso_time("PT59M60.50S").as_deref(), Some("01:00:00.5"));
assert_eq!(iso_time("PT0H0M59S").as_deref(), Some("00:00:59"));
assert_eq!(iso_time("PT1H2M3S").as_deref(), Some("01:02:03"));
assert_eq!(iso_time("PT1.S"), None);
assert_eq!(iso_time("P1000000000000000000D"), None);
}
#[test]
fn a_clock_time_keeps_its_seconds_fraction_as_written() {
assert_eq!(iso_datetime("2024-03-05T00:00:00.0000000001").as_deref(), Some("2024-03-05 00:00:00.0000000001"));
assert_eq!(iso_datetime("2024-03-05T13:45:30.1234567891Z").as_deref(), Some("2024-03-05 13:45:30.1234567891"));
assert_eq!(iso_datetime("2024-03-05T13:45:30.500+02:00").as_deref(), Some("2024-03-05 13:45:30.5"));
assert_eq!(iso_datetime("2024-03-05T00:00:00.000").as_deref(), Some("2024-03-05"));
assert_eq!(iso_time("13:45:00.1234567891").as_deref(), Some("13:45:00.1234567891"));
assert_eq!(iso_time("PT13H45M0.1234567891S").as_deref(), Some("13:45:00.1234567891"));
assert_eq!(iso_time("13:45:00."), None);
assert_eq!(iso_time("13:45:00.5x"), None);
assert_eq!(iso_time("13:45.5"), None);
assert_eq!(iso_time("23:59:60.5"), None);
assert_eq!(iso_time("13: 45.5"), None);
assert_eq!(iso_time("1:45:30.5").as_deref(), Some("01:45:30.5"));
}
#[test]
fn a_typed_ods_value_keeps_to_the_cell_limit() {
let long = format!("2024-03-05T13:45:30.{}", "1".repeat(MAX_CELL_CHARS));
let book = spreadsheet(&format!(
r#"<table:table table:name="Long"><table:table-row><table:table-cell office:value-type="date" office:date-value="{long}"><text:p>x</text:p></table:table-cell></table:table-row></table:table>"#
))
.unwrap();
let (_, rows) = read_rows(&book, Pick::Name("Long")).unwrap();
assert_eq!(rows[0][0].chars().count(), MAX_CELL_CHARS);
}
#[test]
fn a_date_alone_drops_its_zone() {
assert_eq!(iso_datetime("2024-03-05Z").as_deref(), Some("2024-03-05"));
assert_eq!(iso_datetime("2024-03-05+02:00").as_deref(), Some("2024-03-05"));
assert_eq!(iso_datetime("2024-03-05-05:00").as_deref(), Some("2024-03-05"));
assert_eq!(iso_datetime("2024-03-05+02:99"), None);
}
#[test]
fn a_zone_is_at_most_fourteen_hours() {
assert_eq!(iso_datetime("2024-03-05+14:00").as_deref(), Some("2024-03-05"));
assert_eq!(iso_datetime("2024-03-05-14:00").as_deref(), Some("2024-03-05"));
assert_eq!(iso_datetime("2024-03-05+14:01"), None);
assert_eq!(iso_datetime("2024-03-05-15:00"), None);
assert_eq!(iso_datetime("2024-03-05T13:45:00+14:00").as_deref(), Some("2024-03-05 13:45"));
assert_eq!(iso_datetime("2024-03-05T13:45:00+14:01"), None);
assert_eq!(iso_time("13:45:00-15:00"), None);
}
#[test]
fn a_zone_is_z_or_an_offset_not_both() {
assert_eq!(iso_datetime("2024-03-05T13:45:00+02:00Z"), None);
assert_eq!(iso_datetime("2024-03-05T13:45:00Z+02:00"), None);
assert_eq!(iso_datetime("2024-03-05+02:00Z"), None);
assert_eq!(iso_datetime("2024-03-05Z+02:00"), None);
assert_eq!(iso_time("13:45:00+02:00Z"), None);
assert_eq!(iso_time("13:45:00Z+02:00"), None);
assert_eq!(iso_datetime("2024-03-05T13:45:00Z").as_deref(), Some("2024-03-05 13:45"));
assert_eq!(iso_datetime("2024-03-05T13:45:00-05:00").as_deref(), Some("2024-03-05 13:45"));
assert_eq!(iso_time("13:45:00+02:00").as_deref(), Some("13:45"));
}
#[test]
fn a_zone_offset_has_two_digit_hours_and_minutes() {
assert_eq!(iso_datetime("2024-03-05T13:45:00+2:00"), None);
assert_eq!(iso_datetime("2024-03-05T13:45:00+ 2:00"), None);
assert_eq!(iso_time("13:45:00-5:00"), None);
}
#[test]
fn a_leap_second_is_not_a_time() {
assert_eq!(iso_datetime("2024-03-05T23:59:60Z"), None);
assert_eq!(iso_time("23:59:60"), None);
}
#[test]
fn a_duration_with_t_needs_a_time() {
assert_eq!(iso_time("P1DT"), None);
assert_eq!(iso_time("P0DT"), None);
assert_eq!(iso_time("P1D").as_deref(), Some("24:00"));
assert_eq!(iso_time("PT.S"), None);
assert_eq!(iso_time("13:45:00Z").as_deref(), Some("13:45"));
assert_eq!(iso_time("-PT1H").as_deref(), Some("-01:00"));
assert_eq!(iso_time("P2DT1H30M").as_deref(), Some("49:30"));
assert_eq!(iso_time("P1D").as_deref(), Some("24:00"));
assert_eq!(iso_time("P1Y2M"), None);
assert_eq!(iso_time("PT"), None);
assert_eq!(iso_time("PT5"), None);
assert_eq!(iso_time("PT1H2H"), None);
assert_eq!(iso_time("PT1S2H"), None);
assert_eq!(iso_datetime("2024-03-05T"), None);
assert_eq!(iso_datetime("2024-03-05T00:00:00.500").as_deref(), Some("2024-03-05 00:00:00.5"));
assert_eq!(iso_time("00:00:00.250").as_deref(), Some("00:00:00.25"));
assert_eq!(iso_time("25:00"), None);
assert_eq!(iso_datetime("2024-03-05T00:00:00.000").as_deref(), Some("2024-03-05"));
assert_eq!(iso_datetime("2024-03-05T13:45:30+02:00").as_deref(), Some("2024-03-05 13:45:30"));
assert_eq!(iso_datetime("2024-13-05"), None);
assert_eq!(iso_datetime("2023-02-29"), None);
assert_eq!(iso_datetime("2024-03-05junk"), None);
assert_eq!(iso_datetime("2024-03-05T13:99"), None);
}
}
+1 -1
View File
@@ -152,7 +152,7 @@ pub(crate) fn add(ctx: &mut Ctx, lay: &mut DocLayout) {
author_name(&cm.author),
CharProps { bold: Some(true), size: Some(9.0), color: Some(TextColor::Rgb(color)), ..Default::default() },
);
let pl = ctx.para_labelled(&head, inner, None, &[], None);
let pl = ctx.para_labelled(&head, inner, None, &[], 0.0, None);
let lead = pl.lines.first().map_or(0.0, |l| l.top.max(0.0));
push_para(&mut items, (story, &[HEADER_PATH]), &pl, (0, pl.lines.len()), (x, y + lead), inner, Edges::own(&pl, 0, pl.lines.len()));
y += pl.height + 2.0;
+19 -10
View File
@@ -276,17 +276,17 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
Block::Para(p) => {
// A paragraph after one whose mark is hidden goes on from that one's last line
// (Word, #3986; see `Joint`); one that shows nothing passes the place on.
let (mark_hidden, shows_nothing, taken) = Joint::arrive(ctx, &mut joint, (i, p), (width, frames), table);
let (mark_hidden, shows_nothing, taken) = Joint::arrive(ctx, &mut joint, (i, p), (width, frames), table, cell_frame);
let p = taken.as_ref().map_or(p, |t| &t.para);
let label = ctx.next_label(p);
let listed = label.is_some();
let mut pl = ctx.para_labelled(p, width, table, &[], label.clone());
let mut pl = ctx.para_labelled(p, width, table, &[], 0.0, label.clone());
// A text frame (a footer's page number in a frame, say) is placed apart, like a
// floating object, and the text after it wraps around it; it takes no room in
// the flow.
if let Some(fr) = pl.rp.frame.clone().filter(|fr| frames && cell_frame(fr)) {
let fw = fr.w.unwrap_or_else(|| natural_width(&pl)).clamp(1.0, 1584.0);
let pf = if (fw - width).abs() > 0.01 { ctx.para_labelled(p, fw, table, &[], label) } else { pl };
let pf = if (fw - width).abs() > 0.01 { ctx.para_labelled(p, fw, table, &[], 0.0, label) } else { pl };
let h = match fr.h {
Some(h) if fr.h_exact => h,
Some(h) => h.max(pf.height),
@@ -318,7 +318,8 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
// body path. Keep text and wrap exclusions relative to the text's actual top.
// A paragraph going on from a shared line has its origin at that line's top.
let para_top = taken.as_ref().map_or(y, |t| t.joint.top);
y += if i == 0 { before } else { before.max(0.0) };
let applied = if i == 0 { before } else { before.max(0.0) };
y += applied;
TakenUp::start(taken.as_ref(), &mut y, &mut excl);
// Floating objects anchored here: place them, then wrap the text around them.
// One left out of the layout (hidden, or deleted in the final text) takes no room.
@@ -364,7 +365,7 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
}
let rel = rel_exclusions(&excl, 0.0, y);
if !rel.is_empty() {
pl = ctx.para_labelled(p, width, table, &rel, label);
pl = ctx.para_labelled(p, width, table, &rel, applied, label);
}
TakenUp::clear(taken.as_ref(), &mut excl);
// Bordered paragraphs: room for their borders, those of a group joined in one box.
@@ -477,7 +478,7 @@ fn natural_width(pl: &ParaLayout) -> f32 {
}
/// A text frame's placement as a floating object's (`w:framePr` → anchors, alignment, wrap).
fn frame_float(fr: &wordcraft_doc::props::TextFrame) -> Float {
pub(crate) fn frame_float(fr: &wordcraft_doc::props::TextFrame) -> Float {
let anchor = |a: &str, text: Anchor| match a {
"page" => Anchor::Page,
"margin" => Anchor::Margin,
@@ -777,13 +778,14 @@ impl Joint {
(i, p): (usize, &Paragraph),
(width, frames): (f32, bool),
table: Option<&para::CellText>,
cell_frame: impl Fn(&wordcraft_doc::props::TextFrame) -> bool,
) -> (bool, bool, Option<TakenUp>) {
let chr = table.map(|t| &t.chr);
let mark_hidden = ctx.mark_hidden(p, chr);
let shows_nothing = mark_hidden && ctx.text_hidden(p, chr);
let came = joint.take().filter(|j| j.next == i);
*joint = came.filter(|_| shows_nothing).map(|j| Joint { next: i + 1, ..j });
let taken = came.filter(|_| !shows_nothing).and_then(|j| j.take_up(ctx, p, (width, frames), table));
let taken = came.filter(|_| !shows_nothing).and_then(|j| j.take_up(ctx, p, (width, frames), table, cell_frame));
(mark_hidden, shows_nothing, taken)
}
@@ -799,7 +801,7 @@ impl Joint {
/// taller than the text going on from it), with the room for its bottom border (Word).
pub(crate) fn fit(&self, ctx: &mut Ctx, q: &Paragraph, width: f32, table: Option<&para::CellText>) -> (f32, Vec<WrapArea>) {
let eq = ctx.eq_count;
let probe = again(ctx, eq, |ctx| ctx.para_labelled(q, width, table, &[], None));
let probe = again(ctx, eq, |ctx| ctx.para_labelled(q, width, table, &[], 0.0, None));
let (gap, height) = probe.lines.first().map_or((0.0, self.height), |l| ((self.baseline - (l.baseline - l.top)).max(0.0), l.height));
let rect = Rect::new(self.left, self.top, (self.end - self.left).max(0.0), (gap + height - 0.01).max(0.01));
let mut areas = vec![(rect, false, None, WrapText::Right, false)];
@@ -827,9 +829,16 @@ impl Joint {
/// Paragraph `p` of a box `width` wide going on from here, unless a page break comes before
/// it, it runs right to left or it is a text frame (`frames`: placed apart, sharing no line):
/// without its space before, as [`Joint::fit`] lays it out.
fn take_up(self, ctx: &mut Ctx, p: &Paragraph, (width, frames): (f32, bool), table: Option<&para::CellText>) -> Option<TakenUp> {
fn take_up(
self,
ctx: &mut Ctx,
p: &Paragraph,
(width, frames): (f32, bool),
table: Option<&para::CellText>,
cell_frame: impl Fn(&wordcraft_doc::props::TextFrame) -> bool,
) -> Option<TakenUp> {
let own = ctx.doc.styles.resolve_para_in(&p.props, table.map(|t| &t.para));
if own.page_break_before || own.bidi || (frames && own.frame.is_some()) {
if own.page_break_before || own.bidi || own.frame.as_ref().is_some_and(|fr| frames && cell_frame(fr)) {
return None;
}
let mut para = p.clone();
+5
View File
@@ -16,6 +16,9 @@ pub(crate) struct Key {
pub(crate) table: u64,
pub(crate) notes: u64,
pub(crate) excl: u64,
/// The space before the paragraph layout applied above it, which a Top-and-Bottom object in
/// it is laid out again below ([`para::ParaEnv::space_before`]).
pub(crate) space_before: u32,
pub(crate) eq: u32,
pub(crate) read_spacing: Option<u32>,
pub(crate) grid: (u32, u32, u32, bool),
@@ -149,6 +152,8 @@ pub(crate) fn env_hash(doc: &Document, cache: &mut LayoutCache, opts: &LayoutOpt
let outline = (opts.view == ViewMode::Outline).then(|| opts.outline.as_ref().is_some_and(|o| o.plain));
let mut h = std::collections::hash_map::DefaultHasher::new();
styles.hash(&mut h);
// The compatibility mode changes paragraph layout too (widow control in table cells).
doc.settings.compat_mode.hash(&mut h);
opts.show_hidden.hash(&mut h);
opts.hide_deleted.hash(&mut h);
opts.hide_marked.hash(&mut h);
+23 -5
View File
@@ -113,12 +113,21 @@ struct ParaEnvInput<'a> {
label: Option<(String, Level)>,
table: Option<&'a para::CellText>,
exclusions: &'a [para::Exclusion],
space_before: f32,
eq_number: u32,
typing_word: Option<(usize, usize)>,
fitted: &'a [(usize, f32)],
joined: bool,
}
/// The flow's wrap context for a paragraph's layout, as its cache key needs it: the areas text
/// flows around (relative to its first line) and the space before it the flow laid out, which
/// reaches up to them (see [`para::ParaEnv::space_before`]).
struct WrapAreas<'a> {
exclusions: &'a [para::Exclusion],
space_before: f32,
}
/// A header or footer (`story`) laid out for page `number` of a section (`sect`, `mirror`): its
/// table cells' floats placed on the page rather than in their cell ([`Float::outside_cell`],
/// Word's picture watermark in a header that starts with a table), drawn behind the header's
@@ -252,6 +261,7 @@ impl Ctx<'_> {
typing_word: None,
numeral: self.opts.numeral,
exclusions: &[],
space_before: 0.0,
eq_number: 0,
read_line_spacing: None,
grid: para::Grid::default(),
@@ -299,16 +309,18 @@ impl Ctx<'_> {
/// Lay out `p` with its already counted `label`, so laying a paragraph out again (around
/// floating objects, or after it moved) doesn't advance the list counters twice.
/// `space_before` is the space before `p` that the flow laid out above it ([`para::ParaEnv`]).
pub(crate) fn para_labelled(
&mut self,
p: &Paragraph,
width: f32,
table: Option<&para::CellText>,
exclusions: &[para::Exclusion],
space_before: f32,
label: Option<(String, Level)>,
) -> Arc<ParaLayout> {
let fitted = self.fitted_boxes(p);
let (key, eq_number) = self.para_key(p, width, table, exclusions, label.as_ref(), &fitted);
let (key, eq_number) = self.para_key(p, width, table, WrapAreas { exclusions, space_before }, label.as_ref(), &fitted);
self.cache.used.insert(key.clone());
if let Some(pl) = self.cache.paras.get(&key) {
self.cache.hits += 1;
@@ -323,6 +335,7 @@ impl Ctx<'_> {
label,
table,
exclusions,
space_before,
eq_number,
typing_word: typing,
fitted: &fitted,
@@ -347,7 +360,7 @@ impl Ctx<'_> {
return None;
}
let kept = (self.eq_count, self.uses_totals);
let (key, eq_number) = self.para_key(p, width, None, &[], label.as_ref(), &[]);
let (key, eq_number) = self.para_key(p, width, None, WrapAreas { exclusions: &[], space_before: 0.0 }, label.as_ref(), &[]);
(self.eq_count, self.uses_totals) = kept;
if key.typing.is_some() {
return None;
@@ -365,6 +378,7 @@ impl Ctx<'_> {
label,
table: None,
exclusions: &[],
space_before: 0.0,
eq_number,
typing_word: None,
fitted: &[],
@@ -387,7 +401,7 @@ impl Ctx<'_> {
measure: impl FnOnce(&ParaLayout) -> (f32, f32),
) -> (f32, f32) {
let fitted = self.fitted_boxes(p);
let (key, eq_number) = self.para_key(p, width, table, &[], label.as_ref(), &fitted);
let (key, eq_number) = self.para_key(p, width, table, WrapAreas { exclusions: &[], space_before: 0.0 }, label.as_ref(), &fitted);
self.cache.used.insert(key.clone());
if let Some(m) = self.cache.measures.get(&key) {
self.cache.hits += 1;
@@ -402,6 +416,7 @@ impl Ctx<'_> {
label,
table,
exclusions: &[],
space_before: 0.0,
eq_number,
typing_word: typing,
fitted: &fitted,
@@ -455,10 +470,11 @@ impl Ctx<'_> {
p: &Paragraph,
width: f32,
table: Option<&para::CellText>,
exclusions: &[para::Exclusion],
wrap: WrapAreas<'_>,
label: Option<&(String, Level)>,
fitted: &[(usize, f32)],
) -> (Key, u32) {
let WrapAreas { exclusions, space_before } = wrap;
let page = if has_page_fields(p) { Some(self.fields.page_key()) } else { None };
if self.track_totals && !self.uses_totals && has_total_fields(p) {
self.uses_totals = true;
@@ -483,6 +499,7 @@ impl Ctx<'_> {
table: table.map(|t| self.table_key(t)).unwrap_or(0),
notes: if p.objects.iter().any(|o| matches!(o, InlineObject::NoteRef { .. })) { self.notes_hash } else { 0 },
excl: if exclusions.is_empty() { 0 } else { hash_of(&format!("{exclusions:?}")) },
space_before: space_before.to_bits(),
eq: if eq_here > 0 { eq_number } else { 0 },
read_spacing: if self.opts.view == ViewMode::Read { self.opts.read_line_spacing.map(f32::to_bits) } else { None },
grid: self.grid.key(),
@@ -512,7 +529,7 @@ impl Ctx<'_> {
}
fn para_env<'b>(&'b self, input: ParaEnvInput<'b>) -> para::ParaEnv<'b> {
let ParaEnvInput { width, label, table, exclusions, eq_number, typing_word, fitted, joined } = input;
let ParaEnvInput { width, label, table, exclusions, space_before, eq_number, typing_word, fitted, joined } = input;
para::ParaEnv {
doc: self.doc,
width,
@@ -526,6 +543,7 @@ impl Ctx<'_> {
typing_word,
numeral: self.opts.numeral,
exclusions,
space_before,
eq_number,
read_line_spacing: if self.opts.view == ViewMode::Read { self.opts.read_line_spacing } else { None },
grid: self.grid,
+5 -2
View File
@@ -232,7 +232,10 @@ pub(crate) fn rel_exclusions(excl: &[WrapArea], x0: f32, y0: f32) -> Vec<para::E
side: *side,
table: *table,
})
.filter(|e| e.bottom > 0.0)
// Top-and-Bottom areas above the first line can still take room: they sit in the
// paragraph's space before, which Word lays out again below them (#7143). Side-wrapping
// areas there are above the text and take no room, as before.
.filter(|e| e.bottom > 0.0 || e.top_bottom)
.collect()
}
@@ -526,7 +529,7 @@ fn anchor_floats_but(
}
}
let rel = rel_exclusions(&body_wraps(ctx, pb), col_x, y0);
let pl = ctx.para_labelled(p, width, None, &rel, label.clone());
let pl = ctx.para_labelled(p, width, None, &rel, before, label.clone());
(rects, pl, rel)
}
+78 -17
View File
@@ -1,9 +1,9 @@
use super::boxes::{BoxInput, BoxLayout, Edges, Joint, joined, layout_box, push_para};
use super::boxes::{BoxInput, BoxLayout, Edges, Joint, frame_float, joined, layout_box, push_para};
use super::cache::has_page_number_fields;
use super::ctx::{Ctx, Joining};
use super::floats::{
FloatAnchor, LateFloats, ObjFrame, ObjectPlacement, anchor_floats, body_wraps, continued_exclusions, fitting, late_floats, place_late,
place_objects,
FloatAnchor, LateFloats, ObjFrame, ObjectPlacement, anchor_floats, body_wraps, continued_exclusions, fitting, float_rect, late_floats,
place_late, place_objects, wrap_area,
};
use super::notes::{DECOR_STORY, NoteBox, para_notes};
use super::page::{PageBuilder, PageFrame, item_bottom};
@@ -19,6 +19,9 @@ use crate::WRAP_RELAYS;
/// A body paragraph. One after a paragraph whose mark is hidden goes on from that one's last line,
/// as Word shows them, on one line (#3986): see [`Joint`].
pub(crate) fn place_para(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block: usize, body_top: f32) {
if place_page_text_frame(ctx, pb, p, block) {
return;
}
let joint = pb.joint.take().filter(|j| !pb.web && j.next == block && j.page == pb.pages.len() && j.col == pb.col);
let mark_hidden = ctx.mark_hidden(p, None);
// Nothing of it is shown: the place passes on to the paragraph after it.
@@ -96,6 +99,39 @@ fn unjoin(ctx: &mut Ctx, p: &Paragraph) {
}
}
fn place_page_text_frame(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block: usize) -> bool {
if pb.web {
return false;
}
let Some(fr) = ctx.doc.styles.resolve_para_in(&p.props, None).frame else { return false };
if fr.h_anchor != "page" || fr.v_anchor != "page" {
return false;
}
let width = fr.w.unwrap_or_else(|| pb.col_w()).clamp(1.0, 1584.0);
let label = ctx.next_label(p);
let pl = ctx.para_labelled(p, width, None, &[], 0.0, label);
let notes = para_notes(ctx.doc, p, &pl);
let mut new_notes = Vec::new();
for line in &pl.lines {
new_notes.extend(notes_on_line(ctx, pb, line, &notes, &new_notes));
}
add_notes(pb, new_notes, &notes, pl.lines.last().map_or(0, |line| line.c1));
let height = fr.h.map_or(pl.height, |h| if fr.h_exact { h } else { h.max(pl.height) });
let float = frame_float(&fr);
let page = PageFrame { sect: pb.sect, margin_top: None, origin: (0.0, 0.0), number: pb.number, mirror: ctx.mirror };
let rect = float_rect(Some(page), (pb.col_x(), pb.col_w()), pb.y, width, height, &float);
let path = [block as u32];
if let Some(page) = pb.page() {
push_para(&mut page.items, (StoryRef::Body, &path), &pl, (0, pl.lines.len()), (rect.x, rect.y), width, Edges::own(&pl, 0, pl.lines.len()));
}
// The body text after the frame wraps around it as its wrap mode says.
if let Some(area) = wrap_area(rect, &float, None) {
pb.framed.push(area.0);
pb.excl.push(area);
}
true
}
/// A closing mark before a continuous section takes no room after content. An otherwise empty
/// section starting a new page retains its paragraph line.
fn place_para_alone(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block: usize, body_top: f32) {
@@ -236,6 +272,10 @@ struct Flow<'a> {
label: Option<(String, Level)>,
/// Where it was expected to start; floats anchored here are placed again if it starts elsewhere.
guess: f32,
/// The space before it that its layout (`pl`) was broken with: the declared space before
/// until the flow settles what it really lays out, then that, so a later relay keeps a
/// Top-and-Bottom object in it pushing the first line to the same place.
space_applied: f32,
excl_mark: usize,
/// Where its automatic equation numbers start: each layout of it again counts from here.
eq_start: u32,
@@ -269,6 +309,21 @@ struct Flow<'a> {
}
impl<'a> Flow<'a> {
/// [`PageBuilder::fresh`] for this paragraph's text, which its negative indents take past the
/// column's edges: the first line's indent while it is still to place, the other lines'
/// indent while lines after the first are, on the physical sides the paragraph's direction
/// puts them.
fn fresh(&self, pb: &PageBuilder) -> bool {
let rp = &self.pl.rp;
let first = rp.indent_left + rp.indent_first;
let leading = match (self.l0 == 0, self.pl.lines.len() > 1) {
(true, true) => rp.indent_left.min(first),
(true, false) => first,
(false, _) => rp.indent_left,
};
let (leading, trailing) = ((-leading).max(0.0), (-rp.indent_right).max(0.0));
pb.fresh(if rp.bidi { (trailing, leading) } else { (leading, trailing) })
}
fn new(ctx: &mut Ctx, pb: &mut PageBuilder, p: &'a Paragraph, (block, body_top): (usize, f32)) -> Self {
let width = pb.col_w();
// Floating objects anchored here join the page's wrap areas before the text is laid out; if
@@ -288,6 +343,7 @@ impl<'a> Flow<'a> {
width,
label,
guess,
space_applied: space_before,
excl_mark,
eq_start,
float_rects,
@@ -324,13 +380,14 @@ impl<'a> Flow<'a> {
});
(self.float_rects, self.pl, self.rel) = (rects, pl, rel);
self.late = LateFloats::new(&late);
self.space_applied = before;
(self.laid_page, self.laid_width) = (pb.number, pb.col_w());
}
/// Lay the paragraph out again around the wrap areas `rel`, with its fields on their pages.
fn relay(&mut self, ctx: &mut Ctx, rel: &[para::Exclusion]) -> Arc<ParaLayout> {
let (p, width, eq_start, label) = (self.p, self.laid_width, self.eq_start, &self.label);
with_page_map(ctx, &mut self.page_map, |ctx| again(ctx, eq_start, |ctx| ctx.para_labelled(p, width, None, rel, label.clone())))
let (p, width, eq_start, label, space_before) = (self.p, self.laid_width, self.eq_start, &self.label, self.space_applied);
with_page_map(ctx, &mut self.page_map, |ctx| again(ctx, eq_start, |ctx| ctx.para_labelled(p, width, None, rel, space_before, label.clone())))
}
/// The space before the paragraph, after the one between it and the previous paragraph is
@@ -367,7 +424,7 @@ impl<'a> Flow<'a> {
// space before (Word's PDFs: 0 pt and 12 pt before put the text after it at the same place).
// Only that shape is observed: later pages and columns keep theirs.
if self.block == 1
&& pb.fresh()
&& self.fresh(pb)
&& !pb.web
&& pb.pages.last().is_some_and(|pg| pg.float_tables.contains(&Path::top(0)))
&& only_markers(self.p, 0..self.p.text.len())
@@ -444,7 +501,7 @@ impl<'a> Flow<'a> {
// (Against the whole column: balanced columns grow to hold it.)
// With the 0.01 pt of slack the other fit checks take. Balancing from Word 2013's layout
// keeps the lines and the next paragraph together at the top of a column too (#6821).
if pb.y + need > pb.bottom + 0.01 && (!pb.fresh() || Self::strict_widow_control(ctx, pb)) && need <= pb.next_room(self.body_top) {
if pb.y + need > pb.bottom + 0.01 && (!self.fresh(pb) || Self::strict_widow_control(ctx, pb)) && need <= pb.next_room(self.body_top) {
pb.advance(self.block, self.body_top);
unjoin(ctx, self.p);
pb.y += rp.space_before.min(0.0);
@@ -458,7 +515,7 @@ impl<'a> Flow<'a> {
/// paragraph, together there too: asks again, and places the paragraph's floats again where it
/// ends up (#6821).
fn keep_again(&mut self, ctx: &mut Ctx, pb: &mut PageBuilder, rooms: Rooms) {
while self.l0 == 0 && (self.pl.rp.keep_lines || self.pl.rp.keep_next) && pb.fresh() && Self::strict_widow_control(ctx, pb) {
while self.l0 == 0 && (self.pl.rp.keep_lines || self.pl.rp.keep_next) && self.fresh(pb) && Self::strict_widow_control(ctx, pb) {
let (col, pages) = (pb.col, pb.pages.len());
let before = self.keep_together(ctx, pb, rooms, 0.0);
if (pb.col, pb.pages.len()) == (col, pages) {
@@ -550,7 +607,7 @@ impl<'a> Flow<'a> {
if over && fit.l1 > l0 && !split {
break;
}
if over && fit.l1 == l0 && !pb.fresh() && !split && !self.stays_at_bottom(pb, l) {
if over && fit.l1 == l0 && !self.fresh(pb) && !split && !self.stays_at_bottom(pb, l) {
break;
}
fit.notes.extend(line_notes);
@@ -608,11 +665,11 @@ impl<'a> Flow<'a> {
// one (#6821).
let strict = Self::strict_widow_control(ctx, pb);
if fit.forced.is_none() && l1 < n && self.pl.rp.widow_control && n >= 2 {
if l1 - l0 == 1 && l0 == 0 && (!pb.fresh() || strict) {
if l1 - l0 == 1 && l0 == 0 && (!self.fresh(pb) || strict) {
l1 = l0; // orphan: move the first line to the next page
} else if n - l1 == 1 && (l1 - l0 >= 3 || (l0 > 0 && l1 - l0 >= 2)) {
l1 -= 1; // widow: take one more line along
} else if n - l1 == 1 && l0 == 0 && l1 - l0 == 2 && (!pb.fresh() || strict) {
} else if n - l1 == 1 && l0 == 0 && l1 - l0 == 2 && (!self.fresh(pb) || strict) {
// Neither split of a three-line paragraph is allowed (two and a widow, or an
// orphan and two): it moves whole, as in Word.
l1 = l0;
@@ -776,6 +833,7 @@ impl<'a> Flow<'a> {
(self.float_rects, self.pl, self.rel) = (rects, relaid, relaid_rel);
(self.laid_page, self.laid_width) = (pb.number, pb.col_w());
self.anchor_y = y0;
self.space_applied = 0.0;
self.l0 = k;
}
}
@@ -989,8 +1047,10 @@ fn place_para_in_flow(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block:
let mut f = Flow::new(ctx, pb, p, (block, body_top));
let spot = |pb: &PageBuilder| (pb.pages.len(), pb.col);
let placed_at = spot(pb);
// A continuous section's top mid-page is not a page top, so the break still applies.
let broke_before = f.pl.rp.page_break_before && !pb.fresh() && !pb.web;
// A continuous section's top mid-page is not a page top, so the break still applies. A
// page-anchored frame is not content above the paragraph, so it does not make the break
// apply either: the frame's wrap area moves the text below or beside it (#8577).
let broke_before = f.pl.rp.page_break_before && !pb.at_page_top() && !pb.web;
if broke_before {
pb.new_page(block, body_top);
}
@@ -1023,7 +1083,7 @@ fn place_para_in_flow(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block:
fit.l1 = end;
// On a fresh column an unfitting line can overflow. Strict widow control instead moves
// the lines on without emitting anything and must release their late floats as well.
let overflow = end == f.l0 && pb.fresh() && !widowed;
let overflow = end == f.l0 && f.fresh(pb) && !widowed;
if f.settle_late(pb, end, overflow) {
continue;
}
@@ -1085,7 +1145,7 @@ pub(crate) fn place_outline_para(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragr
let width = (pb.col_w() - indent - outline::SYMBOL_W).max(72.0);
let q = outline::outline_para(ctx.doc, p, o.view.plain);
ctx.fields.page = pb.number;
let pl = ctx.para_labelled(&q, width, None, &[], label);
let pl = ctx.para_labelled(&q, width, None, &[], 0.0, label);
pb.y += pl.rp.space_before.max(0.0);
let n = pl.lines.len();
let l1 = if o.view.first_line_only && level >= outline::BODY { n.min(1) } else { n };
@@ -1197,6 +1257,7 @@ fn next_first_line(ctx: &mut Ctx, block: usize, width: f32, depth: usize, new_pa
typing_word: None,
numeral: ctx.opts.numeral,
exclusions: &[],
space_before: 0.0,
eq_number: ctx.eq_count,
read_line_spacing: if ctx.opts.view == ViewMode::Read { ctx.opts.read_line_spacing } else { None },
grid: ctx.grid,
@@ -1311,7 +1372,7 @@ mod tests {
// Continue after the first line. The balance attempt can fit only one of the two lines left.
flow.l0 = 1;
pb.advance(0, top);
assert!(pb.fresh());
assert!(flow.fresh(pb));
assert!((pb.bottom - pb.top - height).abs() < 0.01);
flow.place_due_late(ctx, pb);
assert_eq!(pb.excl.len(), 1, "the anchor line fits before widow control");
@@ -1320,7 +1381,7 @@ mod tests {
assert_eq!(fit.l1, 2);
let (end, widowed) = flow.settled_end(ctx, pb, &fit);
assert_eq!((end, widowed), (1, true));
let overflow = end == flow.l0 && pb.fresh() && !widowed;
let overflow = end == flow.l0 && flow.fresh(pb) && !widowed;
assert!(!flow.settle_late(pb, end, overflow));
assert!(pb.excl.is_empty(), "no text is emitted here, so no wrap area may remain here");
});
+26 -9
View File
@@ -36,6 +36,27 @@ pub(crate) fn section_side(start: SectionStart, restart: Option<u32>, last: u32,
}
}
/// Whether `page` (after `prev`) is its section's first page, the one a different first page's
/// header and footer go on: the page where the section begins. A page's section is the one at its
/// top, so a section that starts continuously part-way down `prev` has no first page of its own:
/// Word shows the earlier section's header there and the section's default one from the next page
/// on, also when its first paragraph begins on `prev` and runs over. `sections` as
/// [`Document::sections`] gives them (each with its last block).
pub(crate) fn begins_section(sections: &[(usize, &SectionProps)], prev: Option<&Page>, page: &Page) -> bool {
if prev.is_some_and(|p| p.section == page.section) {
return false;
}
let start = page.section.checked_sub(1).and_then(|k| sections.get(k)).map_or(0, |(end, _)| end.saturating_add(1));
// A first paragraph (or table) that begins part-way down `prev` and runs over still began
// the section there.
let began_before = prev.is_some_and(|p| {
p.items
.iter()
.any(|it| matches!(it, Placed::Lines { story: StoryRef::Body, path, .. } if path.0.first().is_some_and(|&b| b as usize >= start)))
});
start >= page.first_block && !began_before
}
/// The document's sections with their headers and footers (Word's "link to previous"), each
/// section's resolved once for the whole layout in document order rather than by looking back
/// over the sections before it whenever one is needed.
@@ -174,12 +195,12 @@ pub(crate) fn header_table_areas(ctx: &mut Ctx, pb: &PageBuilder) -> Vec<Rect> {
return Vec::new();
}
let Some(page) = pb.pages.last() else { return Vec::new() };
let first = pb.pages.iter().rev().nth(1).is_none_or(|prev| prev.section != page.section);
let hf = Arc::clone(&ctx.hf);
let first = begins_section(&hf.sections, pb.pages.iter().rev().nth(1), page);
let key = (page.section, page.number, first);
if let Some(areas) = ctx.header_tables.get(&key) {
return areas.clone();
}
let hf = Arc::clone(&ctx.hf);
let Some((_, sect)) = hf.sections.get(page.section) else { return Vec::new() };
if sect.text_direction.is_turned() {
return Vec::new();
@@ -405,13 +426,9 @@ pub(crate) fn headers_footers(ctx: &mut Ctx, pages: &mut [Page], sections: &[(us
let hf = Arc::clone(&ctx.hf);
let even_odd = ctx.doc.settings.even_odd_headers;
let styles = styleref::headers_use_styleref(ctx.doc).then(|| ctx.cache.style_index(ctx.doc));
let mut first_of_section: HashSet<usize> = HashSet::new();
let mut seen = HashSet::new();
for (i, p) in pages.iter().enumerate() {
if seen.insert(p.section) {
first_of_section.insert(i);
}
}
let first_of_section: HashSet<usize> = (0..pages.len())
.filter(|&i| pages.get(i).is_some_and(|p| begins_section(sections, i.checked_sub(1).and_then(|k| pages.get(k)), p)))
.collect();
for (i, page) in pages.iter_mut().enumerate() {
let Some((_, sect)) = sections.get(page.section) else { continue };
// Inherit header/footer references from earlier sections (Word's "link to previous").
+24 -3
View File
@@ -210,10 +210,31 @@ impl NoteBox {
cuts
}
/// The least of the note that must stay with its reference: its first line (all of it if it
/// can't be split).
/// Whether widow/orphan control in the note's paragraphs forbids splitting at `cut`: a
/// paragraph's first line alone above it (an orphan) or its last line alone below it (a
/// widow), as in Word for Mac 16.114.4.
pub(crate) fn breaks_widow_control(&self, cut: f32) -> bool {
self.items.iter().filter(|it| self.splittable(it)).any(|it| {
let Placed::Lines { para, l0, l1, y, .. } = it else { return false };
let Some(first) = para.lines.get(*l0) else { return false };
let ends_at = |k: usize| para.lines.get(k).is_some_and(|l| (y + l.top - first.top + l.height - cut).abs() < 0.01);
let n = para.lines.len();
para.rp.widow_control && n >= 2 && ((*l0 == 0 && *l1 >= 2 && ends_at(0)) || (*l1 == n && ends_at(n - 2)))
})
}
/// Where the note may be split with its paragraphs' widow/orphan control kept, ascending.
pub(crate) fn kept_cuts(&self) -> Vec<f32> {
let mut cuts = self.cuts();
cuts.retain(|&c| !self.breaks_widow_control(c));
cuts
}
/// The least of the note that must stay with its reference: its first line, or more under
/// widow/orphan control (all of it if it can't be split).
pub(crate) fn first_piece(&self) -> f32 {
self.cuts().first().copied().unwrap_or(self.h).min(self.h)
// Widow/orphan control may keep more lines together (two, or a short paragraph whole).
self.kept_cuts().first().copied().unwrap_or(self.h).min(self.h)
}
/// Split the note at line bottom `cut`: the part above (`cut` tall) and the rest, moved up to
+42 -5
View File
@@ -96,6 +96,9 @@ pub(crate) struct PageBuilder<'a> {
pub(crate) early: &'a EarlyFloats,
/// ... and how many of the current page's `excl` they are (its first ones).
pub(crate) seeded: usize,
/// The wrap areas of the page-anchored body text frames on the current page. Text at the top
/// of a column that one of them reaches into gains room by moving on.
pub(crate) framed: Vec<Rect>,
/// No layout pass follows for floats found above their anchors: each is kept clear of the
/// text laid out before it ([`settle_early`]).
pub(crate) settle: bool,
@@ -163,7 +166,7 @@ impl PageBuilder<'_> {
// The note area starts below the text (a page of continued notes alone: at its top).
let area = self.bottom.max(self.body_floor());
let fits = total <= self.orig_bottom - area + 0.01;
let top = match (fits, self.beneath) {
let mut top = match (fits, self.beneath) {
(false, _) => area,
// Below the page's last line of text.
(true, true) => self.body_floor().min(self.orig_bottom - total),
@@ -176,12 +179,15 @@ impl PageBuilder<'_> {
let mut placed = Vec::new();
// Where the continuation notice goes, below a note that continues on the next page.
let mut notice_y = None;
// The bottom of what is placed (with the notice).
let mut end = y;
let mut rest = notes.into_iter();
while let Some(n) = rest.next() {
let room = self.orig_bottom - y;
if fits || n.h <= room + 0.01 {
let ny = y;
y += n.h;
end = y;
placed.push((n, ny));
continue;
}
@@ -189,21 +195,38 @@ impl PageBuilder<'_> {
// always leaves something here (its first line, or all of it if it can't be split),
// so continuing ends.
let first = placed.is_empty();
let cuts = n.cuts();
// Widow/orphan control in the note keeps two of a paragraph's lines on either side;
// the page's first note gives that up before it gives up the page's room.
let room = room - self.seps.notice_h();
match cuts.iter().rev().find(|&&c| c <= room + 0.01).or(cuts.first().filter(|_| first)).copied() {
let fit = |cuts: Vec<f32>| cuts.into_iter().rev().find(|&c| c <= room + 0.01);
let cut = fit(n.kept_cuts()).or_else(|| if first { fit(n.cuts()).or(n.cuts().first().copied()) } else { None });
match cut {
Some(c) => {
let (head, tail) = n.split(c);
notice_y = Some(y + head.h);
end = y + head.h + self.seps.notice_h();
placed.push((head, y));
self.carry.push(tail);
}
None if first => placed.push((n, y)),
None if first => {
end = y + n.h;
placed.push((n, y));
}
None => self.carry.push(n),
}
self.carry.extend(rest.by_ref());
break;
}
// Notes that continue on the next page still end on the bottom margin, the room left
// going above the separator (Word for Mac 16.114.4), unless they go beneath the text.
if !fits && !self.beneath {
let shift = (self.orig_bottom - end).max(0.0);
top += shift;
notice_y = notice_y.map(|ny| ny + shift);
for (_, ny) in &mut placed {
*ny += shift;
}
}
if let Some(pg) = self.pages.last_mut() {
match if cont { &self.seps.cont } else { &self.seps.sep } {
Some((items, _)) => pg.items.extend(items.iter().cloned().map(|mut it| {
@@ -354,6 +377,7 @@ impl PageBuilder<'_> {
let early = self.early;
self.excl.extend(early.get(&self.pages.len()).into_iter().flatten().map(|(_, _, a)| a.clone()));
self.seeded = self.excl.len();
self.framed.clear();
self.float_tables.clear();
if self.sect.line_numbers.as_ref().is_some_and(|l| l.restart == wordcraft_doc::section::LineNumberRestart::Page) {
self.line_no = 0;
@@ -487,9 +511,22 @@ impl PageBuilder<'_> {
/// At the top with nothing above on this page, so moving on gains no room. A continuous
/// section starting mid-page is at its top but not fresh: what doesn't fit there goes to the
/// next page (#3907).
pub(crate) fn fresh(&self) -> bool {
/// `reach` is how far the text reaches past the column's left and right edges (a paragraph's
/// negative indents).
pub(crate) fn fresh(&self, reach: (f32, f32)) -> bool {
self.at_page_top() && !self.framed_here(reach)
}
/// At the top of the page's text with nothing placed above it. A page-anchored frame is not
/// content above it: a paragraph with a page break before needs no new page for one.
pub(crate) fn at_page_top(&self) -> bool {
self.at_top() && self.top <= self.page_top + 0.01
}
/// A page-anchored body text frame's wrap area reaches into the current column's text,
/// widened by `reach` on the left and right.
fn framed_here(&self, (left, right): (f32, f32)) -> bool {
let (x0, x1) = (self.col_x() - left, self.col_x() + self.col_w() + right);
self.framed.iter().any(|r| r.x < x1 && r.right() > x0 && r.y < self.bottom && r.bottom() > self.y)
}
/// Move to the next column or page.
pub(crate) fn advance(&mut self, block: usize, body_top: f32) {
if self.col + 1 < self.cols.len() {
+2
View File
@@ -367,6 +367,7 @@ mod label_spacing_tests {
field_codes: false,
grid: Grid::default(),
exclusions: &[],
space_before: 0.0,
eq_number: 0,
numeral: crate::NumeralMode::default(),
read_line_spacing: None,
@@ -513,6 +514,7 @@ mod tests {
field_codes: false,
grid: Grid::default(),
exclusions: &[],
space_before: 0.0,
eq_number: 0,
numeral: Default::default(),
read_line_spacing: None,
+136 -11
View File
@@ -5,7 +5,7 @@ use super::chars::{
};
use super::grid::east_asian;
use super::model::{ClKind, Cluster, Enclosed, Glyph, ParaEnv, RubyLayout, StyleRun, SymbolRun};
use super::{Arc, Document, FaceRef, NumeralMode, ResolvedChar, RubyAlign, SOFT_HYPHEN};
use super::{Arc, Document, FaceRef, NumeralMode, OBJ, ResolvedChar, RubyAlign, SOFT_HYPHEN};
use wordcraft_fonts::ShapeContext;
pub(super) struct Builder<'a> {
@@ -52,6 +52,25 @@ struct SegmentInput<'a> {
context: &'a [bool],
}
/// Whether `face` draws `cluster`, a character and its combining marks, with no missing glyph.
/// The shaper composes a pair the face has a precomposed glyph for (`=` and U+0338 as `≠`), so a
/// face without the mark itself can still draw the pair.
fn draws_all(face: FaceRef, cluster: &str) -> bool {
let glyphs = wordcraft_fonts::shape_in(&face, cluster, &[], |c| c, ShapeContext::default());
!glyphs.is_empty() && glyphs.iter().all(|g| g.gid != 0)
}
/// A face other than `current` that draws all of `cluster` (CSS Fonts 4 §5.3, cluster matching):
/// the run's Thai face or its own font when one does, else the first face in fallback order with
/// every character of it that draws something.
fn cluster_face(cluster: &str, current: FaceRef, run_face: Option<FaceRef>, primary: FaceRef, bold: bool, italic: bool) -> Option<FaceRef> {
if let Some(f) = run_face.into_iter().chain([primary]).filter(|f| f.id() != current.id()).find(|f| draws_all(*f, cluster)) {
return Some(f);
}
let chars: Vec<char> = cluster.chars().filter(|c| draws_something(*c)).collect();
wordcraft_fonts::FontDb::global().fallback_for_run(&chars, primary.id(), bold, italic).map(|f| FaceRef::of(&f))
}
impl<'a> Builder<'a> {
/// Displayed form of `c` at run-relative byte `at` (Word › Numeral): one char in, one
/// char out. `rtl` is the shaping direction; in Context mode `context` (from
@@ -68,6 +87,10 @@ impl<'a> Builder<'a> {
let mut seg_start = 0;
let mut cur: Option<SegKey> = None;
let mut segs = Vec::new();
// The character the marks after it belong to: where it starts, and as drawn.
let mut base: Option<(usize, char)> = None;
// The character whose cluster was matched, and whether its marks stay with it.
let mut matched: Option<(usize, bool)> = None;
for (i, c) in text.char_indices() {
let rtl = use_levels && levels.get(lbase + i).is_some_and(|l| l % 2 == 1);
let c = show(c);
@@ -78,19 +101,67 @@ impl<'a> Builder<'a> {
_ => rc_cs.is_some() && rc.uses_complex(dc),
};
let primary = if complex { primary_cs.unwrap_or(primary) } else { primary };
let face = match cur {
Some(k) if mark => k.face,
let (bold, italic) = if complex { (rc.bold_cs, rc.italic_cs) } else { (rc.bold, rc.italic) };
// A mark stays in the face of the character it belongs to (Arabic harakat with their
// letter, so the letters join) while that face draws it. When it doesn't, the
// character and its marks go together to a face that draws them all (CSS Fonts 4
// §5.3, cluster matching). With no such face, a mark in left-to-right text that isn't
// complex script is matched on its own like any other character; in right-to-left or
// complex-script text it stays with its letter (#7865). A cluster is matched once, at
// its first mark the face lacks: matching it again at every later mark would make a
// long run of marks quadratic.
let mut with_base = false;
let mut moved = None;
if let Some(k) = cur.filter(|_| mark) {
let current = k.face.unwrap_or(primary);
with_base = !draws_something(c) || current.covers(dc);
if !with_base {
match (base.filter(|(at, _)| *at >= seg_start), matched) {
(Some((at, _)), Some((done, stays))) if done == at => with_base = stays,
(Some((at, b)), _) => {
let marks = text.get(at..).unwrap_or("").chars().skip(1).map(show).take_while(|m| is_mark(*m));
let all: String = std::iter::once(b).chain(marks).inspect(|_| crate::work::steps(1)).collect();
if draws_all(current, &all) {
with_base = true;
} else if let Some(f) = cluster_face(&all, current, run_face, primary, bold, italic) {
// The character goes to that face with its marks.
if at > seg_start {
segs.push((seg_start, at, k));
seg_start = at;
}
let face = (f.id() != primary.id()).then_some(f);
cur = Some(SegKey { face, ..k });
moved = Some(face);
} else {
with_base = k.complex || k.rtl;
}
matched = Some((at, with_base || moved.is_some()));
}
(None, _) => with_base = k.complex || k.rtl,
}
}
}
if !mark {
base = (!c.is_control() && c != OBJ).then_some((i, dc));
}
let face = match (moved, cur) {
(Some(face), _) => face,
(None, Some(k)) if with_base => k.face,
_ if !complex && east_asian(c) && primary_ea.is_some_and(|f| f.covers(c)) => primary_ea,
_ if !c.is_control() && c != SOFT_HYPHEN && run_face.is_some_and(|f| f.covers(dc)) => run_face,
_ if primary.covers(dc) || c.is_whitespace() || c.is_control() || c == SOFT_HYPHEN => None,
Some(SegKey { face: Some(face), .. }) if face.covers(dc) => Some(face),
(None, Some(SegKey { face: Some(face), .. })) if face.covers(dc) => Some(face),
_ if !complex && ea_face.is_some() && crate::kinsoku::is_east_asian(c) => ea_face,
_ => {
let (bold, italic) = if complex { (rc.bold_cs, rc.italic_cs) } else { (rc.bold, rc.italic) };
wordcraft_fonts::FontDb::global().fallback_styled(dc, primary.id(), bold, italic).map(|f| FaceRef::of(&f))
}
_ => wordcraft_fonts::FontDb::global().fallback_styled(dc, primary.id(), bold, italic).map(|f| FaceRef::of(&f)),
};
let key = SegKey { face, small: rc.small_caps && !rc.caps && c.is_lowercase(), complex, rtl };
// A mark is set like the character it belongs to, as for `complex`: in small capitals at
// that character's size, so the two stay in one shaping run and its cluster is matched
// whole.
let small = match cur {
Some(k) if mark => k.small,
_ => rc.small_caps && !rc.caps && c.is_lowercase(),
};
let key = SegKey { face, small, complex, rtl };
match cur {
Some(previous) if previous.same(&key) => {}
Some(previous) => {
@@ -139,6 +210,15 @@ impl<'a> Builder<'a> {
// the height Word gives it.
let (a, d) = match wordcraft_fonts::word::symbol_line(&rc.font, &r) {
Some((a, d)) => (a * face.upem, d * face.upem),
// A character Times New Roman or its metric twin lacks: the twin lacks more than
// Times New Roman ("‒", "₽" in Liberation Serif), so the line is as tall as the run's
// font, as with Times New Roman in Word, not as the taller fallback. East Asian text
// keeps its face's height.
None if face_override.is_some() && is_times_twin(&r.face.family) && !face.is_east_asian() => {
let (a, d) = wordcraft_fonts::word::line_metrics(&r.face);
let k = face.upem / r.face.upem.max(1.0);
(a * k, d * k)
}
None => wordcraft_fonts::word::line_metrics(&face),
};
let k = size as f64 / face.upem.max(1.0);
@@ -422,12 +502,15 @@ impl<'a> Builder<'a> {
let ge = bounds.get(bi + 1).copied().unwrap_or(shape_text.len());
let g0 = self.glyphs.len() as u32;
let mut adv = 0.0f32;
// What kerning added to the last glyph's advance: its pair with the next glyph.
let mut kern = 0.0f32;
while let Some(g) = shaped.get(gi) {
if g.cluster >= ge {
break;
}
self.glyphs.push(Glyph { gid: g.gid, dx: adv + g.x_offset as f32 * k * hscale, dy: g.y_offset as f32 * k });
adv += g.x_advance as f32 * k * hscale;
kern = if rc.kerned() && !key.rtl { pair_with_next(g, st.face.advance(g.gid)) * k * hscale } else { 0.0 };
gi += 1;
}
let g1 = self.glyphs.len() as u32;
@@ -455,6 +538,7 @@ impl<'a> Builder<'a> {
obj_h: 0.0,
obj_d: 0.0,
dot: s == "." || s == ",",
kern: if kind == ClKind::Text && g1 == g0 + 1 { kern } else { 0.0 },
});
}
if matches!(dir, Dir::Para) {
@@ -527,6 +611,7 @@ impl<'a> Builder<'a> {
obj_h: 0.0,
obj_d: 0.0,
dot: false,
kern: 0.0,
});
return;
};
@@ -560,7 +645,20 @@ impl<'a> Builder<'a> {
let style = first.style;
let g1 = added.last().map(|c| c.g1).unwrap_or(g0);
self.shown.push((self.clusters.len(), text.to_string(), ranges));
self.clusters.push(Cluster { start, end, adv: x, kind: ClKind::Text, style, g0, g1, break_after: false, obj_h: 0.0, obj_d: 0.0, dot: false });
self.clusters.push(Cluster {
start,
end,
adv: x,
kind: ClKind::Text,
style,
g0,
g1,
break_after: false,
obj_h: 0.0,
obj_d: 0.0,
dot: false,
kern: 0.0,
});
}
/// Shape `texts` on top of one another as one cluster for `start..end`: each aligned within
@@ -610,11 +708,38 @@ impl<'a> Builder<'a> {
if !text.is_empty() {
self.shown.push((k, text, ranges));
}
self.clusters.push(Cluster { start, end, adv, kind: ClKind::Text, style, g0, g1, break_after: false, obj_h: 0.0, obj_d: 0.0, dot: false });
self.clusters.push(Cluster {
start,
end,
adv,
kind: ClKind::Text,
style,
g0,
g1,
break_after: false,
obj_h: 0.0,
obj_d: 0.0,
dot: false,
kern: 0.0,
});
Some(k)
}
}
/// What kerning added to a glyph's advance (in font units) for its pair with the next glyph. An
/// old-style `kern` table's pair is split between its two glyphs, the second's half in its advance
/// and its offset alike: that half is the pair with the glyph before, which stays on the line.
fn pair_with_next(g: &wordcraft_fonts::ShapedGlyph, plain_advance: f64) -> f32 {
let added = g.x_advance as f32 - plain_advance as f32;
let before = if added != 0.0 { g.x_offset as f32 } else { 0.0 };
added - before
}
/// Times New Roman or one of its metric twins.
fn is_times_twin(family: &str) -> bool {
["Times New Roman", "Liberation Serif", "Tinos"].iter().any(|f| family.eq_ignore_ascii_case(f))
}
/// Lay out an `EQ \o` field (ECMA-376 Part 1 §17.16.5.20): its arguments drawn on top of one
/// another, as one cluster. An enclosure symbol among them (○ □ △ ◇, see
/// [`wordcraft_doc::eq::EncloseShape`]) is drawn as a shape around the text rather than as a
+2 -1
View File
@@ -55,7 +55,8 @@ pub(super) fn caps_expands(c: char) -> bool {
}
/// Combining marks and joiners (bidi classes NSM, BN: harakat, ZWNJ, ZWJ) belong to the
/// character before them: same font, same shaping run, so Arabic joining isn't broken.
/// character before them: same font, same shaping run, so Arabic joining isn't broken. A mark
/// that font can't draw takes its character to a face that draws both (`segment_keys`, #7865).
pub(super) fn is_mark(c: char) -> bool {
use unicode_bidi::BidiClass::{BN, NSM};
// No ASCII character is a mark (its BN characters are controls).
+76 -9
View File
@@ -14,6 +14,9 @@ const MIN_LINE_WIDTH: f32 = 1.0;
struct Breaker<'e> {
level: Option<&'e Level>,
rp: wordcraft_doc::resolve::ResolvedPara,
/// The space before the paragraph that the flow laid out above it, which a Top-and-Bottom
/// object in it is laid out again below (see [`ParaEnv::space_before`]).
space_before: f32,
mark_style: u32,
exclusions: &'e [Exclusion],
n: usize,
@@ -220,6 +223,7 @@ impl<'e> Breaker<'e> {
// Exact spacing fixes the table-contact boundary even when the mark has other metrics.
// Keep the existing estimate for shapes and for non-exact spacing.
table_h: if let LineSpacing::Exactly(h) = rp.line_spacing { h } else { est_h },
space_before: env.space_before,
rp,
first_x0: None,
hcache: Vec::new(),
@@ -262,6 +266,26 @@ impl<'e> Breaker<'e> {
let mut guard = 0;
loop {
let lo = self.row_left(pl);
// A Top-and-Bottom object ending in the paragraph's space before (or reaching into
// its first line) is a block the first line must start below, with that space before
// laid out again under it (#7143). Exclusions are relative to the first line, so look
// `space_before` above it too: the space the flow actually laid out, so an object
// above a gap that collapsing, contextual spacing or a page top removed takes no
// room, while the part of a merged gap that was laid out still does.
if self.first && self.space_before > 0.0 {
let before = self.space_before;
let row = (self.top - before, self.est_h + before, self.table_h);
if let Some(below) = self
.exclusions
.iter()
.filter(|e| e.top_bottom)
.filter(|e| e.intersects_row(row.0, row.1, row.2, lo, self.base_right))
.map(|e| e.bottom)
.reduce(f32::max)
{
self.top = self.top.max(below + before);
}
}
let row = (self.top, self.est_h, self.table_h);
match row_spans(self.exclusions, row, (lo, self.base_right), self.tight_indent).map(|mut spans| (spans.pop_front(), spans)) {
Ok((Some((a, b)), rest)) => {
@@ -442,7 +466,7 @@ impl<'e> Breaker<'e> {
/// tallest picture on it (which sits on the baseline).
fn extents(&self, pl: &ParaLayout, (c0, c1): (usize, usize)) -> Extents {
let rp = &self.rp;
let mut ex = Extents { asc: 0.0, desc: 0.0, obj_asc: 0.0, obj_desc: 0.0, text: false };
let mut ex = Extents { asc: 0.0, desc: 0.0, obj_asc: 0.0, obj_desc: 0.0, text: false, single: 0.0 };
let mut any = false;
let dropped = pl.drop_cap.map_or(0, |d| d.0);
for (k, c) in pl.clusters.get(c0..c1).into_iter().flatten().enumerate() {
@@ -486,6 +510,7 @@ impl<'e> Breaker<'e> {
};
ex.asc = ex.asc.max(a);
ex.desc = ex.desc.max(d);
ex.single = ex.single.max(a + d);
any = true;
// Text needs its descent below the line; so do inline math (an object with its own
// descent) and a check box. A line break ending the line is no text.
@@ -503,7 +528,7 @@ impl<'e> Breaker<'e> {
/// The line's height, baseline and text extent.
fn measure(&self, pl: &ParaLayout, range: (usize, usize)) -> Measure {
let rp = &self.rp;
let Extents { mut asc, mut desc, obj_asc, obj_desc, text } = self.extents(pl, range);
let Extents { mut asc, mut desc, obj_asc, obj_desc, text, single } = self.extents(pl, range);
let mut text_natural = asc + desc;
let font_desc = desc;
desc = desc.max(obj_desc);
@@ -554,6 +579,10 @@ impl<'e> Breaker<'e> {
}
}
}
// Multiple spacing adds (m - 1) x the tallest of the line's runs, not of the line: a line
// mixing fonts is as much taller as its runs' extents make it, once (Word for Mac and
// Windows: 10 pt Times New Roman with 10 pt Courier New at 1.5 and double spacing).
let run_leading = if single > 0.0 && !pictures_alone { single.min(text_natural) } else { text_natural };
// Keep the picture floor independent of list-label metrics.
let natural = asc + desc;
let pictures = if obj_asc > asc { obj_asc + desc } else { 0.0 };
@@ -562,7 +591,9 @@ impl<'e> Breaker<'e> {
let (height, centred) = match (rp.line_spacing, grid) {
(LineSpacing::Multiple(m), Some(g)) => ((g.snap_height(natural) * m).max(g.snap_height(pictures)), true),
(LineSpacing::AtLeast(v), Some(g)) => (g.snap_height(natural.max(pictures)).max(v), true),
(LineSpacing::Multiple(m), None) => ((text_natural * m + label_extra).max(text_pictures + (m - 1.0).max(0.0) * font_natural), false),
(LineSpacing::Multiple(m), None) => {
((text_natural + (m - 1.0) * run_leading + label_extra).max(text_pictures + (m - 1.0).max(0.0) * font_natural), false)
}
(LineSpacing::AtLeast(v), None) => (natural.max(text_pictures).max(v), false),
(LineSpacing::Exactly(v), _) => (v, false),
};
@@ -745,6 +776,8 @@ struct Extents {
obj_desc: f32,
/// Whether the line holds text besides its pictures (spaces and tabs don't count).
text: bool,
/// The tallest of its runs' own heights (ascent plus descent): the multiple's leading.
single: f32,
}
/// A line's height and baseline, and the extent of its text.
@@ -876,6 +909,14 @@ impl Scan {
bk.wrapped_tab = Some(j);
return true;
}
if bk.wrapped_tab == Some(j) && self.narrowed && stop.pos > bk.base_right + 0.01 && bk.skipped < 50 {
// A left tab past the right indent that wrapped into a span narrowed by a
// floating object (the far side of it, say): like Word, it goes on to the
// first line clear of the object (#6577). A stop inside the right indent
// keeps the zero-width path below.
self.skip = true;
return true;
}
if bk.wrapped_tab == Some(j) {
// Still past the right indent on the line it wrapped to: it takes no
// room, and its text starts at the indent rather than on a line of its own.
@@ -909,19 +950,33 @@ impl Scan {
}
self.x += w;
}
_ => self.pending_tab = Some((j, stop, self.x)),
_ => {
// A right tab's room grows from nothing with its text (a tab moved on from the
// line before may still hold the width it had there).
if stop.align == TabAlign::Right
&& let Some(c) = pl.clusters.get_mut(j)
{
c.adv = 0.0;
}
self.pending_tab = Some((j, stop, self.x));
}
}
if stop.leader != TabLeader::None {
self.leaders.push((j, stop.leader));
}
}
/// Whether text after a right/centre tab grows leftwards into the tab's space first.
/// Whether text after a right/centre tab grows leftwards into the tab's space first. Up to a
/// right stop it fits even past the right indent (Word: a TOC entry whose text ends
/// less than a digit short of the indent keeps its page number on its line when the stop is
/// at the margin); unshifted, the text after the tab ends at `x - room`.
fn absorbs(&self, pl: &ParaLayout, advance: f32) -> bool {
self.pending_tab.is_some_and(|(tj, stop, _)| {
let room = pl.clusters.get(tj).map(|t| t.adv).unwrap_or(0.0);
match stop.align {
TabAlign::Right | TabAlign::Decimal => room >= advance,
// Not where a floating object narrows the line: the text would run into it.
TabAlign::Right => room >= advance || (!self.narrowed && self.x - room + advance <= stop.pos + 0.01),
TabAlign::Decimal => room >= advance,
TabAlign::Center => room >= advance / 2.0 && self.x + advance / 2.0 <= self.right_edge + 0.01,
_ => false,
}
@@ -947,7 +1002,7 @@ impl Scan {
0.0
};
let fits = absorbs
|| self.x + advance - pl.auto_space_after(j) <= self.right_edge + shrink + 0.01
|| self.x + advance - pl.auto_space_after(j) - line_end_kern(pl, j) <= self.right_edge + shrink + 0.01
|| c.kind == ClKind::Space
|| c.kind == ClKind::Marker;
if !fits && pl.is_edit_boundary(c.start) && (c0..j).any(|k| pl.clusters.get(k).is_some_and(takes_room)) {
@@ -997,7 +1052,9 @@ impl Scan {
/// Text after a decimal/centre/right tab shifts as it grows.
fn shift_pending_tab(&mut self, pl: &mut ParaLayout) {
let Some((tj, stop, tx)) = self.pending_tab else { return };
let seg_w = self.x - tx;
// For a right tab `x` includes the room the tab has so far (it starts from none).
let old = pl.clusters.get(tj).map(|c| c.adv).unwrap_or(0.0);
let seg_w = self.x - tx - if stop.align == TabAlign::Right { old } else { 0.0 };
let shift = match stop.align {
TabAlign::Right => stop.pos - tx - seg_w,
TabAlign::Center => stop.pos - tx - seg_w / 2.0,
@@ -1006,7 +1063,6 @@ impl Scan {
_ => 0.0,
};
let shift = shift.max(0.0);
let old = pl.clusters.get(tj).map(|c| c.adv).unwrap_or(0.0);
if (shift - old).abs() > 0.001 {
let delta = shift - old;
if let Some(c) = pl.clusters.get_mut(tj) {
@@ -1114,6 +1170,17 @@ impl Scan {
}
}
/// The kerning cluster `j` loses when the line ends after it inside a word: Word measures a line's
/// last letter without its pair with the letter that goes on to the next line (a cell's width
/// swept a twip at a time in Word: the letters before a broken kerning pair fit only where they
/// fit on their own, without the pair).
fn line_end_kern(pl: &ParaLayout, j: usize) -> f32 {
match (pl.clusters.get(j), pl.clusters.get(j + 1)) {
(Some(c), Some(next)) if next.kind == ClKind::Text => c.kern,
_ => 0.0,
}
}
/// Narrowest span text flows into beside a floating object, points. Word puts an empty
/// paragraph beside a floating table in a 21.3pt gap but not in an 18.6pt one.
const MIN_SPAN: f32 = 20.0;
+10 -1
View File
@@ -147,6 +147,9 @@ pub struct Cluster {
pub obj_d: f32,
/// The cluster is a decimal separator (decimal tabs align on it).
pub dot: bool,
/// The kerning between this cluster and the next (part of `adv`, usually negative): a line
/// that ends between them lays the cluster out without it.
pub kern: f32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -391,8 +394,14 @@ pub struct ParaEnv<'a> {
/// How digits look on screen (an unresolved `System` shows Western digits).
pub numeral: NumeralMode,
/// Areas text must flow around (floating objects), relative to the paragraph: x from the
/// column's left edge, y from the top of the first line.
/// column's left edge, y from the top of the first line (its top with the space before
/// applied, which is where [`ParaEnv::space_before`] reaches up to).
pub exclusions: &'a [Exclusion],
/// The space before the paragraph that the flow above it actually laid out: its declared
/// space before less what collapsing against the previous paragraph's space after, contextual
/// spacing or a page top took away (and the negative space applied at a page top). A
/// Top-and-Bottom object reaching into it is laid out again below it (#7143).
pub space_before: f32,
/// Automatic equation numbers used before this paragraph.
pub eq_number: u32,
pub read_line_spacing: Option<f32>,
+12 -1
View File
@@ -62,6 +62,7 @@ impl Slot {
obj_h,
obj_d,
dot: false,
kern: 0.0,
}
}
}
@@ -101,6 +102,11 @@ fn is_special(c: char) -> bool {
fn paragraph_props(p: &Paragraph, env: &ParaEnv) -> ResolvedPara {
let doc = env.doc;
let mut rp = doc.styles.resolve_para_in(&p.props, env.table.map(|t| &t.para));
// Before Word 2013 layout (compatibility mode 15) a row split across pages divides its cells'
// text at any line: widow/orphan control doesn't apply in a table (measured in modes 12, 14).
if env.table.is_some() && doc.settings.compat_mode < wordcraft_doc::COMPAT_MODE_CURRENT {
rp.widow_control = false;
}
if let Some(spacing) = env.read_line_spacing.filter(|s| s.is_finite() && (1.0..=2.0).contains(s)) {
rp.line_spacing = wordcraft_doc::props::LineSpacing::Multiple(spacing);
}
@@ -546,7 +552,12 @@ fn list_label(cx: &Cx, b: &mut Builder, mark_style: u32) -> Option<Label> {
let break_only =
b.clusters.iter().any(|c| c.kind == ClKind::PageBreak) && b.clusters.iter().all(|c| matches!(c.kind, ClKind::PageBreak | ClKind::Marker));
let (text, lvl) = cx.env.label.as_ref().filter(|_| !break_only && !cx.env.joined)?;
let rc = cx.res.char(&p.mark.clone().overlaid(&lvl.chr));
let mut rc = cx.res.char(&p.mark.clone().overlaid(&lvl.chr));
// Word never kerns a list number, whatever the kerning of the paragraph mark or the level
// (measured in Word for Mac: "11)" in Times New Roman with kerning on is 16 pt wide, not
// the 15.55 pt of the kerned "11", so it passes a 312-twip hanging indent and the text goes on
// to the next tab stop).
Arc::make_mut(&mut rc).kern = 0.0;
// A bullet no installed font can draw would come from whatever icon font has its
// private-use code (Font Awesome's Twitter logo at U+F081, #1683): it shows the level's
// default bullet instead.
+6 -4
View File
@@ -237,6 +237,7 @@ fn new_page_builder<'p>(
leading_floor: 0.0,
early,
seeded: 0,
framed: Vec::new(),
settle,
column_lines: None,
}
@@ -446,9 +447,10 @@ fn section_endnotes(ctx: &mut Ctx, pb: &mut PageBuilder, endnotes: &mut VecDeque
/// the turned pages of vertical sections.
fn finish_pages(pb: PageBuilder, doc: &Document, sections: &[(usize, &SectionProps)], web: bool) -> Vec<Page> {
let mut pb = pb;
pb.close_column_lines();
pb.apply_valign();
pb.flush_notes();
// Each page is aligned once, before its notes go on it: `finish_page` leaves the page
// top-aligned after, so a page of continued notes isn't moved down again past the bottom
// margin when the next one starts.
pb.finish_page();
let last_block = doc.body.len().saturating_sub(1);
for _ in 0..MAX_NOTE_PAGES {
if pb.carry.is_empty() {
@@ -456,7 +458,7 @@ fn finish_pages(pb: PageBuilder, doc: &Document, sections: &[(usize, &SectionPro
}
let top = pb.top;
pb.new_page(last_block, top);
pb.flush_notes();
pb.finish_page();
}
pb.carry.clear();
pb.raise_front();
+62 -5
View File
@@ -248,6 +248,7 @@ pub fn measure_table_columns(doc: &wordcraft_doc::Document, t: &Table) -> Vec<(f
// Measurement uses a fixed environment (like show_hidden/proofing above).
numeral: crate::NumeralMode::default(),
exclusions: &[],
space_before: 0.0,
eq_number: 0,
read_line_spacing: None,
grid: crate::para::Grid::default(),
@@ -616,6 +617,51 @@ fn table_frame(ctx: &mut Ctx, t: &Table, avail: f32, depth: usize, style: Option
}
pub fn layout_table(ctx: &mut Ctx, story: StoryRef, t: &Table, path: &[u32], avail: f32, depth: usize) -> TableLayout {
layout_table_rows(ctx, story, t, path, avail, depth, None)
}
/// Row `ri` of the body table laid out again for where it lands on a page, `room` points above the
/// bottom of the page body: a merged cell starting in it that runs on past the page end is
/// aligned (and its turned text laid out) within that room, as its text is drawn with this row.
/// The row's height is the one [`layout_table`] gave it.
pub fn layout_table_row_in(ctx: &mut Ctx, t: &Table, path: &[u32], avail: f32, ri: usize, room: f32) -> Option<RowLayout> {
// A look ahead: list and equation numbers in the cells don't count again.
let (counters, eq_count) = (ctx.counters.clone(), ctx.eq_count);
let mut tl = layout_table_rows(ctx, StoryRef::Body, t, path, avail, 1, Some((ri, room)));
(ctx.counters, ctx.eq_count) = (counters, eq_count);
tl.rows.pop()
}
/// How many rows after row `ri` the merged cells starting in it run on (0 without any).
pub(crate) fn merge_rows_after(t: &Table, ri: usize) -> usize {
let Some(row) = t.rows.get(ri) else { return 0 };
let mut gx = row.first_grid();
let mut most = 0;
for c in &row.cells {
let g = gx;
gx += c.span();
if c.props.vmerge != VMerge::Restart {
continue;
}
let mut k = ri + 1;
while t.rows.get(k).is_some_and(|r| {
let mut gx = r.first_grid();
r.cells.iter().any(|x| {
let at = gx;
gx += x.span();
at == g && x.props.vmerge == VMerge::Continue
})
}) {
k += 1;
}
most = most.max(k - ri - 1);
}
most
}
/// [`layout_table`], or with `only` = (row, room) just that row, its merged cells aligned within
/// `room` (see [`layout_table_row_in`]).
fn layout_table_rows(ctx: &mut Ctx, story: StoryRef, t: &Table, path: &[u32], avail: f32, depth: usize, only: Option<(usize, f32)>) -> TableLayout {
let style = table_style(ctx, t);
// Cell text formatting and looks per set of style parts, built once per table.
let mut cell_text: Vec<(Region, CellText)> = Vec::new();
@@ -797,7 +843,7 @@ pub fn layout_table(ctx: &mut Ctx, story: StoryRef, t: &Table, path: &[u32], ava
rows.push(cells);
}
grow_vertical_merges(&rows, &mut heights);
finish_table_rows(ctx, TableRows { story, table: t, path, depth, cell_text, rows, heights, bottoms, edges, x, total })
finish_table_rows(ctx, TableRows { story, table: t, path, depth, cell_text, rows, heights, bottoms, edges, x, total, only })
}
fn grow_vertical_merges(rows: &[Vec<CellBox>], heights: &mut [f32]) {
@@ -832,13 +878,15 @@ struct TableRows<'a> {
edges: Vec<f32>,
x: f32,
total: f32,
/// Only this row (and the room under its top for its merged cells), when set.
only: Option<(usize, f32)>,
}
/// Place the laid-out cells of every row: vertical alignment, turned text, borders and the cell
/// rectangles, clipped where the row's exact height or a fixed table's column is too small for
/// the cell's text.
fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout {
let TableRows { story, table: t, path, depth, cell_text, rows, heights, bottoms, edges, x, total } = input;
let TableRows { story, table: t, path, depth, cell_text, rows, heights, bottoms, edges, x, total, only } = input;
// Grid columns holding a vertical-merge continuation, per row.
let cont: Vec<Vec<usize>> = t
.rows
@@ -858,6 +906,9 @@ fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout {
// Second pass: place cells with their row height, fills and borders.
let mut out = Vec::with_capacity(rows.len());
for (ri, cells) in rows.into_iter().enumerate() {
if only.is_some_and(|(row, _)| row != ri) {
continue;
}
let rh = heights.get(ri).copied().unwrap_or(0.0);
let exact = t.rows.get(ri).is_some_and(|r| r.props.height_rule == HeightRule::Exact && r.props.height.is_some_and(|h| h > 0.0));
let mut items = Vec::new();
@@ -898,10 +949,16 @@ fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout {
_ => None,
})
.fold(c.h, f32::max);
// A merged cell's text is drawn with its restart row, even when the merge runs on
// over later pages: only the room left on the page it starts on can align it.
let align_span = match only {
Some((_, room)) if c.vmerge == VMerge::Restart => span_h.min(room.max(0.0)),
_ => span_h,
};
let mut dy = match c.valign {
VAlign::Top => 0.0,
VAlign::Center => ((span_h - align_h) / 2.0).max(0.0),
VAlign::Bottom => (span_h - align_h).max(0.0),
VAlign::Center => ((align_span - align_h) / 2.0).max(0.0),
VAlign::Bottom => (align_span - align_h).max(0.0),
};
let end = (c.vmerge != VMerge::Continue && c.turned.is_none()).then_some(c.end + dy);
let mut cell_items = c.items;
@@ -909,7 +966,7 @@ fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout {
dy = 0.0;
let m = c.margins;
// The lines run the cell's whole height (laid out again if the row grew).
let len = (span_h - (c.h - tn.len)).clamp(4.0, TURNED_LIMIT);
let len = (align_span - (c.h - tn.len)).clamp(4.0, TURNED_LIMIT);
let mut across = tn.across;
if (len - tn.len).abs() > 0.01
&& let Some(cell) = t.rows.get(ri).and_then(|r| r.cells.get(tn.ci))
+23 -6
View File
@@ -2,7 +2,7 @@ use super::boxes::{BoxInput, clear_of_float_tables, layout_box};
use super::ctx::{Ctx, with_pct_base};
use super::floats::{WrapArea, align_in, body_wraps};
use super::flow::again;
use super::headers::{header_items_cap, header_table_areas, placed_cost};
use super::headers::{begins_section, header_items_cap, header_table_areas, placed_cost};
use super::notes::table_notes;
use super::page::{PageBuilder, PageFrame, page_frame};
use super::placed::Placed;
@@ -14,14 +14,14 @@ pub(crate) fn footer_table_wraps(ctx: &mut Ctx, pb: &PageBuilder) -> Vec<WrapAre
return Vec::new();
}
let Some(page) = pb.pages.last() else { return Vec::new() };
let first = pb.pages.iter().rev().nth(1).is_none_or(|prev| prev.section != page.section);
let hf = Arc::clone(&ctx.hf);
let first = begins_section(&hf.sections, pb.pages.iter().rev().nth(1), page);
let key = (page.section, page.number, first);
if let Some(areas) = ctx.footer_wraps.get(&key) {
return areas.clone();
}
ctx.footer_wraps.insert(key, Vec::new());
let doc = ctx.doc;
let hf = Arc::clone(&ctx.hf);
let Some((_, sect)) = hf.sections.get(page.section) else { return Vec::new() };
if sect.text_direction.is_turned() {
return Vec::new();
@@ -73,6 +73,8 @@ pub(crate) fn footer_table_wraps(ctx: &mut Ctx, pb: &PageBuilder) -> Vec<WrapAre
/// The room a table in the text needs to start on a page: its repeated header rows and the least
/// room its first row can start in (whole, or the part of it that splits off). A paragraph kept
/// with the table goes over with it when that much is not left, as in Word.
/// Before Word 2013 layout (compatibility mode 15) the header rows may stay alone at the foot of a
/// page, so the paragraph keeps with them only.
pub(crate) fn table_start_need(ctx: &mut Ctx, t: &wordcraft_doc::Table, block: usize, width: f32) -> f32 {
// A look ahead: list and equation numbers in the cells don't count yet.
let (counters, eq_count) = (ctx.counters.clone(), ctx.eq_count);
@@ -80,6 +82,10 @@ pub(crate) fn table_start_need(ctx: &mut Ctx, t: &wordcraft_doc::Table, block: u
(ctx.counters, ctx.eq_count) = (counters, eq_count);
let headers = t.rows.iter().take_while(|r| r.props.header).count();
let head: f32 = tl.rows.iter().take(headers).map(|r| r.height).sum();
if headers > 0 && ctx.doc.settings.compat_mode < wordcraft_doc::COMPAT_MODE_CURRENT {
// With the border below the last of them, as `place_table` places them.
return head + tl.rows.get(headers - 1).map_or(0.0, |r| r.edge);
}
let (Some(row), Some(laid)) = (t.rows.get(headers), tl.rows.get(headers)) else { return head };
// ponytail: bisection assumes starting a row gets no harder with more room.
let (mut lo, mut hi) = (0.0f32, laid.height + laid.edge);
@@ -259,9 +265,11 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc
t.rows.get(ri).is_some_and(|r| r.props.height_rule == HeightRule::AtLeast && r.props.height.is_some_and(|h| h > room + 0.01))
};
// Like Word, repeated header rows don't stay alone at the bottom of a page: when the first row
// after them can't start under them there, the table starts on the next page.
// after them can't start under them there, the table starts on the next page. Before Word
// 2013 layout (compatibility mode 15) they do (measured in modes 12 and 14).
let first = header_rows.len();
if !header_rows.is_empty()
&& ctx.doc.settings.compat_mode >= wordcraft_doc::COMPAT_MODE_CURRENT
&& !pb.at_top()
&& let Some(row) = tl.rows.get(first)
{
@@ -288,13 +296,22 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc
.get(ri)
.is_some_and(|r| r.props.cant_split && !(r.props.height_rule == HeightRule::Exact && r.props.height.is_some_and(|h| h > 0.0)));
let mut rest: Option<table::RowLayout> = None;
// The row laid out again for where it lands, when a merge starting in it runs past the
// end of that page (its text is drawn with this row, so it can't be aligned below it).
let mut aligned: Option<table::RowLayout> = None;
let merge_rows = table::merge_rows_after(t, ri);
let merge_h: f32 = tl.rows.iter().skip(ri).take(merge_rows + 1).map(|r| r.height).sum();
// On a new page holding only the repeated header rows.
let mut fresh = false;
// Nothing but this table's header rows above it on a page it started at the top of.
let under_top_headers = ri == first && table_at_top;
// Each pass places the part of the row that fits, then breaks the page.
for _ in 0..1000 {
let cur = rest.as_ref().unwrap_or(row);
if rest.is_none() && merge_rows > 0 {
let room = (pb.bottom - pb.y).max(0.0);
aligned = (merge_h > room + 0.01).then(|| table::layout_table_row_in(ctx, t, &[block as u32], width, ri, room)).flatten();
}
let cur = rest.as_ref().or(aligned.as_ref()).unwrap_or(row);
// A fitting kept row follows the next row when that row cannot start below it.
// Move only the prefix's start; an oversized follower cannot separate its kept rows.
let defer_kept = pb.y + cur.height <= pb.bottom + 0.01
@@ -351,7 +368,7 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc
}
fresh = true;
}
let last = rest.as_ref().unwrap_or(row);
let last = rest.as_ref().or(aligned.as_ref()).unwrap_or(row);
place(pb, last);
table_notes(ctx, pb, &last.items);
}
File diff suppressed because it is too large Load Diff
+154
View File
@@ -0,0 +1,154 @@
//! A combining mark the face of its character can't draw (#7865): the character and its marks are
//! drawn together in a face that has them all (CSS Fonts 4 §5.3, cluster matching), and with no
//! such face the mark on its own from a face that has it, except in right-to-left and
//! complex-script text, where it stays with its letter. Marks the face draws and pairs it composes
//! stay with their character. Fixed test fonts: Source Serif 4 lacks U+0336 and U+0338; Source
//! Sans 3 has U+0338; only JetBrains Mono has U+0336.
use std::sync::Arc;
use wordcraft_doc::{CharProps, Document, Paragraph, para_block};
use wordcraft_fonts::{FaceRef, FontDb};
use super::lay;
use super::linear::assert_linear_steps;
use crate::display::DisplayOptions;
use crate::{ParaLayout, Placed};
const SERIF: &str = "Source Serif 4";
fn serif() -> FaceRef {
crate::test_fonts();
let face = wordcraft_fonts::word::resolve(SERIF, false, false).face;
assert_eq!(face.family, SERIF, "the fixed test fonts include {SERIF}");
face
}
/// A document of one paragraph, `text` set in Source Serif 4; `cs`: with complex-script
/// formatting (`w:cs`), its complex-script font Source Serif 4 too.
fn doc(text: &str, cs: bool) -> Document {
let chr = CharProps { font: Some(SERIF.into()), font_cs: Some(SERIF.into()), cs: Some(cs), size: Some(12.0), ..Default::default() };
let mut d = Document::new();
d.body = vec![para_block(Paragraph::with_text(text, chr))];
d
}
/// [`doc`] laid out: its paragraph and the characters drawn as missing glyphs.
fn laid(text: &str, cs: bool) -> (Arc<ParaLayout>, Vec<char>) {
laid_doc(&doc(text, cs))
}
/// `d`, a document of one paragraph, laid out: the paragraph and the characters drawn as missing
/// glyphs.
fn laid_doc(d: &Document) -> (Arc<ParaLayout>, Vec<char>) {
crate::test_fonts();
let l = lay(d);
let missing = l.missing_glyphs(d, &DisplayOptions::default(), None).chars.iter().map(|(c, _)| *c).collect();
let para = l
.pages
.iter()
.flat_map(|p| &p.items)
.find_map(|it| match it {
Placed::Lines { para, .. } => Some(para.clone()),
_ => None,
})
.expect("the paragraph is laid out");
(para, missing)
}
/// The face that draws the character at byte `at` of the paragraph.
fn face_at(para: &ParaLayout, at: usize) -> FaceRef {
let c = para.clusters.iter().find(|c| c.start <= at && at < c.end).expect("a cluster holds the character");
para.styles[c.style as usize].face
}
#[test]
fn a_mark_its_letters_font_lacks_goes_with_its_letter_to_a_face_that_has_both() {
let serif = serif();
let (letter, mark) = ('∞', '\u{338}');
assert!(serif.covers(letter) && !serif.covers(mark), "{SERIF} has {letter} and lacks U+0338");
let text = format!("x {letter}{mark} y");
let (para, missing) = laid(&text, false);
assert!(missing.is_empty(), "nothing is drawn as a missing glyph, but {missing:?} were");
let at = text.find(letter).expect("the letter is in the text");
let face = face_at(&para, at);
assert_eq!(face.id(), face_at(&para, at + letter.len_utf8()).id(), "the letter and its mark are drawn in one face");
assert!(face.covers(letter) && face.covers(mark), "that face has both");
assert_eq!(face_at(&para, 0).id(), serif.id(), "the text before stays in the run's font");
assert_eq!(face_at(&para, text.len() - 1).id(), serif.id(), "the text after goes back to the run's font");
}
/// In small capitals a mark is set at the size of the lower-case letter it belongs to, so the
/// letter and its marks still go together to a face that has them all, also when the run's font has
/// the first mark and lacks the second.
#[test]
fn in_small_capitals_a_letter_and_its_marks_go_together_to_a_face_that_has_them_all() {
let serif = serif();
let (letter, has, lacks) = ('x', '\u{301}', '\u{336}');
assert!(serif.covers(letter) && serif.covers(has) && !serif.covers(lacks), "{SERIF} has x and U+0301 and lacks U+0336");
let text: String = [letter, has, lacks].iter().collect();
let chr = CharProps { font: Some(SERIF.into()), size: Some(12.0), small_caps: Some(true), ..Default::default() };
let mut d = Document::new();
d.body = vec![para_block(Paragraph::with_text(&text, chr))];
let (para, missing) = laid_doc(&d);
assert!(missing.is_empty(), "nothing is drawn as a missing glyph, but {missing:?} were");
let style_at = |at: usize| para.clusters.iter().find(|c| c.start <= at && at < c.end).expect("a cluster holds the character").style;
let face = face_at(&para, 0);
assert!(face.covers(lacks), "the letter is drawn in a face that has U+0336");
for (at, c) in text.char_indices().skip(1) {
assert_eq!(face_at(&para, at).id(), face.id(), "U+{:04X} is drawn in its letter's face", c as u32);
assert_eq!(style_at(at), style_at(0), "U+{:04X} is set at its letter's size", c as u32);
}
}
#[test]
fn a_mark_the_font_composes_with_its_letter_stays_in_the_run_font() {
let serif = serif();
// The font has no U+0338, but the shaper draws = with it as ≠, which the font has.
assert!(!serif.covers('\u{338}') && serif.covers('≠'), "{SERIF} lacks U+0338 and has ≠");
let text = "x =\u{338} y";
let (para, missing) = laid(text, false);
assert!(missing.is_empty(), "nothing is drawn as a missing glyph, but {missing:?} were");
for (at, c) in text.char_indices() {
assert_eq!(face_at(&para, at).id(), serif.id(), "U+{:04X} stays in the run's font", c as u32);
}
}
#[test]
fn a_mark_no_face_draws_with_its_letter_is_drawn_from_a_face_that_has_it() {
let serif = serif();
let (letter, mark) = ('ǹ', '\u{336}');
let db = FontDb::global();
assert!(serif.covers(letter) && !serif.covers(mark), "{SERIF} has {letter} and lacks U+0336");
assert!(db.fallback_for_run(&[letter, mark], serif.id(), false, false).is_none(), "no face has both");
assert!(db.fallback_for(mark, serif.id()).is_some(), "a face has U+0336");
let text = format!("{letter}{mark}");
let (para, missing) = laid(&text, false);
assert!(missing.is_empty(), "the mark is drawn, but {missing:?} were missing glyphs");
assert_eq!(face_at(&para, 0).id(), serif.id(), "the letter stays in the run's font");
assert!(face_at(&para, letter.len_utf8()).covers(mark), "the mark comes from a face that has it");
}
/// In complex-script text a mark no face draws with its letter stays in the letter's face, so it is
/// never split from its letter (Arabic harakat would lose their place on it).
#[test]
fn in_complex_script_text_a_mark_no_face_draws_with_its_letter_stays_with_it() {
let serif = serif();
let (letter, mark) = ('ǹ', '\u{336}');
assert!(FontDb::global().fallback_for_run(&[letter, mark], serif.id(), false, false).is_none(), "no face has both");
let (para, _) = laid(&format!("{letter}{mark}"), true);
assert_eq!(face_at(&para, 0).id(), serif.id(), "the letter stays in the run's font");
assert_eq!(face_at(&para, letter.len_utf8()).id(), serif.id(), "the mark stays with its letter");
}
/// A letter followed by many marks no face draws with it, in complex-script text, where they stay
/// with it: their cluster is matched once, not again at every mark, which made the layout quadratic
/// in their number.
#[test]
fn a_long_run_of_marks_after_one_letter_lays_out_in_linear_time() {
let serif = serif();
let (letter, mark) = ('ǹ', '\u{336}');
assert!(FontDb::global().fallback_for_run(&[letter, mark], serif.id(), false, false).is_none(), "no face has both");
let text = |n: usize| std::iter::once(letter).chain(std::iter::repeat_n(mark, n)).collect::<String>();
assert_linear_steps("marks after one letter", 200, |n| doc(&text(n), true), |d| drop(std::hint::black_box(lay(d))));
}
+14
View File
@@ -89,6 +89,20 @@ fn a_joined_paragraphs_drawings_are_relative_to_the_shared_line() {
assert!(boxed < alpha + 12.0, "the box's text at {boxed} is below the shared line at {alpha}");
}
#[test]
fn a_margin_anchored_frame_in_a_cell_joins_after_a_hidden_mark() {
let mut d = Document::from_text("Alpha\nOmega");
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().mark.hidden = Some(true);
d.para_mut(StoryRef::Body, &Path::top(1)).unwrap().props.frame =
Some(TextFrame { h_anchor: "page".into(), v_anchor: "margin".into(), ..Default::default() });
in_cell(&mut d);
let l = lay(&d);
let alpha = top_of(&l, &Path(vec![0, 0, 0, 0]));
let omega = top_of(&l, &Path(vec![0, 0, 0, 1]));
assert!((omega - alpha).abs() < 1.0, "framed paragraph should share hidden-mark line: {alpha} vs {omega}");
}
#[test]
fn a_text_frame_after_a_hidden_mark_is_not_joined() {
// A framed paragraph is placed apart, so it shares no line with the one before: its number is
+114
View File
@@ -0,0 +1,114 @@
//! A long word broken by letters: the letter ending the line is measured without its kerning
//! pair with the letter that goes on to the next line (Word, a line's width swept a twip at a
//! time: the letters before a broken kerning pair fit only where they fit on their own).
use super::*;
#[test]
fn a_word_broken_by_letters_ends_without_its_kerning_pair() {
let text = "AVAVAVAVAVAVAVAVAVAV";
let doc = |indent_right: f32| {
let mut d = Document::from_text(text);
Arc::make_mut(&mut d.styles).default_chr.kern = Some(1.0);
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| p.indent_right = Some(indent_right)).unwrap();
d
};
// The word on one line: the first five letters' width with the "AV" pair after the fifth
// and without it.
let l = lay(&doc(0.0));
let para = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para.clone()) } else { None }).unwrap();
let paired: f32 = para.clusters[..5].iter().map(|c| c.adv).sum();
let alone = paired - para.clusters[4].kern;
assert!(alone - paired > 0.1, "the test font kerns \"AV\": {paired} vs {alone}");
// A line between the two takes four letters, as in Word; with the pair it took five.
let got = body_lines(&lay(&doc(468.0 - (paired + alone) / 2.0)), text);
assert_eq!(got.first().map(String::as_str), Some("AVAV"), "{got:?}");
// A line as wide as the five letters alone takes them.
let got = body_lines(&lay(&doc(468.0 - alone - 0.004)), text);
assert_eq!(got.first().map(String::as_str), Some("AVAVA"), "{got:?}");
}
/// Inter under the family name "Kernx" with its `GPOS` hidden and an old-style `kern` table that
/// kerns "AV" by `units` (and nothing else): a shaper splits such a pair between the two letters,
/// half in the first one's advance and half in the second one's advance and offset.
fn legacy_kern_family(units: i16) -> &'static str {
const FAMILY: &str = "Kernx";
let inter = wordcraft_fonts::word::resolve("Inter", false, false).face;
let (a, v) = (inter.glyph_for('A') as u16, inter.glyph_for('V') as u16);
let src = inter.data().to_vec();
let u16_at = |d: &[u8], o: usize| u16::from_be_bytes([d[o], d[o + 1]]) as usize;
let u32_at = |d: &[u8], o: usize| u32::from_be_bytes([d[o], d[o + 1], d[o + 2], d[o + 3]]) as usize;
// The tables, `GPOS` renamed so no shaper reads it, and the new `kern` table.
let mut tables: Vec<([u8; 4], Vec<u8>)> = (0..u16_at(&src, 4))
.map(|i| {
let r = 12 + 16 * i;
let tag: [u8; 4] = src[r..r + 4].try_into().unwrap();
let tag = if &tag == b"GPOS" { *b"XPOS" } else { tag };
(tag, src[u32_at(&src, r + 8)..u32_at(&src, r + 8) + u32_at(&src, r + 12)].to_vec())
})
.collect();
let mut kern = Vec::new();
for x in [0u16, 1, 0, 20, 0x0001, 1, 6, 0, 0, a, v] {
kern.extend(x.to_be_bytes());
}
kern.extend(units.to_be_bytes());
tables.push((*b"kern", kern));
tables.sort_by_key(|t| t.0);
// The font file again: its header, the table records, then the tables (4-byte aligned).
let n = tables.len();
let mut data = src[..12].to_vec();
data[4..6].copy_from_slice(&(n as u16).to_be_bytes());
let mut at = 12 + 16 * n;
let mut body = Vec::new();
for (tag, t) in &tables {
data.extend(tag);
data.extend(0u32.to_be_bytes());
data.extend((at as u32).to_be_bytes());
data.extend((t.len() as u32).to_be_bytes());
body.extend(t);
while body.len() % 4 != 0 {
body.push(0);
}
at = 12 + 16 * n + body.len();
}
data.extend(body);
// The family name, in the name table's UTF-16 and single-byte records alike.
let name = tables.iter().take_while(|t| &t.0 != b"name").map(|t| t.1.len().div_ceil(4) * 4).sum::<usize>() + 12 + 16 * n;
let len = tables.iter().find(|t| &t.0 == b"name").map_or(0, |t| t.1.len());
let wide = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::<Vec<u8>>();
for (from, to) in [(wide("Inter"), wide(FAMILY)), (b"Inter".to_vec(), FAMILY.as_bytes().to_vec())] {
for i in name..name + len - from.len() {
if data[i..i + from.len()] == from[..] {
data[i..i + from.len()].copy_from_slice(&to);
}
}
}
wordcraft_fonts::FontDb::global().add_font(data);
FAMILY
}
/// A letter ending a line whose kerning pair with the letter before it the shaper split between
/// them keeps that pair: only its pair with the letter going on to the next line is dropped
/// (Word for Windows, a font with only an old-style `kern` table: "...3Vy" of a base64 token on
/// one line, where the "y" carrying half the "Vy" pair measured it wider and moved it on).
#[test]
fn a_letter_ending_a_line_keeps_its_pair_with_the_letter_before() {
crate::test_fonts();
let text = "AVAVAVAVAVAVAVAVAVAV";
let family = legacy_kern_family(-300);
let doc = |indent_right: f32| {
let mut d = Document::from_text(text);
let st = Arc::make_mut(&mut d.styles);
st.default_chr.kern = Some(1.0);
st.default_chr.font = Some(family.into());
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| p.indent_right = Some(indent_right)).unwrap();
d
};
let l = lay(&doc(0.0));
let para = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para.clone()) } else { None }).unwrap();
// "AVAVAV" on a line: the "AV" pairs in it kerned, the "VA" after it not kerned at all.
let six: f32 = para.clusters[..6].iter().map(|c| c.adv).sum();
assert!(para.clusters[0].kern < -0.5, "the test font kerns \"AV\": {}", para.clusters[0].kern);
let got = body_lines(&lay(&doc(468.0 - six - 0.004)), text);
assert_eq!(got.first().map(String::as_str), Some("AVAVAV"), "{got:?}");
}
@@ -0,0 +1,52 @@
//! A character Times New Roman's metric twin lacks ("‒", "₽" in Liberation Serif) is drawn from
//! a fallback face, but the line is as tall as the twin's: Times New Roman has those characters,
//! so Word's line is as tall as Times New Roman's, not the taller UI sans.
use crate::{Document, LayoutCache, LayoutOptions, Placed, layout};
/// Inter under the family name "Tinos" (a metric twin of Times New Roman), from the bundled font
/// so the test needs no installed font. Inter lacks "☐"; Source Sans 3 (the fallback) has it and
/// its line is taller (1.326 em against 1.21).
fn fake_tinos() -> &'static str {
const FAMILY: &str = "Tinos";
let inter = wordcraft_fonts::word::resolve("Inter", false, false).face;
assert!(!inter.covers('☐'));
let mut data = inter.data().to_vec();
let u16_at = |d: &[u8], o: usize| u16::from_be_bytes([d[o], d[o + 1]]) as usize;
let u32_at = |d: &[u8], o: usize| u32::from_be_bytes([d[o], d[o + 1], d[o + 2], d[o + 3]]) as usize;
let (name, len) = (0..u16_at(&data, 4))
.map(|i| 12 + 16 * i)
.find(|&r| &data[r..r + 4] == b"name")
.map(|r| (u32_at(&data, r + 8), u32_at(&data, r + 12)))
.unwrap();
let wide = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::<Vec<u8>>();
for (from, to) in [(wide("Inter"), wide(FAMILY)), (b"Inter".to_vec(), FAMILY.as_bytes().to_vec())] {
for i in name..name + len - from.len() {
if data[i..i + from.len()] == from[..] {
data[i..i + from.len()].copy_from_slice(&to);
}
}
}
wordcraft_fonts::FontDb::global().add_font(data);
FAMILY
}
fn line_height(text: &str, font: &str) -> f32 {
let chr = wordcraft_doc::CharProps { font: Some(font.into()), size: Some(14.0), ..Default::default() };
let mut d = Document::new();
d.body = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text(text, chr))];
let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default());
l.pages.iter().flat_map(|p| &p.items).find_map(|it| if let Placed::Lines { para, .. } = it { Some(para.lines[0].height) } else { None }).unwrap()
}
#[test]
fn a_twin_fallback_keeps_the_twins_line_height() {
crate::test_fonts();
let tinos = fake_tinos();
assert_eq!(wordcraft_fonts::word::resolve(tinos, false, false).face.family, tinos, "the test font is installed under its own name");
let plain = line_height("Aa", tinos);
let boxed = line_height("A☐a", tinos);
assert!((boxed - plain).abs() < 0.01, "a line with a fallback character is {boxed} pt, without it {plain} pt");
// Other fonts keep the fallback's taller line.
assert!(line_height("A☐a", "Inter") > line_height("Aa", "Inter") + 1.0);
}
+20 -26
View File
@@ -3,7 +3,7 @@ use super::glyphs::{baseline, cluster_ends, glyph_id, glyph_outlines, left_to_ri
use super::options::{PdfError, PdfOptions};
use super::paint::{append_path, fill, grown, norm, ok, paint_fill, pdf_line_cap, rect_path, shape_effects, shape_path};
use super::picture::{Vector, build_vector, load_image, paint_of, vector_picture};
use super::tags::{Role, TagEntry, figure_alt, graphic_alt, holds_picture, holds_text};
use super::tags::{Role, TagEntry, build_tag_tree, figure_alt, graphic_alt, holds_picture, holds_text};
use super::{
Annotation, Arc, Artifact, ArtifactType, ClKind, ContentTag, DocLayout, DocPath, Document, Draw, FaceRef, Fill, FillRule, Font, HashMap, HashSet,
Identifier, Image, InlineObject, ItemDisplay, KrillaGlyph, LineCap, LineEnd, LineJoin, LineStyle, LinkAnnotation, Node, NonZeroU16, Outline,
@@ -146,13 +146,14 @@ impl Exporter<'_> {
e.children.push(Node::Leaf(id));
}
}
Role::Figure => {
Role::Figure(source) => {
let id: Identifier = s.start_tagged(ContentTag::Other);
f(self, s);
s.end_tagged();
let alt = alt.map(str::to_string).filter(|a| !a.is_empty()).or_else(|| Some("picture".to_string()));
let g = TagGroup::with_children(Tag::Figure(alt), vec![Node::Leaf(id)]);
self.tags.push(TagEntry { kind: Tag::Div.into(), children: vec![Node::Group(g)], at: self.at });
let source = source.filter(|(_, p)| p.0.len() >= 4).map(|(st, p)| (st, p.clone()));
self.tags.push(TagEntry { kind: Tag::Div.into(), children: vec![Node::Group(g)], source, at: self.at });
}
}
}
@@ -160,7 +161,7 @@ impl Exporter<'_> {
/// A rotated inline picture or group: turned as a whole, with each picture in it tagged on its
/// own, so a decorative picture is an artifact while the others stay figures with their alt
/// text. A described shape's figure keeps its description; anything else is an artifact.
fn rotated_pictures(&mut self, s: &mut Surface, d: &Draw) {
fn rotated_pictures(&mut self, s: &mut Surface, d: &Draw, source: Option<(StoryRef, &DocPath)>) {
match d {
Draw::Rotated { cx, cy, spin, items } => {
if !ok(*cx) || !ok(*cy) {
@@ -169,7 +170,7 @@ impl Exporter<'_> {
let [a, b, c, d, e, f] = spin.matrix(*cx, *cy);
s.push_transform(&Transform::from_row(a, b, c, d, e, f));
for it in items {
self.rotated_pictures(s, it);
self.rotated_pictures(s, it, source);
}
s.pop();
}
@@ -178,13 +179,13 @@ impl Exporter<'_> {
let Some(clip) = rect_path(rect) else { return };
s.push_clip_path(&clip, &FillRule::NonZero);
for it in items {
self.rotated_pictures(s, it);
self.rotated_pictures(s, it, source);
}
s.pop();
}
Draw::Image { decorative: true, .. } => self.tagged(s, Role::Artifact(ArtifactType::Other), None, |me, s| me.draw(s, d)),
Draw::Image { alt, .. } => self.tagged(s, Role::Figure, Some(alt), |me, s| me.draw(s, d)),
Draw::Figure { alt, draws, .. } => self.tagged(s, Role::Figure, Some(alt), |me, s| {
Draw::Image { alt, .. } => self.tagged(s, Role::Figure(source), Some(alt), |me, s| me.draw(s, d)),
Draw::Figure { alt, draws, .. } => self.tagged(s, Role::Figure(source), Some(alt), |me, s| {
for d in draws {
me.draw(s, d);
}
@@ -195,22 +196,22 @@ impl Exporter<'_> {
/// One draw of a paragraph's line, tagged for what it is: text as the paragraph's content
/// (structure entry `idx`), pictures and figures on their own, anything else an artifact.
fn line_item(&mut self, s: &mut Surface, d: &Draw, idx: usize) {
fn line_item(&mut self, s: &mut Surface, d: &Draw, idx: usize, story: StoryRef, path: &DocPath) {
match d {
Draw::Glyphs { .. } | Draw::Turned { .. } => self.tagged(s, Role::Para(idx), None, |me, s| me.draw(s, d)),
// A picture marked decorative: an artifact screen readers skip.
Draw::Image { decorative: true, .. } => self.tagged(s, Role::Artifact(ArtifactType::Other), None, |me, s| me.draw(s, d)),
Draw::Image { alt, .. } => self.tagged(s, Role::Figure, Some(alt), |me, s| me.draw(s, d)),
Draw::Image { alt, .. } => self.tagged(s, Role::Figure(Some((story, path))), Some(alt), |me, s| me.draw(s, d)),
// A rotated inline picture, or a rotated group holding pictures: turned as a
// whole, each picture tagged on its own (see `rotated_pictures`).
Draw::Rotated { items, .. } if items.iter().any(holds_picture) => self.rotated_pictures(s, d),
Draw::Rotated { items, .. } if items.iter().any(holds_picture) => self.rotated_pictures(s, d, Some((story, path))),
// A clip (a turned picture cut at its line, an exact-height cell's lines, a canvas's
// members): each draw in it tagged as it would be outside it.
Draw::Clip { rect, items } => {
let Some(clip) = rect_path(rect) else { return };
s.push_clip_path(&clip, &FillRule::NonZero);
for it in items {
self.line_item(s, it, idx);
self.line_item(s, it, idx, story, path);
}
s.pop();
}
@@ -218,7 +219,7 @@ impl Exporter<'_> {
// without text falls to the artifacts below.
Draw::Rotated { items, .. } if items.iter().any(holds_text) => self.tagged(s, Role::Para(idx), None, |me, s| me.draw(s, d)),
// An inline chart, diagram or described shape: its text is part of the figure, not the paragraph.
Draw::Figure { alt, kind, draws: inner } => self.tagged(s, Role::Figure, Some(figure_alt(alt, *kind)), |me, s| {
Draw::Figure { alt, kind, draws: inner } => self.tagged(s, Role::Figure(Some((story, path))), Some(figure_alt(alt, *kind)), |me, s| {
for d in inner {
me.draw(s, d);
}
@@ -267,7 +268,7 @@ impl Exporter<'_> {
Placed::Lines { story, path, para, .. } => {
let idx = self.entry(*story, path, para);
for d in &draws {
self.line_item(s, d, idx);
self.line_item(s, d, idx, *story, path);
}
}
Placed::Image { story, path, off, .. } => {
@@ -276,7 +277,7 @@ impl Exporter<'_> {
let role = if obj.is_some_and(InlineObject::is_decorative) || *off == usize::MAX {
Role::Artifact(ArtifactType::Other)
} else {
Role::Figure
Role::Figure(Some((*story, path)))
};
let alt = match obj {
Some(InlineObject::Image { alt, .. }) => alt.clone(),
@@ -289,7 +290,7 @@ impl Exporter<'_> {
});
}
// A floating shape with a description: a figure (see `shape_figure_alt`).
Placed::Shape { alt, .. } if !alt.is_empty() => self.tagged(s, Role::Figure, Some(alt), |me, s| {
Placed::Shape { alt, .. } if !alt.is_empty() => self.tagged(s, Role::Figure(None), Some(alt), |me, s| {
for d in &draws {
me.draw(s, d);
}
@@ -299,7 +300,7 @@ impl Exporter<'_> {
Some(InlineObject::Graphic { alt, .. }) => graphic_alt(alt, graphic.kind).to_string(),
_ => graphic.kind.noun().to_string(),
};
self.tagged(s, Role::Figure, Some(&alt), |me, s| {
self.tagged(s, Role::Figure(Some((*story, path))), Some(&alt), |me, s| {
for d in &draws {
me.draw(s, d);
}
@@ -337,26 +338,19 @@ impl Exporter<'_> {
}
_ => Tag::P.into(),
};
self.tags.push(TagEntry { kind, children: Vec::new(), at: self.at });
self.tags.push(TagEntry { kind, children: Vec::new(), source: Some((story, path.clone())), at: self.at });
let i = self.tags.len() - 1;
self.tag_index.insert((story, path.clone()), i);
i
}
pub(crate) fn tag_tree(&mut self) -> TagTree {
let mut tree = TagTree::new().with_lang(self.doc.styles.default_chr.lang.clone());
// In reading order: a floating object drawn over the text after it is read after its
// anchor (#5534). The sort is stable, so what is read at one place keeps its order.
let mut tags = std::mem::take(&mut self.tags);
tags.sort_by_key(|e| e.at);
self.tag_index.clear();
for e in tags {
if e.children.is_empty() {
continue;
}
tree.push(TagGroup::with_children(e.kind, e.children));
}
tree
build_tag_tree(self.doc, tags)
}
/// The watermark text stretched over its box (Word's `v:textpath fitshape`): its advance across
+2 -2
View File
@@ -25,7 +25,7 @@
pub mod imposition;
use std::collections::{HashMap, HashSet};
use std::num::NonZeroU16;
use std::num::{NonZeroU16, NonZeroU32};
use std::sync::Arc;
use craft_metafile::{Picture, PlacedItem};
@@ -42,7 +42,7 @@ use krilla::outline::{Outline, OutlineNode};
use krilla::page::PageSettings;
use krilla::paint::{Fill, FillRule, LineCap, LineJoin, Stroke, StrokeDash};
use krilla::surface::Surface;
use krilla::tagging::{Artifact, ArtifactType, ContentTag, Identifier, Node, SpanTag, Tag, TagGroup, TagKind, TagTree};
use krilla::tagging::{Artifact, ArtifactType, ContentTag, Identifier, Node, SpanTag, TableHeaderScope, Tag, TagGroup, TagKind, TagTree};
use krilla::text::{Font, GlyphId, KrillaGlyph};
use wordcraft_doc::graphic::GraphicKind;
use wordcraft_doc::para::{InlineObject, ShapeKind};
+162 -4
View File
@@ -1,4 +1,4 @@
use super::{ArtifactType, Draw, GraphicKind, Node, TagKind};
use super::{ArtifactType, DocPath, Document, Draw, GraphicKind, Node, NonZeroU32, StoryRef, TableHeaderScope, Tag, TagGroup, TagKind, TagTree};
/// A chart's or diagram's alt text: its own, else what it is ("chart", "diagram").
pub(crate) fn graphic_alt(alt: &str, kind: GraphicKind) -> &str {
@@ -36,6 +36,8 @@ pub(crate) fn figure_alt(alt: &str, kind: Option<GraphicKind>) -> &str {
pub(crate) struct TagEntry {
pub(crate) kind: TagKind,
pub(crate) children: Vec<Node>,
/// Paragraph `(story, path)` this entry belongs to, used to nest table cell entries under `Table`/`TR`/`TH` or `TD`.
pub(crate) source: Option<(StoryRef, DocPath)>,
/// Where it is first read: the page (in the order pages are drawn) and the place there of
/// the item it came from (`Page::reading`). The tree is in this order, not the drawing order.
pub(crate) at: (usize, usize),
@@ -43,13 +45,169 @@ pub(crate) struct TagEntry {
/// What the content being drawn is, for tagging.
#[derive(Clone, Copy, PartialEq)]
pub(crate) enum Role {
pub(crate) enum Role<'a> {
/// Paragraph content of the structure entry at this index.
Para(usize),
/// Header/footer, decorations: not part of the structure.
Artifact(ArtifactType),
/// A floating picture (its own Figure).
Figure,
/// A figure (its own `Figure`), optionally anchored to `(story, path)`.
Figure(Option<(StoryRef, &'a DocPath)>),
}
enum StructNode {
Leaf(TagGroup),
Table(TableNode),
}
struct TableNode {
story: StoryRef,
path: DocPath,
rows: Vec<RowNode>,
}
struct RowNode {
index: usize,
cells: Vec<CellNode>,
}
struct CellNode {
index: usize,
children: Vec<StructNode>,
}
/// Build the PDF structure tree, nesting table cell entries under `Table` -> `TR` -> `TH` / `TD`.
pub(crate) fn build_tag_tree(doc: &Document, tags: Vec<TagEntry>) -> TagTree {
let mut roots = Vec::new();
for e in tags {
let group = (!e.children.is_empty()).then(|| TagGroup::with_children(e.kind, e.children));
match (e.source, group) {
// A blank cell still gets its TD/TH, so the row keeps every column's position.
(Some((story, path)), group) if path.0.len() >= 4 => insert_into_nodes(&mut roots, story, &path, group),
(_, Some(group)) => roots.push(StructNode::Leaf(group)),
_ => {}
}
}
let mut tree = TagTree::new().with_lang(doc.styles.default_chr.lang.clone());
for node in roots {
tree.push(into_tag_group(doc, node));
}
tree
}
fn insert_into_nodes(mut nodes: &mut Vec<StructNode>, story: StoryRef, path: &DocPath, group: Option<TagGroup>) {
let mut k = 0usize;
while k.saturating_add(3) < path.0.len() {
let Some(prefix) = path.0.get(..=k) else { break };
let Some(&row_raw) = path.0.get(k + 1) else { break };
let Some(&cell_raw) = path.0.get(k + 2) else { break };
let table_path = DocPath(prefix.to_vec());
let row_idx = row_raw as usize;
let cell_idx = cell_raw as usize;
let table_pos = nodes.iter().rposition(|n| matches!(n, StructNode::Table(t) if t.story == story && t.path == table_path));
let table_pos = match table_pos {
Some(pos) => pos,
None => {
nodes.push(StructNode::Table(TableNode { story, path: table_path, rows: Vec::new() }));
nodes.len() - 1
}
};
let Some(StructNode::Table(table)) = nodes.get_mut(table_pos) else { return };
let row_pos = match table.rows.binary_search_by_key(&row_idx, |r| r.index) {
Ok(pos) => pos,
Err(pos) => {
table.rows.insert(pos, RowNode { index: row_idx, cells: Vec::new() });
pos
}
};
let Some(row) = table.rows.get_mut(row_pos) else { return };
let cell_pos = match row.cells.binary_search_by_key(&cell_idx, |c| c.index) {
Ok(pos) => pos,
Err(pos) => {
row.cells.insert(pos, CellNode { index: cell_idx, children: Vec::new() });
pos
}
};
let Some(cell) = row.cells.get_mut(cell_pos) else { return };
nodes = &mut cell.children;
k = k.saturating_add(3);
}
if let Some(group) = group {
nodes.push(StructNode::Leaf(group));
}
}
fn into_tag_group(doc: &Document, node: StructNode) -> TagGroup {
match node {
StructNode::Leaf(g) => g,
StructNode::Table(t) => {
let doc_table = doc.table(t.story, &t.path);
// Only the unbroken run of header rows at the top of the table are headers, as layout
// counts them (`take_while(|r| r.props.header)`); a row marked as a header further down
// is a body row, so its cells get TD and not TH.
let header_rows = doc_table.map(|dt| dt.rows.iter().take_while(|r| r.props.header).count()).unwrap_or(0);
let row_nodes = t
.rows
.into_iter()
.map(|r| {
let doc_row = doc_table.and_then(|dt| dt.rows.get(r.index));
let is_header = r.index < header_rows;
let cell_nodes = r
.cells
.into_iter()
.map(|c| {
let doc_cell = doc_row.and_then(|dr| dr.cells.get(c.index));
let col_span = doc_cell.and_then(|dc| NonZeroU32::new(dc.span() as u32)).filter(|n| n.get() > 1);
let row_span =
doc_table.and_then(|dt| cell_row_span(dt, r.index, c.index)).and_then(NonZeroU32::new).filter(|n| n.get() > 1);
let tag: TagKind = if is_header {
Tag::TH(TableHeaderScope::Column).with_col_span(col_span).with_row_span(row_span).into()
} else {
Tag::TD.with_col_span(col_span).with_row_span(row_span).into()
};
let children = c.children.into_iter().map(|ch| Node::Group(into_tag_group(doc, ch))).collect();
Node::Group(TagGroup::with_children(tag, children))
})
.collect();
Node::Group(TagGroup::with_children(Tag::TR, cell_nodes))
})
.collect();
TagGroup::with_children(Tag::Table, row_nodes)
}
}
}
fn cell_row_span(table: &wordcraft_doc::Table, row_idx: usize, cell_idx: usize) -> Option<u32> {
let row = table.rows.get(row_idx)?;
let cell = row.cells.get(cell_idx)?;
if cell.props.vmerge != wordcraft_doc::props::VMerge::Restart {
return None;
}
let grid_col = row.first_grid().saturating_add(row.cells.get(..cell_idx)?.iter().map(wordcraft_doc::Cell::span).sum::<usize>());
let mut span = 1u32;
for next_row in table.rows.get(row_idx.saturating_add(1)..)? {
let mut g = next_row.first_grid();
let mut matched = false;
for nc in &next_row.cells {
if g == grid_col && nc.props.vmerge == wordcraft_doc::props::VMerge::Continue {
matched = true;
break;
}
g = g.saturating_add(nc.span());
if g > grid_col {
break;
}
}
if matched {
span = span.saturating_add(1);
} else {
break;
}
}
(span > 1).then_some(span)
}
#[cfg(test)]
+79
View File
@@ -3709,3 +3709,82 @@ fn chart_and_equation_text_keep_their_pdf_bytes() {
["B", "o", "d", "y", " ", "t", "e", "x", "R", "v", "n", "u", "2", "0", "4", "+", "1", equation_x].into_iter().map(String::from).collect();
assert_eq!(shown, expected, "math face: {}", math_face.family);
}
#[test]
fn tables_are_tagged_with_table_tr_th_and_td() {
use wordcraft_doc::{Cell, Row, Table, props::RowProps};
let mut d = Document::from_text("A table.");
let header = Row {
props: RowProps { header: true, ..Default::default() },
cells: vec![Cell::with_text("Head"), Cell::with_text("Col2")],
..Default::default()
};
let body = Row { cells: vec![Cell::with_text("Cell10"), Cell::with_text("Cell11")], ..Default::default() };
let t = Table { grid: vec![120.0, 120.0], rows: vec![header, body], ..Default::default() };
d.body.push(Arc::new(wordcraft_doc::Block::Table(t)));
let raw = String::from_utf8_lossy(&export(&d, &PdfOptions { tagged: true, compress: false, ..Default::default() }).unwrap()).into_owned();
assert!(raw.contains("/S/Table") || raw.contains("/S /Table"), "missing /S /Table in:\n{raw}");
assert!(raw.contains("/S/TR") || raw.contains("/S /TR"), "missing /S /TR in:\n{raw}");
assert!(raw.contains("/S/TH") || raw.contains("/S /TH"), "missing /S /TH in:\n{raw}");
assert!(raw.contains("/S/TD") || raw.contains("/S /TD"), "missing /S /TD in:\n{raw}");
assert!(raw.contains("/Scope/Column") || raw.contains("/Scope /Column"), "missing /Scope /Column on TH");
}
/// Only the run of header rows at the top of the table are headers, as layout counts them: a
/// header-flagged row further down is a body row, so its cells are TD and not TH.
#[test]
fn a_header_row_below_the_top_of_the_table_is_tagged_td() {
use wordcraft_doc::{Cell, Row, Table, props::RowProps};
let mut d = Document::from_text("A table.");
let header = Row {
props: RowProps { header: true, ..Default::default() },
cells: vec![Cell::with_text("Head"), Cell::with_text("Col2")],
..Default::default()
};
let body = Row { cells: vec![Cell::with_text("Cell10"), Cell::with_text("Cell11")], ..Default::default() };
let later_header = Row {
props: RowProps { header: true, ..Default::default() },
cells: vec![Cell::with_text("Mid"), Cell::with_text("Mid2")],
..Default::default()
};
let t = Table { grid: vec![120.0, 120.0], rows: vec![header, body, later_header], ..Default::default() };
d.body.push(Arc::new(wordcraft_doc::Block::Table(t)));
let raw = String::from_utf8_lossy(&export(&d, &PdfOptions { tagged: true, compress: false, ..Default::default() }).unwrap()).into_owned();
let count = |tag: &str| raw.matches(&format!("/S/{tag}")).count() + raw.matches(&format!("/S /{tag}")).count();
assert_eq!(count("TH"), 2, "only the top header row's cells are TH");
assert_eq!(count("TD"), 4, "the body row and the later header row are TD");
}
/// A blank cell still gets its TD or TH, so a filled cell after it keeps its column.
#[test]
fn blank_table_cells_keep_their_td_and_th() {
use wordcraft_doc::{Cell, Row, Table, props::RowProps};
let mut d = Document::from_text("A table.");
let header = Row {
props: RowProps { header: true, ..Default::default() },
cells: vec![Cell::with_text(""), Cell::with_text("Col2")],
..Default::default()
};
let body = Row { cells: vec![Cell::with_text(""), Cell::with_text("Cell11")], ..Default::default() };
let t = Table { grid: vec![120.0, 120.0], rows: vec![header, body], ..Default::default() };
d.body.push(Arc::new(wordcraft_doc::Block::Table(t)));
let raw = String::from_utf8_lossy(&export(&d, &PdfOptions { tagged: true, compress: false, ..Default::default() }).unwrap()).into_owned();
let count = |tag: &str| raw.matches(&format!("/S/{tag}")).count() + raw.matches(&format!("/S /{tag}")).count();
assert_eq!(count("TH"), 2, "both header cells, including the blank one");
assert_eq!(count("TD"), 2, "both body cells, including the blank one");
}
/// A row whose cells are all blank is still a row: its TR and its cells are in the tree.
#[test]
fn an_all_blank_row_keeps_its_cells() {
use wordcraft_doc::{Cell, Row, Table};
let mut d = Document::from_text("A table.");
let blank = Row { cells: vec![Cell::with_text(""), Cell::with_text("")], ..Default::default() };
let filled = Row { cells: vec![Cell::with_text("A"), Cell::with_text("B")], ..Default::default() };
let t = Table { grid: vec![120.0, 120.0], rows: vec![blank, filled], ..Default::default() };
d.body.push(Arc::new(wordcraft_doc::Block::Table(t)));
let raw = String::from_utf8_lossy(&export(&d, &PdfOptions { tagged: true, compress: false, ..Default::default() }).unwrap()).into_owned();
let count = |tag: &str| raw.matches(&format!("/S/{tag}")).count() + raw.matches(&format!("/S /{tag}")).count();
assert_eq!(count("TR"), 2, "both rows, including the all-blank one");
assert_eq!(count("TD"), 4, "every body cell");
}
+2 -2
View File
@@ -16,7 +16,7 @@ craft = { workspace = true, features = [
"color", "color-ui", "control", "draw", "font-manager", "gpu", "menu", "pages", "print", "review", "table", "text",
"text-find", "web-api", "web-host", "window",
] }
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
wordcraft-geom = { workspace = true, features = ["image"] }
wordcraft-doc = { workspace = true }
wordcraft-fonts = { workspace = true }
@@ -76,7 +76,7 @@ craft-ui-test-kit = { workspace = true }
craft = { workspace = true, features = ["ui-testing"] }
[build-dependencies]
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", features = ["subset"] }
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", features = ["subset"] }
serde_json = { workspace = true }
toml = "1"
+3 -3
View File
@@ -1,5 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" height="20">
<rect x="7.5" y="2.5" width="5" height="9.5" rx="1" fill="none" stroke="currentColor" stroke-width="1.25"/>
<path d="M5 9.5 L5 11 L10 15 L15 11 L15 9.5" fill="none" stroke="currentColor" stroke-width="1.25"/>
<path d="M10 15 L10 18" fill="none" stroke="currentColor" stroke-width="1.25"/>
<rect x="7.5" y="2.5" width="5" height="9.5" rx="2.5" fill="none" stroke="currentColor" stroke-width="1.25"/>
<path d="M5 9.5 L5 11 L10 15 L15 11 L15 9.5" fill="none" stroke="currentColor" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M10 15 L10 18" fill="none" stroke="currentColor" stroke-width="1.25" stroke-linecap="round"/>
</svg>

Before

Width:  |  Height:  |  Size: 386 B

After

Width:  |  Height:  |  Size: 458 B

+13 -1
View File
@@ -134,6 +134,12 @@ impl WordApp {
read_aloud_error: None,
autosave_path: None,
saves_in_flight: Vec::new(),
#[cfg(not(target_arch = "wasm32"))]
windowless_save_folders: Default::default(),
#[cfg(not(target_arch = "wasm32"))]
owned_picks: Default::default(),
#[cfg(not(target_arch = "wasm32"))]
native_windows: None,
fallback_chooser: false,
font_generation: wordcraft_fonts::FontDb::global().generation(),
recovery_seen: false,
@@ -280,7 +286,12 @@ impl WordApp {
self.host = std::sync::Arc::new(self.host.with_lang(lang.craft_lang()));
}
let commands: CommandInput = self.command_input();
FrameInput::new(self.root_env()).commands(commands).host(self.host.clone())
// The windowless trial's host routes `PathRow` picks to the window that files them (`file_dialogs::path_rows`).
#[cfg(not(target_arch = "wasm32"))]
let host = self.frame_host();
#[cfg(target_arch = "wasm32")]
let host = self.host.clone();
FrameInput::new(self.root_env()).commands(commands).host(host)
}
/// Start-up with no document to open (#766): show File › Home (Blank document, the templates
@@ -363,6 +374,7 @@ impl WordApp {
// draws, for itself.
self.window_work(ctx);
self.drain_inbox();
crate::keys::tick_paste_wait(self, ctx);
self.paste_arrived(ctx);
// Focus hides the title bar's search box: a search left open there has no box to show it, and would keep
// Escape from leaving Focus (#5398).
+25 -12
View File
@@ -348,7 +348,11 @@ impl WordApp {
let params = if fired.command.params.is_null() { json!({}) } else { fired.command.params.clone() };
let from_key = fired.source == FireSource::Key;
let (id, params) = if id == "edit.pasteFormat" && from_key { self.paste_format_command(ctx, params) } else { (id, params) };
let (id, params) = if id == "edit.pasteFormat" && from_key { self.paste_format_command(ctx, fired.mods, params) } else { (id, params) };
if from_key && id != "edit.pasteFormat" {
self.canvas.ignore_next_paste = false;
self.canvas.paste_wait_since = None;
}
// An Undo or Redo that is not a focused field's own edit (S-L187 sends that one to the
// field) first takes back the gesture under way and every running one (S-L364).
if matches!(id, "edit.undo" | "edit.redo") {
@@ -368,25 +372,34 @@ impl WordApp {
self.canvas.focus_page(ctx);
}
}
self.canvas.paste_event_consumed_same_frame = false;
}
/// Paste Formatting from its key. Mod+Shift+V pastes the formatting Mod+Shift+C (or the Format
/// Painter) picked up; with none picked up it pastes the clipboard as text only, as Word for
/// Windows does (#1537, #4943). Another key bound to Paste Formatting only pastes formatting.
/// The framework fires one command per chord, so nothing waits for a browser paste event.
fn paste_format_command(&self, ctx: &egui::Context, params: Value) -> (&'static str, Value) {
/// On platforms where a browser paste event follows Mod+Shift+V, pasting formatting arms
/// `ignore_next_paste` so that paired paste event is dropped.
fn paste_format_command(&mut self, ctx: &egui::Context, fired_mods: craft::keymap::Mods, params: Value) -> (&'static str, Value) {
let formatting = self.session.painter.is_some() || self.session.copied_format.is_some();
// The command runs a pass after its press, when a quick tap's modifiers are already up: with none held the fire
// is Mod+Shift+V's while that chord is still the command's.
let mods = ctx.input(|i| i.modifiers);
let chord = if mods.any() {
mods.command && mods.shift && !mods.alt
// `fired.mods` carries the chord's modifiers across every OS window, even after a quick
// tap releases the physical keys before `run_fired` runs.
let platform = if craft::ui::runtime::windows::os_of(ctx) == craft::host::target::Os::Mac {
craft::keymap::Platform::Mac
} else {
let default = Binding::parse("Mod+Shift+V").ok().map(|binding| binding.trigger.chord);
craft::ui::runtime::commands::bindings(ctx, &CommandRef::new("edit.pasteFormat"))
.iter()
.any(|binding| Some(binding.trigger.chord) == default)
craft::keymap::Platform::Windows
};
let eff = fired_mods.effective(platform);
let mod_shift = eff.cmd && eff.shift && !eff.alt && !eff.ctrl;
let default = Binding::parse("Mod+Shift+V").ok().map(|binding| binding.trigger.chord);
let chord = mod_shift
&& craft::ui::runtime::commands::bindings(ctx, &CommandRef::new("edit.pasteFormat"))
.iter()
.any(|binding| Some(binding.trigger.chord.effective(platform)) == default);
if formatting && chord && self.canvas.paste_event_follows_chord && !std::mem::take(&mut self.canvas.paste_event_consumed_same_frame) {
self.canvas.ignore_next_paste = true;
self.canvas.paste_wait_since = Some(ctx.input(|i| i.time));
}
if !formatting && chord { ("edit.pasteText", json!({})) } else { ("edit.pasteFormat", params) }
}
}
+81 -20
View File
@@ -10,8 +10,13 @@ use super::{
};
use crate::colors;
/// The document's own save stamps: zoom, last-modified-by, created, modified and revision.
type SaveStamps = (Option<wordcraft_doc::Zoom>, String, String, String, u32);
impl WordApp {
/// `run` for a command a mouse drag on a table sends: the view stays where it is.
/// Runs a command from a pointer gesture without automatically scrolling to the caret.
/// Table and ruler gestures and picture or shape selection use this when the pointer
/// already identifies the target.
pub(crate) fn run_keep_view(&mut self, id: &str, params: Value) -> Result<Value, String> {
self.canvas.keep_view = true;
let r = self.run(id, params);
@@ -34,10 +39,23 @@ impl WordApp {
/// Close, Envelopes, Labels and Finish & Merge on a document with unsaved changes first ask
/// Save / Don't Save / Cancel, and the command runs once that is answered (`ui.saveChanges`).
pub fn run(&mut self, id: &str, params: Value) -> Result<Value, String> {
if id == "file.close"
&& let Some(result) = self.raise_closing()
{
return Ok(result);
if id == "file.close" {
if let Some(result) = self.raise_closing() {
return Ok(result);
}
// Before any Save Changes prompt: this window's own system file dialog may still use it,
// so the close (or the quit it continues) waits for that dialog and then runs as asked.
#[cfg(not(target_arch = "wasm32"))]
if params.get("quit").and_then(Value::as_bool) == Some(true) {
if self.defer_quit_for_native_panels() {
return Ok(json!({"closed": false, "deferred": true}));
}
} else if self.defer_close_for_native_panel(self.windows.shown()) {
return Ok(json!({"closed": false, "deferred": true}));
}
if let Some(error) = self.rejected_draft_blocks_last_surface_close() {
return Err(error);
}
}
// Undo and Redo act on whole steps: a SmartArt typing run still open is folded into its one step first,
// or Undo would take back only the last keystroke of it.
@@ -114,6 +132,42 @@ impl WordApp {
r
}
/// File › Export's `copy` (#6131) writes a copy and never the document's own file. A host
/// page's Save writes the opened file under its own name and its flag can't say "copy", so a
/// copy named like the opened file would overwrite it with unsaved text; and `password`
/// changes the document's own later saves. Both are refused before anything is written.
fn copy_save(&self, id: &str, name: &str, params: &Value) -> Result<bool, String> {
let as_copy = params.get("copy").and_then(Value::as_bool) == Some(true);
if !as_copy {
return Ok(false);
}
let opened = self.session.path.as_ref().and_then(|p| p.file_name()).map(|n| n.to_string_lossy().to_string());
// Compare file names only: a copy given as a path still lands on the opened file's name.
let copy_name = std::path::Path::new(name).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| name.to_string());
if opened.as_deref() == Some(copy_name.as_str()) {
return Err("a copy can't have the same name as the open document: choose another name".into());
}
if matches!(id, "file.save" | "file.saveAs") && params.get("password").is_some_and(|pw| !pw.is_null()) {
return Err("`password` changes the document's own saves, so it can't come with `copy` (use file.encrypt)".into());
}
Ok(true)
}
/// A copy (File › Export, #6131) writes its bytes with fresh save stamps; the document's own
/// are then put back, so its next Save still goes to the original file.
fn restore_copy_stamps(&mut self, as_copy: bool, stamps: &SaveStamps) {
if as_copy {
let (zoom, by, created, modified, revision) = stamps;
(
self.session.doc.settings.zoom,
self.session.doc.core.last_modified_by,
self.session.doc.core.created,
self.session.doc.core.modified,
self.session.doc.core.revision,
) = (*zoom, by.clone(), created.clone(), modified.clone(), *revision);
}
}
/// Run a command for a script or an agent (control channel, MCP bridge): never asks first.
/// UI-level commands (`ui.*`) are handled here, the rest by the engine.
pub fn execute(&mut self, id: &str, params: Value) -> Result<Value, String> {
@@ -153,6 +207,9 @@ impl WordApp {
// Inspect only the suffix bytes: no full-name allocation or UTF-8 slicing.
let has_pdf_suffix = name.as_bytes().last_chunk::<4>().is_some_and(|suffix| suffix.eq_ignore_ascii_case(b".pdf"));
let name = if id == "file.exportPdf" && !has_pdf_suffix { format!("{name}.pdf") } else { name };
// `copy` (File › Export, #6131) writes a copy: the document keeps its unsaved changes,
// its name and its save stamps, as for a PDF.
let as_copy = self.copy_save(id, &name, &params)?;
// A save with a password encrypts this and later saves (`file.save`'s `password`).
if matches!(id, "file.save" | "file.saveAs")
&& let Some(pw) = params.get("password").filter(|v| !v.is_null())
@@ -172,6 +229,7 @@ impl WordApp {
self.session.doc.core.revision,
);
// A save is a save, download or not: advance the revision and modified stamp (#262).
// A copy carries fresh stamps too, but the document's own are put back after.
if matches!(id, "file.save" | "file.saveAs") {
self.session.stamp_save();
}
@@ -192,23 +250,26 @@ impl WordApp {
return Err(error);
}
};
self.restore_copy_stamps(as_copy, &before_stamp);
// An export is a copy, and so is a save in a format that doesn't keep everything (a
// page image, plain text): the document itself still has unsaved changes.
let marked_saved = matches!(id, "file.save" | "file.saveAs") && keeps_everything(&name);
let marked_saved = matches!(id, "file.save" | "file.saveAs") && !as_copy && keeps_everything(&name);
// The ticket's answer may be a failure: what the save stamped is put back then (`settle_saves`).
let undo_stamp: Option<Box<dyn FnOnce(&mut wordcraft_engine::Session)>> = matches!(id, "file.save" | "file.saveAs").then(|| {
let dirty = dirty_before;
Box::new(move |session: &mut wordcraft_engine::Session| {
(
session.doc.settings.zoom,
session.doc.core.last_modified_by,
session.doc.core.created,
session.doc.core.modified,
session.doc.core.revision,
) = before_stamp;
session.dirty = dirty;
}) as Box<dyn FnOnce(&mut wordcraft_engine::Session)>
});
// A copy already restored its stamps above, so settling it leaves the document's own stamps alone.
let undo_stamp: Option<Box<dyn FnOnce(&mut wordcraft_engine::Session)>> =
(matches!(id, "file.save" | "file.saveAs") && !as_copy).then(|| {
let dirty = dirty_before;
Box::new(move |session: &mut wordcraft_engine::Session| {
(
session.doc.settings.zoom,
session.doc.core.last_modified_by,
session.doc.core.created,
session.doc.core.modified,
session.doc.core.revision,
) = before_stamp;
session.dirty = dirty;
}) as Box<dyn FnOnce(&mut wordcraft_engine::Session)>
});
// Save As tells the host page the document is now this file, which it only is when the
// save marks it saved. A Save under a name the page never sent (an untitled document,
// an imported .doc saved as .docx) is a new file too, never an overwrite.
@@ -398,7 +459,7 @@ impl WordApp {
self.canvas.read_first_visible = None;
}
// Drawing leaves the caret where it was: following it would pull the view off the ink.
// A mouse drag on a table (`run_keep_view`) does the same (#1738). A caret in an empty
// Pointer gestures using `run_keep_view` also keep the view in place. A caret in an empty
// story (a footer just made) also spans the whole story: it isn't a selection of it, and
// the view follows it. Saving, exporting, printing, the document's properties and File ›
// Options move neither the caret nor the text, so the view stays where the user is
+18 -2
View File
@@ -229,7 +229,7 @@ impl WordApp {
}
/// End the operation without running anything; its owning window's prompt closes with it.
fn cancel_closing(&mut self) {
pub(crate) fn cancel_closing(&mut self) {
if let Some(closing) = self.closing.take()
&& let Some(id) = closing.prompt
{
@@ -508,6 +508,12 @@ impl WordApp {
self.status(tl!("Wait for the print job to finish submitting before closing."));
return false;
}
// A system file dialog may still use its window's handles until it answers: the loop keeps
// running (and closes what it can), and the quit goes on by itself once they have ended.
#[cfg(not(target_arch = "wasm32"))]
if self.defer_quit_for_native_panels() {
return false;
}
if self.quit_requested {
return true;
}
@@ -541,7 +547,17 @@ impl WordApp {
if let Some(result) = self.raise_closing() {
return Ok(result);
}
if self.closes_only_its_window("file.close", params) && self.close_window_only() {
// This window's own system file dialog may still use it: close (or go on quitting) once
// that has ended.
#[cfg(not(target_arch = "wasm32"))]
if params.get("quit").and_then(Value::as_bool) == Some(true) {
if self.defer_quit_for_native_panels() {
return Ok(json!({"closed": false, "deferred": true}));
}
} else if self.defer_close_for_native_panel(self.windows.shown()) {
return Ok(json!({"closed": false, "deferred": true}));
}
if self.closes_only_its_window("file.close", params) && self.close_window_only()? {
return Ok(json!({"closed": true, "window": true}));
}
if let Some(e) = crate::control::close_refused(self, "file.close", params) {
+33 -10
View File
@@ -16,12 +16,18 @@ use crate::i18n::Lang;
// PLAN(chrome-w12): build.rs embeds the craft faces into `craft_fonts.rs`
pub static CRAFT_FONTS: &[EmbeddedFace] = include!(concat!(env!("OUT_DIR"), "/craft_fonts.rs"));
/// The interface fonts for `lang`: the embedded craft faces, ordered by the language's scripts,
/// and installed system fonts loaded on demand where the platform has them.
/// The interface fonts for `lang`: WordCraft's own Inter and the embedded craft faces, ordered by the language's
/// scripts, and installed system fonts loaded on demand where the platform has them.
pub fn ui_fonts(lang: Lang) -> UiFonts<'static> {
ui_fonts_with_optional_faces(lang, CRAFT_FONTS)
}
/// [`ui_fonts`] with `faces` as the optional craft-fonts faces. Tests pass none, so the faces a CI build embeds
/// can't hide a character the interface's own faces lack.
pub(crate) fn ui_fonts_with_optional_faces(lang: Lang, faces: &[EmbeddedFace]) -> UiFonts<'static> {
let codes: Vec<&str> = Lang::all().map(Lang::code).collect();
let os_locale = wordcraft_engine::system_locale();
let fonts = UiFonts::new(&I18nScripts).craft_faces(CRAFT_FONTS).languages(&codes).ui_language(lang.code());
let fonts = UiFonts::new(&I18nScripts).craft_faces(&own_inter()).craft_faces(faces).languages(&codes).ui_language(lang.code());
let fonts = match os_locale {
Some(locale) => fonts.os_locale(locale),
None => fonts,
@@ -31,6 +37,21 @@ pub fn ui_fonts(lang: Lang) -> UiFonts<'static> {
fonts
}
/// WordCraft's own Inter Regular and SemiBold, from the bytes the document fonts embed. The suite's interface face is
/// the same Inter release cut to Latin, Greek and Cyrillic; tagged with those scripts, these come right after the
/// suite's faces and draw the rest of Inter (○ ✓ ★, the macOS key symbols) in the same design and row height, as the
/// interface did before it moved onto the shared font stack (#7101).
fn own_inter() -> [EmbeddedFace; 2] {
wordcraft_fonts::bundled_inter().map(|(style, bytes)| EmbeddedFace {
family: "Inter",
style,
scripts: &["Latn", "Grek", "Cyrl"],
index: 0,
bytes,
role: None,
})
}
#[cfg(test)]
/// One character of each script the app ships, to find the document fonts that cover it.
const FALLBACK_SAMPLES: [char; 6] = ['ع', 'א', 'ก', 'ა', 'ա', '汉'];
@@ -116,12 +137,12 @@ mod tests {
}
}
/// Symbols written as text in the interface code must exist in the interface fonts; a missing
/// glyph draws as an empty box, as the panes' "✕" close button once did. Letters are the
/// catalogs' business (see the i18n font tests).
/// Symbols written as text in the interface code must exist in the interface fonts, also in a build without the
/// optional craft-fonts faces; a missing glyph draws as an empty box, as the panes' "✕" close button once did.
/// Letters are the catalogs' business (see the i18n font tests).
#[test]
fn interface_symbols_have_glyphs() {
let stack = ui_fonts(Lang::EN).stack();
let stack = ui_fonts_with_optional_faces(Lang::EN, &[]).stack();
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
let mut symbols = BTreeSet::new();
// The i18n module's literals are catalog and pseudo-locale test text, not interface text.
@@ -154,9 +175,11 @@ mod tests {
symbols.retain(|(c, file)| !exempt(*c, file));
let files: Vec<(char, String)> = symbols.into_iter().collect();
let texts: Vec<(String, String)> = files.iter().map(|(c, f)| (c.to_string(), f.clone())).collect();
let samples = texts.iter().map(|(t, f)| Sample::new("en", f, t));
let missing = missing_glyphs(&stack, &FontRef::proportional(), samples, false);
assert!(missing.is_empty(), "symbols without a glyph: {missing:#?}");
for family in [FontRef::proportional(), FontRef::named(craft::ui::fonts::SEMIBOLD)] {
let samples = texts.iter().map(|(t, f)| Sample::new("en", f, t));
let missing = missing_glyphs(&stack, &family, samples, false);
assert!(missing.is_empty(), "symbols without a glyph in {family:?}: {missing:#?}");
}
}
/// An installed Arabic font is asked for only when Arabic text needs one (and no embedded
+5
View File
@@ -167,7 +167,12 @@ impl WordApp {
updates_ui::run(self);
crate::dialogs::host::prepare(self);
let had_dialogs = !self.dialog_host.is_empty();
// A `PathRow` pick filed in the run is bound to the exact dialog opening running it (windowless trial).
#[cfg(not(target_arch = "wasm32"))]
self.begin_row_forms();
self.dialog_host.run(ui);
#[cfg(not(target_arch = "wasm32"))]
self.end_row_forms();
crate::dialogs::host::settle(self, ctx);
crate::dialogs::chrome::apply_modal_nudge(self, ui);
if moved(self) {
+4
View File
@@ -77,6 +77,10 @@ impl WordApp {
if !ClipboardHandle::of(ctx).arrived() {
return;
}
if std::mem::take(&mut self.canvas.ignore_next_paste) {
self.canvas.paste_wait_since = None;
return;
}
// PLAN(canvas-w9): cv.A10 `CanvasState::focused(&self, &egui::Context) -> bool`
if paste_target(self.canvas.focused(ctx), self.ui.backstage, self.modal_open()) {
let _ = self.run("edit.paste", json!({}));
+1 -1
View File
@@ -374,7 +374,7 @@ fn works_without_document(page: &str) -> bool {
/// The built-in templates in gallery order: display label and the `file.new` template id.
const TEMPLATES: [(&str, &str); 5] =
[("Blank document", "blank"), ("Studio handbook (sample)", "sample"), ("Letter", "letter"), ("Résumé", "resume"), ("Report", "report")];
[("Blank document", "blank"), ("Studio handbook", "sample"), ("Letter", "letter"), ("Résumé", "resume"), ("Report", "report")];
/// How many templates Home shows before "More templates" (the rest are on New).
const HOME_TEMPLATES: usize = 4;
+18
View File
@@ -941,3 +941,21 @@ fn clicking_beside_the_back_arrow_does_not_close_the_file_page() {
h.run_steps(4);
assert!(h.state().ui.backstage, "clicking beside the arrow leaves the File page open");
}
/// #7171: in a window too short for the settings column its scroll bar shows, and the buttons stop where the bar's lane
/// starts instead of running under it. The column also ends short of the preview.
#[test]
fn print_settings_buttons_stay_clear_of_the_bar_and_the_preview() {
let mut a = new_app();
a.run("text.insert", json!({"text": "Some text"})).unwrap();
a.run("ui.backstage", json!({"value": true, "page": "print"})).unwrap();
let mut h = harness(a, egui::vec2(700.0, 500.0));
h.run_steps(6);
let column = h.query_all_by_label("Print").map(|n| n.rect()).max_by(|a, b| a.height().total_cmp(&b.height())).expect("the settings column");
let pane = h.query_all_by_label("Sheet 1 of 1").map(|n| n.rect()).max_by(|a, b| a.height().total_cmp(&b.height())).expect("the preview");
assert!(pane.min.x >= column.max.x + 8.0, "a gap between the column and the preview: {column:?} {pane:?}");
for name in ["Save these pages as PDF…", "PDF document (*.pdf)"] {
let button = h.get_by_label(name).rect();
assert!(button.min.x >= column.min.x && button.max.x <= column.max.x - 4.0, "{name} leaves the bar's lane: {button:?} {column:?}");
}
}
+17 -2
View File
@@ -152,8 +152,8 @@ pub struct CanvasState {
/// revision: finding out walks every paragraph, too slow for every frame (#811).
markup_facts: Cell<Option<((u64, u64), [bool; 3])>>,
pub scroll_to_caret: bool,
/// Set while a command runs for a mouse drag on a table: the pointer is already
/// on the target, so the view stays put instead of following the caret (#1738).
/// Set while a pointer-triggered command runs through `WordApp::run_keep_view`
/// to suppress automatic scrolling to the caret.
pub keep_view: bool,
/// A heading navigation click aligns its page against the navigation pane, not just visible.
pub(crate) nav_to_caret: bool,
@@ -262,6 +262,17 @@ pub struct CanvasState {
/// Snapshot of `session.doc` for `(document_id, rev)`, shared via `Arc::clone` across
/// unchanged frames instead of cloning the full `Document` every pass.
doc_snapshot: Option<((u64, u64), Arc<wordcraft_doc::Document>)>,
/// On the web, Mod+Shift+V pasted formatting from its key press: the browser's paste event
/// that follows is the same keystroke and pastes nothing (#5616). Any other key press, pointer
/// press, focus change, or wait past `PASTE_WAIT` clears it.
pub(crate) ignore_next_paste: bool,
/// Input time (seconds) when `ignore_next_paste` was armed.
pub(crate) paste_wait_since: Option<f64>,
/// Whether the platform sends a paste event after Mod+Shift+V's key (true on the web).
pub(crate) paste_event_follows_chord: bool,
/// The paired browser paste arrived and was dropped in the same frame as Mod+Shift+V, before
/// `run_fired` runs in the next frame.
pub(crate) paste_event_consumed_same_frame: bool,
}
type TablePreviewKey = ((String, serde_json::Value, u64, u64, wordcraft_engine::Selection), Arc<DocLayout>);
@@ -474,6 +485,10 @@ impl Default for CanvasState {
preview_scroll: None,
table_preview_layout: None,
doc_snapshot: None,
ignore_next_paste: false,
paste_wait_since: None,
paste_event_follows_chord: cfg!(target_arch = "wasm32"),
paste_event_consumed_same_frame: false,
}
}
}
+5 -6
View File
@@ -151,12 +151,11 @@ fn rows(app: &mut WordApp, ui: &mut Ui) {
let _ = Menu::submenu_row(ui, tl!("Synonyms").to_string(), |ui, _cx| {
for w in syn.iter().filter_map(|x| x.as_str()) {
if MenuItem::new(w.to_string()).show(ui).ran {
let _ = app.run("select.word", json!({}));
let (a, b) = app.session.sel.ordered();
let trimmed = app.session.doc.para_at(&a).and_then(|p| p.text.get(a.off..b.off)).map(|t| t.trim_end().len()).unwrap_or(0);
let end = wordcraft_doc::Pos { off: a.off + trimmed, ..b };
app.session.set_selection(wordcraft_engine::Selection { anchor: a, focus: end });
let _ = app.run("text.insert", json!({"text": w, "raw": true}));
// The word the synonyms were looked up for: quotes around it stay (#6517).
if let Some((a, b)) = wordcraft_engine::cmd::review::thesaurus_word(&app.session) {
app.session.set_selection(wordcraft_engine::Selection { anchor: a, focus: b });
let _ = app.run("text.insert", json!({"text": w, "raw": true}));
}
}
}
});
+1 -1
View File
@@ -10,7 +10,7 @@
//! - `ui.clickText {page, x, y}`: click at a page position (points from the page's top-left)
//! - `ui.dialog.set`, `ui.dialog.confirm`, `ui.dialog.cancel`: the open dialogs' fields and answers
//! - `ui.screenshot {path?, region?}`: PNG of the window (or of `region` `[x0, y0, x1, y1]` in points); `ui.render {path?, page?, scale?}`: page PNG
//! (without `path`, both reply with the PNG as base64 `png`)
//! (without `path`, the reply carries the PNG as base64: `base64` for a screenshot, `png` for a render)
//! - `ui.resize`, `ui.focus`, `ui.closeWindow`, `ui.clipboard`, `ui.replayAt`, `ui.accessTree`
//! - `ui.parity`: feature catalog parity
//!
+37 -9
View File
@@ -248,7 +248,20 @@ fn library_method(app: &mut WordApp, ctx: &egui::Context, req: &ControlRequest)
return Some(Reply::from_result(r));
}
let host = WindowHost::of(ctx);
let viewport = app.active_viewport();
let viewport = match app.control_viewport() {
Ok(viewport) => viewport,
// Caps Lock is runtime-wide. Leave non-input methods to the rest of the dispatcher.
Err(_) if req.method == "ui.capsLock" => egui::ViewportId::ROOT,
Err(e)
if matches!(
req.method.as_str(),
"ui.click" | "ui.focus" | "ui.drop" | "ui.move" | "ui.drag" | "ui.wheel" | "ui.key" | "ui.release" | "ui.type" | "ui.ime"
) =>
{
return Some(err(e));
}
Err(_) => return None,
};
let canvas = &app.canvas;
let map = |page: usize, p: egui::Pos2| page_point_on_screen(canvas, page, p);
match input_method(&req.method, &req.params, &host, viewport, &map)? {
@@ -260,6 +273,10 @@ fn library_method(app: &mut WordApp, ctx: &egui::Context, req: &ControlRequest)
/// `ui.clickText {page, x, y, ..}`: a click at a point of a page, as the library's `ui.click`
/// would deliver it at the screen point the page point is shown at.
fn click_text(app: &mut WordApp, ctx: &egui::Context, p: &Value) -> Reply {
let viewport = match app.control_viewport() {
Ok(viewport) => viewport,
Err(e) => return err(e),
};
let page = p.get("page").and_then(Value::as_u64).map_or(0, |v| usize::try_from(v).unwrap_or(usize::MAX));
let num = |k: &str| p.get(k).and_then(Value::as_f64).map(|v| v as f32);
let (Some(x), Some(y)) = (num("x"), num("y")) else { return err("missing x/y") };
@@ -270,7 +287,7 @@ fn click_text(app: &mut WordApp, ctx: &egui::Context, p: &Value) -> Reply {
click.insert("x".into(), json!(pos.x));
click.insert("y".into(), json!(pos.y));
click.insert("coordinates".into(), json!("screen"));
match input_method("ui.click", &Value::Object(click), &WindowHost::of(ctx), app.active_viewport(), &|_: usize, _: egui::Pos2| None) {
match input_method("ui.click", &Value::Object(click), &WindowHost::of(ctx), viewport, &|_: usize, _: egui::Pos2| None) {
Some(Ok(())) => ok(json!({"screen": [pos.x, pos.y]})),
Some(Err(e)) => err(e),
None => err("ui.click is not available"),
@@ -286,7 +303,11 @@ fn resize(app: &mut WordApp, ctx: &egui::Context, p: &Value) -> Reply {
let Some(size) = crate::window_geometry::requested_size(egui::vec2(w, h), max_side) else {
return err("width and height must be positive numbers no larger than 3.4e38");
};
WindowHost::of(ctx).act(app.active_viewport(), WindowAction::SetInnerSize(size));
let viewport = match app.control_viewport() {
Ok(viewport) => viewport,
Err(e) => return err(e),
};
WindowHost::of(ctx).act(viewport, WindowAction::SetInnerSize(size));
ok(json!({"width": size.x, "height": size.y}))
}
@@ -377,10 +398,10 @@ fn handle_request(app: &mut WordApp, ctx: &egui::Context, req: &ControlRequest)
"ui.parity" => ok(wordcraft_engine::catalog::parity(&app.session.registry)),
"ui.clickText" => click_text(app, ctx, p),
"ui.screenshot" => match craft::automation::screenshot::ScreenshotParams::from_params(p) {
Ok(params) => {
let token = app.next_capture_token();
Reply::screenshot(token, params, app.active_viewport())
}
Ok(params) => match app.control_viewport() {
Ok(viewport) => Reply::screenshot(app.next_capture_token(), params, viewport),
Err(e) => err(e),
},
Err(e) => err(e),
},
"ui.render" => {
@@ -401,12 +422,19 @@ fn handle_request(app: &mut WordApp, ctx: &egui::Context, req: &ControlRequest)
}
"ui.resize" => resize(app, ctx, p),
"ui.focus" => {
WindowHost::of(ctx).act(app.active_viewport(), WindowAction::Focus);
let viewport = match app.control_viewport() {
Ok(viewport) => viewport,
Err(e) => return err(e),
};
WindowHost::of(ctx).act(viewport, WindowAction::Focus);
app.canvas.focus_page(ctx);
ok(json!({}))
}
// Close the active window through the same guard as its OS close button.
"ui.closeWindow" => ok(json!({"requested": WindowHost::of(ctx).act(app.active_viewport(), WindowAction::Close)})),
"ui.closeWindow" => match app.control_viewport() {
Ok(viewport) => ok(json!({"requested": WindowHost::of(ctx).act(viewport, WindowAction::Close)})),
Err(e) => err(e),
},
"ui.clipboard" => clipboard(ctx, p),
"ui.replayAt" => {
let Some(at) = p.get("at").and_then(Value::as_f64) else { return err("missing `at`") };
+25
View File
@@ -365,3 +365,28 @@ fn a_script_opens_the_dialog_a_launcher_command_asks_for() {
assert!(r["result"]["icons"].is_array(), "{r}");
assert!(b.dialog_host.open_dialogs().is_empty(), "a script's Insert Icon without an id opens no picker");
}
/// Every method the Methods table of `docs/control-protocol.md` lists is one the control channel answers: none falls
/// through to the commands as an unknown id. The input methods moved to the framework's names in #7101, and the table
/// kept `ui.press`, `ui.drag` and `ui.text`.
#[test]
fn every_method_the_protocol_doc_lists_is_answered() {
let doc = include_str!("../../../../docs/control-protocol.md");
// `lines`, so a checkout with CRLF line endings (Windows) reads the table too.
let methods: Vec<&str> = doc
.lines()
.skip_while(|line| *line != "## Methods")
.skip_while(|line| !line.starts_with('|'))
.take_while(|line| line.starts_with('|'))
.filter_map(|row| row.strip_prefix("| `")?.split(" |").next())
.flat_map(|cell| cell.split(" / "))
.map(|name| name.trim_matches('`'))
.collect();
assert!(methods.contains(&"engine.execute"), "the Methods table: {methods:?}");
let ctx = installed();
for method in methods {
let r = call(&mut app(), &ctx, method, json!({}));
let unknown = wordcraft_engine::CmdError::Unknown(method.to_string()).to_string();
assert_ne!(r["error"].as_str(), Some(unknown.as_str()), "the doc lists `{method}`, which the control channel doesn't answer");
}
}
+13 -2
View File
@@ -81,6 +81,7 @@ fn settle(app: &mut WordApp, _ctx: &egui::Context, id: DialogId) -> Settle {
let result = match answer {
HyperlinkAnswer::Set { link, text, .. } => {
let places = link_places(app).map(|(_, refs)| refs).unwrap_or_default();
let text = text.filter(|t| *t != tl!("<<Selection in document>>"));
match link_params(&link.target, text.as_deref(), &places) {
Some(params) => app.run("insert.link", params).map(|_| ()).map_err(Label::from),
None => Err(Label::from(tl!("That place is no longer in the document."))),
@@ -94,11 +95,21 @@ fn settle(app: &mut WordApp, _ctx: &egui::Context, id: DialogId) -> Settle {
Settle::Keep
}
/// The text Text to display shows: the selected text, or a placeholder when the selection is not
/// plain text in one line of one paragraph (#8286). `insert.link` keeps such a selection as it is,
/// so the placeholder is never written. lean: still editable, craft-libs has no read-only field.
fn display_text(app: &WordApp) -> String {
if wordcraft_engine::cmd::insert::selection_is_one_line(&app.session) {
app.session.selected_text()
} else {
tl!("<<Selection in document>>").to_string()
}
}
/// Opens Insert › Link on the selected text.
pub(crate) fn open(app: &mut WordApp, _name: &str, _params: &Value, parent: Option<DialogId>) -> Option<DialogId> {
let (groups, _) = link_places(app)?;
let dialog =
HyperlinkDialog::new(CurrentLink::None, Some(app.session.selected_text())).place_groups(groups).parts(HyperlinkParts::NoScreenTip).held_ok();
let dialog = HyperlinkDialog::new(CurrentLink::None, Some(display_text(app))).place_groups(groups).parts(HyperlinkParts::NoScreenTip).held_ok();
Some(open_with(app, parent, Keyed::new("link", dialog), DialogHooks { prepare: None, settle }))
}
+6 -3
View File
@@ -2364,9 +2364,12 @@ fn modal_dialog_with_open_popup_does_not_shake_on_inside_click_but_shakes_on_out
#[test]
fn bare_fields_and_groups_draw_their_captions() {
use egui::accesskit::Role;
for (dialog, captions) in
[("envelopes", &["Delivery address", "Return address", "Envelope size"][..]), ("dropCap", &["Position", "Lines to drop"][..])]
{
for (dialog, captions) in [
("envelopes", &["Delivery address", "Return address", "Envelope size"][..]),
("dropCap", &["Position", "Lines to drop"][..]),
("mergeRecords", &["To:"][..]),
("printRecords", &["To:"][..]),
] {
let mut h = app_harness(app_with("Lanterns"));
h.state_mut().run("ui.dialog", json!({"name": dialog})).unwrap();
h.run_steps(6);
+10 -1
View File
@@ -206,6 +206,12 @@ impl WordApp {
/// turn and asks Save / Don't Save / Cancel about it. A guard already running keeps its open
/// prompt. With none left, the app quits.
pub(crate) fn ask_before_quit(&mut self) -> Value {
// Every way to quit comes here (the updater too): while a system file dialog may still use
// a window, no prompt starts; the quit goes on by itself once the dialogs have ended.
#[cfg(not(target_arch = "wasm32"))]
if self.defer_quit_for_native_panels() {
return json!({"quit": false, "deferred": true});
}
let documents = self.unsaved_documents();
if documents.is_empty() {
self.quit_requested = true;
@@ -214,6 +220,9 @@ impl WordApp {
if self.closing.is_some() {
return json!({"quit": false});
}
if let Some(error) = self.rejected_draft_blocks_quit() {
return json!({"quit": false, "error": error});
}
self.ui.backstage = false;
match self.begin_closing(craft::quit::CloseScope::Quit, documents, "file.close".into(), json!({"quit": true})) {
Ok(_) => json!({"quit": self.quit_requested}),
@@ -448,7 +457,7 @@ mod tests {
crate::test_harness::frames(&mut h, 4);
h.state_mut().run("ui.backstage", json!({"page": "home"})).unwrap();
crate::test_harness::frames(&mut h, 4);
let at = h.get_by_label("Studio handbook (sample)").rect().center();
let at = h.get_by_label("Studio handbook").rect().center();
let button =
|pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE };
h.input_mut().events.extend([egui::Event::PointerMoved(at), button(true)]);
+813 -14
View File
@@ -9,12 +9,38 @@
//! When no system dialog can open (a Linux desktop with neither a file chooser portal nor
//! zenity, #576) the service opens the framework's fallback chooser itself; the app only asks
//! for it by name with [`PickRequest::fallback`].
//!
//! The windowless trial binds each pick to the window that asked and the document it showed
//! ([`WordApp::pump_owned_picks`]). Each pick gets a private file service, so its panel never joins
//! another window's queue. The system dialog launches only with that window's own live native
//! window as its parent (the same panels: AppKit's Save sheet with its Format menu, rfd, or the
//! desktop portal, which on native Wayland is still asked without a parent as before). Its
//! answer settles in that window. The in-app chooser is used when asked for (`ui.fileBrowser`,
//! `WORDCRAFT_FILE_DIALOG=builtin`), when the system dialog answers that it can't show, or when
//! the desktop can't find the window's native window. A pick whose window closes, is rejected
//! or changes is cancelled, and nothing else; a system dialog it already launched is never
//! cancelled (nothing confirms it stopped using its parent): it finishes, its answer is dropped,
//! and its parent window is kept alive until then. Close and quit wait for such dialogs.
#[cfg(not(target_arch = "wasm32"))]
use craft::dialogs::{
service::{FilePanels, FileService},
ui::FileChooser,
};
#[cfg(not(target_arch = "wasm32"))]
use craft::host::{Files, Wake};
use craft::host::{PickId, PickRequest, Picked};
#[cfg(not(target_arch = "wasm32"))]
use craft::ui::dialog::{DialogHost, StackDialog, StandardPrompt};
use serde_json::{Value, json};
use crate::WordApp;
/// The SDK `PathRow`'s own picks in the windowless trial: the frame host's file service binds them to the drawn window
/// and hands them to the owned route below ([`path_rows`]).
#[cfg(not(target_arch = "wasm32"))]
pub(crate) mod path_rows;
/// Most font files one Add Font pick tries; the rest of a bigger selection is skipped.
const MAX_FONTS_PER_PICK: usize = 2000;
@@ -74,6 +100,10 @@ pub(crate) enum AfterPick {
/// document through Manage Sources (#2640).
#[cfg(not(target_arch = "wasm32"))]
Sources,
/// Windowless trial: hand the answer back to the `PathRow` that filed ticket `id` from that dialog opening
/// ([`path_rows`]); the row writes it into its own form field.
#[cfg(not(target_arch = "wasm32"))]
Row(path_rows::RowTarget),
}
/// What to do once Save As has written the document.
@@ -92,6 +122,201 @@ pub(crate) struct PendingDialog {
after: AfterPick,
}
/// How many distinct passes an attached owner may have no live native window before its pick
/// falls back to the in-app chooser, and how often those passes are scheduled.
#[cfg(not(target_arch = "wasm32"))]
const MISSING_PASSES: u32 = 5;
#[cfg(not(target_arch = "wasm32"))]
const MISSING_RETRY: std::time::Duration = std::time::Duration::from_millis(100);
/// Most system file dialogs that may use a window's handles at once: launched and not answered,
/// plus cancelled ones not yet settled. A native pick beyond it waits, holding nothing.
#[cfg(not(target_arch = "wasm32"))]
const MAX_NATIVE_OPERATIONS: usize = 2;
/// The desktop's read-only view of its native windows: the incarnation of the live native window a
/// document viewport has now, `None` while it has none (not attached yet, or gone). A window
/// recreated under the same viewport has a new incarnation. Injected with
/// [`WordApp::set_native_window_lookup`]; without one, picks use the in-app chooser and say why.
#[cfg(not(target_arch = "wasm32"))]
pub trait NativeWindowLookup {
fn incarnation(&self, viewport: egui::ViewportId) -> Option<std::num::NonZeroU64>;
}
/// The desktop's panel pumps for owned picks. The window is borrowed or leased only through these
/// calls; nothing here keeps a window or a raw handle.
#[cfg(not(target_arch = "wasm32"))]
pub trait OwnerPanels {
/// Pump `panels` with exactly that window (`viewport` at `incarnation`) as the parent, and
/// return what keeps that window alive while the launched panel may still use its handles.
/// `None`, without pumping, when that window is no longer live.
fn pump_parented(
&mut self,
viewport: egui::ViewportId,
incarnation: std::num::NonZeroU64,
panels: &mut FilePanels,
host: &mut DialogHost,
) -> Option<ParentLease>;
/// Pump `panels` without a parent. The router calls it only when nothing can show natively:
/// the pick asked for the in-app chooser, or its one native panel already launched (later
/// pumps collect its answer, also for a cancelled pick whose dialog is left to finish).
fn pump_unparented(&mut self, panels: &mut FilePanels, host: &mut DialogHost);
}
/// What the desktop hands back for a native panel it launched on a window: it keeps that window
/// alive (on the desktop, a strong reference to it) because the platform's dialog backend may use
/// the parent's handles after the launching call returns, until the panel answers. The router
/// holds it with the ticket and drops it, on the loop's thread, only once the panel has answered,
/// or, for a cancelled pick, once its dialog (left to finish) has answered. Opaque here.
#[cfg(not(target_arch = "wasm32"))]
pub struct ParentLease {
_keep: Box<dyn std::any::Any + Send>,
}
#[cfg(not(target_arch = "wasm32"))]
impl ParentLease {
/// A lease over `keep`, dropped with the lease.
pub fn new(keep: impl std::any::Any + Send) -> Self {
Self { _keep: Box::new(keep) }
}
}
/// A desktop that only pumps without a parent: an intermediate stage and a test adapter.
#[cfg(not(target_arch = "wasm32"))]
struct NoWindowLookup<F>(F);
#[cfg(not(target_arch = "wasm32"))]
impl<F: FnMut(&mut FilePanels, &mut DialogHost)> OwnerPanels for NoWindowLookup<F> {
fn pump_parented(&mut self, _: egui::ViewportId, _: std::num::NonZeroU64, _: &mut FilePanels, _: &mut DialogHost) -> Option<ParentLease> {
None
}
fn pump_unparented(&mut self, panels: &mut FilePanels, host: &mut DialogHost) {
(self.0)(panels, host);
}
}
/// The windowless trial's picks, each bound to the window that asked, cancelled native panels
/// still settling, and the close or quit that waits for them. App-wide: focusing another window
/// never moves a pick.
#[cfg(not(target_arch = "wasm32"))]
#[derive(Default)]
pub(crate) struct OwnedPicks {
/// At most one per window.
jobs: Vec<OwnedPick>,
/// Forgotten native panels, each pumped until it settles and kept with its parent's lease till
/// then. Bounded with the live ones by [`MAX_NATIVE_OPERATIONS`].
retired: Vec<Retired>,
/// Closes and a quit asked for while a system dialog still used a window, replayed once it ended.
deferred: Vec<ExitIntent>,
/// The app is exiting: no pick is admitted or launched; launched panels only drain.
quiescing: bool,
/// The `PathRow` picks' draw scope, staged picks and answers, shared with the frame host's [`path_rows::RowFiles`].
rows: path_rows::RowRoute,
/// The frame host carrying [`path_rows::RowFiles`], and the generation of the app host it wraps.
env_host: Option<(u64, std::sync::Arc<craft::host::Host>)>,
}
/// A close or quit waiting for system dialogs to end.
#[cfg(not(target_arch = "wasm32"))]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum ExitIntent {
/// Quit (the app menu, the OS, the last window's close): waits for every system dialog.
Quit,
/// Close `window` (its close button, File › Close in it) while it shows `document`: waits for
/// that window's own dialogs, and is dropped if the window shows another document by then.
Close { window: u64, document: u64 },
}
/// A cancelled pick whose system dialog launched. The dialog is never cancelled from here (the
/// SDK cannot confirm a dialog has stopped using its parent): it finishes as the user answers it,
/// and its answer is taken and dropped.
#[cfg(not(target_arch = "wasm32"))]
struct Retired {
/// The window its panel launched on (it may have closed since).
window: u64,
id: PickId,
files: FileService,
panels: FilePanels,
_lease: Option<ParentLease>,
}
/// A pick and its owner: the window that asked and the document it showed then.
#[cfg(not(target_arch = "wasm32"))]
struct OwnedPick {
window: u64,
document: u64,
after: AfterPick,
/// Held until the route is settled; the private service gets it right before its first pump.
request: PickRequest,
/// The in-app chooser answers it: asked for, preferred, no lookup, or no native window found.
in_app: bool,
/// The exact native window the pick belongs to: taken at the gesture from an attached owner,
/// or at its first attachment from an owner that was still mounting. Never taken again.
pin: Option<NativeOwner>,
/// The owner was still mounting at the gesture, so its first attachment may be pinned.
bind_on_attach: bool,
/// Scheduled passes counted without a live native window, and the pass counted last.
missing: u32,
missing_pass: Option<u64>,
ticket: Option<Ticket>,
/// Taken by a pump that had just checked the owner; settled by [`WordApp::poll_file_dialog`]
/// after checking it again.
answer: Option<Picked>,
}
/// One private file service for one pick, so its panel never joins another window's queue and
/// its answer cannot be taken by another pick (each service counts its tickets anew).
#[cfg(not(target_arch = "wasm32"))]
struct Ticket {
id: PickId,
files: FileService,
panels: FilePanels,
/// Whether its panel launches on `pin` (else the in-app chooser answers it).
native: bool,
/// Keeps the pinned window alive until the panel answers.
lease: Option<ParentLease>,
/// Whether the panels have been pumped: an unpumped ticket never reached a panel.
pumped: bool,
/// One chooser instance on the owner host; do not cancel a later one with the same ID.
chooser: Option<(craft::ui::dialog::DialogId, u64)>,
/// Replace IDs can recur because each private file service starts its ticket count anew.
replace: Option<(craft::ui::dialog::DialogId, u64)>,
}
#[cfg(not(target_arch = "wasm32"))]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
struct NativeOwner {
viewport: egui::ViewportId,
/// The owner's mount attempt: a remount is another surface.
attempt: u64,
incarnation: std::num::NonZeroU64,
}
/// Why an owned pick ended without its answer.
#[cfg(not(target_arch = "wasm32"))]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum PickEnd {
/// Its window or document closed, or the window's surface was rejected.
Gone,
/// The native window it was pinned to is no longer the owner's.
Changed,
/// Another prompt took the Replace confirmation's place.
Replaced,
/// The window's close or quit prompt asked for its Save As in place of this unlaunched pick.
Superseded,
/// The dialog opening a `PathRow` pick was filed from closed or was replaced.
FormClosed,
/// The `PathRow` that filed it forgot its ticket.
Forgotten,
}
#[cfg(test)]
thread_local! {
/// Tests: the answers each new private file service's panels give instead of native panels, one
/// list per service in order; the last list serves every later one.
pub(crate) static SCRIPTED_PANELS: std::cell::RefCell<Option<std::collections::VecDeque<Vec<craft::dialogs::Answer>>>> =
const { std::cell::RefCell::new(None) };
}
/// How asking for a file went.
pub(crate) enum Asked {
/// Another file dialog is still open; nothing happened.
@@ -103,8 +328,12 @@ pub(crate) enum Asked {
}
impl WordApp {
/// Whether a file dialog is open (its answer hasn't arrived yet).
/// Whether a file dialog is open for the drawn window (its answer hasn't arrived yet).
pub fn file_dialog_open(&self) -> bool {
#[cfg(not(target_arch = "wasm32"))]
if self.owned_picks.jobs.iter().any(|job| job.window == self.windows.shown()) || self.owned_picks.rows.staged_for(self.windows.shown()) {
return true;
}
self.file_dialog.is_some()
}
@@ -114,15 +343,31 @@ impl WordApp {
self
}
/// The desktop's view of its native windows, for the windowless trial's system file dialogs.
#[cfg(not(target_arch = "wasm32"))]
pub fn set_native_window_lookup(&mut self, lookup: Option<std::sync::Arc<dyn NativeWindowLookup + Send + Sync>>) {
self.native_windows = lookup;
}
/// Ask the file service for a file and do `after` with the answer. Called in the pass of the
/// user's gesture, since the browser's picker needs its activation. Ignored while another
/// dialog is open.
pub(crate) fn ask_file(&mut self, req: PickRequest, after: AfterPick) -> Asked {
#[cfg(not(target_arch = "wasm32"))]
if self.windows.windowless_trial() {
self.supersede_for_guard_save_as(&after);
}
if self.file_dialog_open() {
log::debug!("file dialog already open; ignoring {req:?}");
self.status(tl!("A file dialog is already open."));
return Asked::Busy;
}
// The windowless trial binds every pick to the window that asked and the document it
// shows (the Start screen's placeholder included); see `pump_owned_picks`.
#[cfg(not(target_arch = "wasm32"))]
if self.windows.windowless_trial() {
return self.push_owned_pick(self.windows.shown(), self.shown_document, req, after);
}
let fallback = req.fallback || self.fallback_chooser;
let id = self.host.files().pick(req.fallback(fallback));
self.file_dialog = Some(PendingDialog { id, after });
@@ -130,43 +375,564 @@ impl WordApp {
self.poll_file_dialog().map_or(Asked::Pending, Asked::Done)
}
/// Admit a pick owned by window `window` showing `document`: the one admission point. An owner
/// already attached is pinned to its live native window now, at the gesture.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn push_owned_pick(&mut self, window: u64, document: u64, request: PickRequest, after: AfterPick) -> Asked {
if self.owned_picks.quiescing {
return Asked::Busy;
}
if self.owned_picks.jobs.iter().any(|job| job.window == window) {
self.status(tl!("A file dialog is already open."));
return Asked::Busy;
}
let mut in_app = request.fallback || self.fallback_chooser;
if !in_app && self.native_windows.is_none() {
in_app = true;
self.status(tl!("System file dialogs can't open over separate document windows here, so WordCraft's file chooser is used."));
}
let (mut pin, mut bind_on_attach) = (None, false);
if !in_app {
// Before the first frame no window has attached: the owner is still mounting.
match self.ctx.clone().map(|ctx| self.pick_owner_surface(&ctx, window, document)) {
None | Some(crate::windows::OwnerSurface::Pending) => bind_on_attach = true,
Some(crate::windows::OwnerSurface::Attached { viewport, attempt }) => pin = self.live_native_owner(viewport, attempt),
Some(crate::windows::OwnerSurface::Gone) => {}
}
}
self.owned_picks.jobs.push(OwnedPick {
window,
document,
after,
request,
in_app,
pin,
bind_on_attach,
missing: 0,
missing_pass: None,
ticket: None,
answer: None,
});
if let Some(ctx) = &self.ctx {
ctx.request_repaint_of(egui::ViewportId::ROOT);
}
Asked::Pending
}
/// The Save As that a close or quit prompt's Save asks for, in the prompt's own window for its
/// own document, takes the place of a pick that window has queued but not launched (a quit
/// paused it). Nothing else is superseded: a launched or answered pick, a retired dialog and
/// another window's pick all stay, and the Save As is then Busy as before.
#[cfg(not(target_arch = "wasm32"))]
fn supersede_for_guard_save_as(&mut self, after: &AfterPick) {
let AfterPick::SaveAs { after: AfterSave::Closing, document } = after else { return };
let window = self.windows.shown();
if !self.closing.as_ref().is_some_and(|c| c.window == window && c.document == *document) {
return;
}
let Some(at) = self.owned_picks.jobs.iter().position(|job| {
job.window == window
&& job.document == *document
&& job.ticket.is_none()
&& job.answer.is_none()
&& !matches!(job.after, AfterPick::SaveAs { after: AfterSave::Closing, .. })
}) else {
return;
};
let job = self.owned_picks.jobs.remove(at);
let ctx = self.ctx.clone().unwrap_or_default();
self.cancel_owned_pick(&ctx, job, PickEnd::Superseded);
}
/// The live native window of an attached owner at `viewport`, from the desktop's lookup.
#[cfg(not(target_arch = "wasm32"))]
fn live_native_owner(&self, viewport: Option<egui::ViewportId>, attempt: u64) -> Option<NativeOwner> {
let viewport = viewport?;
let incarnation = self.native_windows.as_ref()?.incarnation(viewport)?;
Some(NativeOwner { viewport, attempt, incarnation })
}
/// Whether `pin` is still exactly the owner's live native window.
#[cfg(not(target_arch = "wasm32"))]
fn pin_is_live(&self, window: u64, pin: NativeOwner) -> bool {
self.attached_attempt(window) == Some(pin.attempt)
&& self.native_windows.as_ref().and_then(|l| l.incarnation(pin.viewport)) == Some(pin.incarnation)
}
/// [`WordApp::pump_owned_picks`] for a desktop whose pump has no parent to give: picks it
/// cannot launch natively wait and then use the in-app chooser. An intermediate stage until the
/// desktop passes its [`OwnerPanels`].
#[cfg(not(target_arch = "wasm32"))]
pub fn pump_windowless_save_as(&mut self, ctx: &egui::Context, pump: impl FnMut(&mut FilePanels, &mut DialogHost)) {
self.pump_owned_picks(ctx, &mut NoWindowLookup(pump));
}
/// Pump every owned pick on its own window's host, from the root pass: launch, collect, cancel,
/// clean up, then replay a close or quit that waited for system dialogs.
#[cfg(not(target_arch = "wasm32"))]
pub fn pump_owned_picks(&mut self, ctx: &egui::Context, desk: &mut impl OwnerPanels) {
// `PathRow` picks whose owner's drawing did not hand them over (it ended early) join here, bound to the owner
// they were filed in, never to the window drawn now.
self.admit_row_picks(None);
// Cancelled after their one panel launched: nothing is queued, so this launches nothing; it
// collects the dialog's late answer and drops it. If that answer would open the in-app
// chooser or a Replace question, they open on this throwaway host and the next pump finds
// them gone, which settles the pick as cancelled. A settled one releases its lease.
self.owned_picks.retired.retain_mut(|retired| {
desk.pump_unparented(&mut retired.panels, &mut DialogHost::new());
let _ = retired.files.take_answer(retired.id);
retired.files.pending_pick().is_some()
});
// A quit whose dialogs have ended goes on before any new launch is scheduled.
self.replay_deferred_exits();
// One pick at a time is out of the list, so admission counts every other one, visited or not.
// Only a pick without a launched panel launches, so the one out holds no lease then.
let mut at = 0;
while at < self.owned_picks.jobs.len() {
let mut job = self.owned_picks.jobs.remove(at);
match self.advance_owned_pick(ctx, &mut job, desk) {
Ok(()) => {
self.owned_picks.jobs.insert(at, job);
at += 1;
}
Err(end) => self.cancel_owned_pick(ctx, job, end),
}
}
if !self.owned_picks.retired.is_empty() {
// A portal Save's close arrives as an answer; look again soon even if nothing wakes.
ctx.request_repaint_after(MISSING_RETRY);
}
self.replay_deferred_exits();
}
#[cfg(not(target_arch = "wasm32"))]
fn advance_owned_pick(&mut self, ctx: &egui::Context, job: &mut OwnedPick, desk: &mut impl OwnerPanels) -> Result<(), PickEnd> {
let surface = self.pick_owner_surface(ctx, job.window, job.document);
if surface == crate::windows::OwnerSurface::Gone {
return Err(PickEnd::Gone);
}
// A pinned pick checks its exact window at every pump, launched or not, also while its
// answer waits: a pick never moves to a recreated window.
if let Some(pin) = job.pin
&& !self.pin_is_live(job.window, pin)
{
return Err(PickEnd::Changed);
}
if let AfterPick::Row(row) = &job.after
&& !self.row_form_live(job.window, job.document, row.form)
{
return Err(PickEnd::FormClosed);
}
if job.answer.is_some() {
return Ok(());
}
if job.ticket.is_none() && !job.in_app {
if job.pin.is_none() && job.bind_on_attach {
match surface {
crate::windows::OwnerSurface::Attached { viewport, attempt } => {
job.pin = self.live_native_owner(viewport, attempt);
job.bind_on_attach = false;
}
_ => {
// Still mounting: its mount pass attaches or rejects it; look again soon.
ctx.request_repaint_after(MISSING_RETRY);
return Ok(());
}
}
}
match job.pin {
Some(pin) => {
if self.owned_picks.quiescing || self.native_operations() >= MAX_NATIVE_OPERATIONS || self.quit_pauses_launch(&job.after) {
// Earlier system dialogs still use their windows: wait, holding nothing.
ctx.request_repaint_after(MISSING_RETRY);
return Ok(());
}
let (files, panels) = self.private_file_service();
let id = files.pick(job.request.clone());
job.ticket = Some(Ticket { id, files, panels, native: true, lease: None, pumped: false, chooser: None, replace: None });
let Some(host) = self.window_dialog_host_mut(job.window) else { return Err(PickEnd::Gone) };
let Some(ticket) = job.ticket.as_mut() else { return Ok(()) };
match desk.pump_parented(pin.viewport, pin.incarnation, &mut ticket.panels, host) {
Some(lease) => ticket.lease = Some(lease),
// The pinned window went between the lookup and the pump. The request
// never reached a panel: drop it unpumped, and the pick with it.
None => {
job.ticket = None;
return Err(PickEnd::Changed);
}
}
ticket.pumped = true;
return self.observe_ticket(ctx, job);
}
None => {
let pass = ctx.cumulative_pass_nr();
if job.missing_pass != Some(pass) {
job.missing_pass = Some(pass);
job.missing += 1;
}
if job.missing < MISSING_PASSES {
ctx.request_repaint_after(MISSING_RETRY);
return Ok(());
}
job.in_app = true;
self.status(tl!("The system file dialog couldn't attach to this window, so WordCraft's file chooser is used."));
}
}
}
if job.ticket.is_none() {
let (files, panels) = self.private_file_service();
let id = files.pick(job.request.clone().fallback(true));
job.ticket = Some(Ticket { id, files, panels, native: false, lease: None, pumped: false, chooser: None, replace: None });
}
let Some(host) = self.window_dialog_host_mut(job.window) else { return Err(PickEnd::Gone) };
let Some(ticket) = job.ticket.as_mut() else { return Ok(()) };
if ticket.replace.is_some_and(|(id, serial)| host.open_serial(id).is_some_and(|open| open != serial)) {
return Err(PickEnd::Replaced);
}
// The in-app chooser, or a launched panel (its pin checked above) whose queue is empty.
desk.pump_unparented(&mut ticket.panels, host);
ticket.pumped = true;
self.observe_ticket(ctx, job)
}
/// After a pump of `job`'s panels on its owner's host: note the chooser and Replace prompt it
/// opened there, and take its answer (releasing the lease: the panel is done with the parent).
#[cfg(not(target_arch = "wasm32"))]
fn observe_ticket(&mut self, ctx: &egui::Context, job: &mut OwnedPick) -> Result<(), PickEnd> {
let Some(host) = self.window_dialog_host_mut(job.window) else { return Err(PickEnd::Gone) };
let Some(ticket) = job.ticket.as_mut() else { return Ok(()) };
if ticket.chooser.is_none()
&& let Some(chooser) = host.get::<FileChooser>()
{
let id = chooser.id();
ticket.chooser = host.open_serial(id).map(|serial| (id, serial));
// The root pump can run after the owner was drawn; show the chooser next frame.
ctx.request_repaint_of(egui::ViewportId::ROOT);
}
let now = ticket.panels.open_questions().next();
let known = ticket.replace.map(|(id, _)| id);
if now != known {
ticket.replace = now.and_then(|id| host.open_serial_by_id::<StandardPrompt>(id).map(|serial| (id, serial)));
ctx.request_repaint_of(egui::ViewportId::ROOT);
}
job.answer = ticket.files.take_answer(ticket.id);
if job.answer.is_some() {
ticket.lease = None;
}
Ok(())
}
/// System file dialogs that may still use a window's handles: launched and unanswered, plus
/// cancelled ones not settled.
#[cfg(not(target_arch = "wasm32"))]
fn native_operations(&self) -> usize {
self.owned_picks.retired.len() + self.owned_picks.jobs.iter().filter(|job| job.ticket.as_ref().is_some_and(|t| t.lease.is_some())).count()
}
/// Whether a quit holds back launching a pick's system dialog: while the quit waits for earlier
/// dialogs, or asks about unsaved documents, no new one opens, except the Save As that a
/// close or quit prompt's Save asks for.
#[cfg(not(target_arch = "wasm32"))]
fn quit_pauses_launch(&self, after: &AfterPick) -> bool {
// Quit decided (a replay in this pump may have just set it): nothing launches any more.
if self.quit_requested {
return true;
}
let quitting = self.owned_picks.deferred.contains(&ExitIntent::Quit)
|| self.closing.as_ref().is_some_and(|c| c.params.get("quit").and_then(Value::as_bool) == Some(true));
quitting && !matches!(after, AfterPick::SaveAs { after: AfterSave::Closing, .. })
}
/// Whether any system file dialog launched by an owned pick may still use its parent window's
/// handles. Their parent leases must outlive that, so quit waits while this is true.
#[cfg(not(target_arch = "wasm32"))]
pub fn native_file_panels_open(&self) -> bool {
self.native_operations() > 0
}
/// Whether window `key`'s own pick has a system dialog that may still use it, or an answer not
/// yet settled in it.
#[cfg(not(target_arch = "wasm32"))]
fn window_native_pick_unsettled(&self, key: u64) -> bool {
self.owned_picks.retired.iter().any(|retired| retired.window == key)
|| self
.owned_picks
.jobs
.iter()
.any(|job| job.window == key && (job.answer.is_some() || job.ticket.as_ref().is_some_and(|t| t.lease.is_some())))
}
/// The app is exiting: call once the desktop has accepted the quit or the root window's close,
/// before its last passes. From then on no pick is admitted or launches a system dialog (so a
/// final draw cannot start one); picks not launched are dropped without being pumped; launched
/// panels are left to finish and keep their leases while [`WordApp::pump_owned_picks`] drains them,
/// a pass every 100 ms, until [`WordApp::native_file_panels_open`] is false. Deferred closes are
/// dropped. Idempotent.
#[cfg(not(target_arch = "wasm32"))]
pub fn quiesce_native_file_panels(&mut self) {
self.owned_picks.quiescing = true;
self.owned_picks.deferred.clear();
let ctx = self.ctx.clone().unwrap_or_default();
for job in std::mem::take(&mut self.owned_picks.jobs) {
if let Some(ticket) = job.ticket {
// An in-app chooser (asked for, or a system dialog's fallback) or Replace question
// would stay on screen with nothing to answer it.
self.close_pick_dialogs(&ctx, job.window, &ticket);
self.retire_ticket(job.window, ticket);
}
}
}
/// Quit while system dialogs still use their windows: remember it (once) and say so; it goes on
/// by itself once they have ended. A pick that never launched does not hold it.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn defer_quit_for_native_panels(&mut self) -> bool {
if !self.native_file_panels_open() {
return false;
}
if !self.owned_picks.deferred.contains(&ExitIntent::Quit) {
self.owned_picks.deferred.push(ExitIntent::Quit);
}
self.status(tl!("WordCraft will quit once the open file dialog is closed."));
true
}
/// Closing window `key` while its own system dialog still uses it: remember it (once) and say
/// so; other windows close as usual.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn defer_close_for_native_panel(&mut self, key: u64) -> bool {
if !self.window_native_pick_unsettled(key) {
return false;
}
let Some(document) = self.window_document(key) else { return false };
let intent = ExitIntent::Close { window: key, document };
if !self.owned_picks.deferred.contains(&intent) {
self.owned_picks.deferred.push(intent);
}
self.status(tl!("This window will close once its file dialog is closed."));
true
}
/// Replay a deferred close or quit whose dialogs have ended, through the usual guards. One that
/// would meet a close prompt already asking waits for it, so no prompt is replaced.
#[cfg(not(target_arch = "wasm32"))]
fn replay_deferred_exits(&mut self) {
if self.owned_picks.deferred.is_empty() || self.closing.is_some() || self.owned_picks.quiescing {
return;
}
let deferred = std::mem::take(&mut self.owned_picks.deferred);
let mut waiting = Vec::new();
for intent in deferred {
match intent {
ExitIntent::Quit
if !self.native_file_panels_open() && !self.owned_picks.jobs.iter().any(|job| job.answer.is_some()) && self.closing.is_none() =>
{
self.quit();
}
// The window shows another document now: the close was for the one it showed.
ExitIntent::Close { window, document } if !self.window_shows_document(window, document) => {}
ExitIntent::Close { window, .. } if !self.window_native_pick_unsettled(window) && self.closing.is_none() => {
self.close_window(window);
}
intent => waiting.push(intent),
}
}
waiting.append(&mut self.owned_picks.deferred);
self.owned_picks.deferred = waiting;
}
/// A private file service seeded with the trial's remembered folders.
#[cfg(not(target_arch = "wasm32"))]
fn private_file_service(&self) -> (FileService, FilePanels) {
let ctx = self.ctx.clone();
let wake = Wake::new(move || {
if let Some(ctx) = &ctx {
ctx.request_repaint_of(egui::ViewportId::ROOT);
}
});
#[cfg(test)]
{
let scripted = SCRIPTED_PANELS.with(|s| {
let mut lists = s.borrow_mut();
let lists = lists.as_mut()?;
if lists.len() > 1 { lists.pop_front() } else { lists.front().cloned() }
});
if let Some(answers) = scripted {
let (files, panels) = FileService::scripted(wake, answers);
return (files.with_last_folders(self.windowless_save_folders.clone()), panels);
}
}
let (files, panels) = FileService::new(wake);
(files.with_last_folders(self.windowless_save_folders.clone()), panels)
}
/// A failed native attachment parks the logical window but makes its picks unusable.
/// Cancel only that window's, before another viewport can settle them or the user retries it.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn cancel_windowless_save_as_for_mount_failure(&mut self, ctx: &egui::Context, window: u64) {
let (gone, kept): (Vec<_>, Vec<_>) = std::mem::take(&mut self.owned_picks.jobs).into_iter().partition(|job| job.window == window);
self.owned_picks.jobs = kept;
for job in gone {
self.cancel_owned_pick(ctx, job, PickEnd::Gone);
}
}
#[cfg(not(target_arch = "wasm32"))]
fn cancel_owned_pick(&mut self, ctx: &egui::Context, job: OwnedPick, end: PickEnd) {
if let Some(ticket) = job.ticket {
self.close_pick_dialogs(ctx, job.window, &ticket);
self.retire_ticket(job.window, ticket);
}
// What the pick left pending in its window, if that window is still there: nothing else's.
self.clear_window_pick_state(job.window, matches!(job.after, AfterPick::Picture), matches!(job.after, AfterPick::Recipients));
if matches!(job.after, AfterPick::SaveAs { after: AfterSave::Closing, .. })
&& self.closing.as_ref().is_some_and(|c| c.window == job.window && c.document == job.document)
{
self.cancel_closing();
}
if end == PickEnd::Superseded {
// Its row still waits for the pick: it learns it did not open.
if let AfterPick::Row(row) = job.after {
self.cancel_row_pick(job.window, job.document, row);
}
return;
}
self.status(match end {
PickEnd::Replaced => tl!("The Replace confirmation changed. Try saving again."),
PickEnd::Changed => tl!("The document window for this file dialog changed. Try again."),
PickEnd::Gone | PickEnd::Superseded => tl!("The document window for this Save As is no longer available."),
PickEnd::FormClosed => tl!("The dialog that asked for this file has closed."),
// Its row let go of it; there is nothing to say.
PickEnd::Forgotten => return,
});
}
/// Remove from window `window`'s host the in-app chooser and Replace question `ticket` opened
/// there, exactly those instances (a later dialog with the same ID stays). Every place a
/// ticket is cancelled or retired calls this first, so no chooser or prompt is left showing for
/// a pick that no longer answers. A closed window already lost its host.
#[cfg(not(target_arch = "wasm32"))]
fn close_pick_dialogs(&mut self, ctx: &egui::Context, window: u64, ticket: &Ticket) {
let Some(host) = self.window_dialog_host_mut(window) else { return };
if let Some((id, serial)) = ticket.chooser
&& host.open_serial(id) == Some(serial)
{
host.cancel_by_id(ctx, id);
let _ = host.take_by_id::<FileChooser>(id);
}
if let Some((id, serial)) = ticket.replace
&& host.open_serial(id) == Some(serial)
&& host.open_dialogs().iter().filter(|dialog| dialog.id == id).count() == 1
{
host.cancel_by_id(ctx, id);
}
if let Some((_, serial)) = ticket.replace {
let _ = host.take_by_open_serial::<StandardPrompt>(serial);
}
}
/// Drop a ticket. A system dialog that launched and has not answered is left to finish and kept,
/// with its lease, for cleanup pumps; the next pass is scheduled. An in-app chooser or an
/// unpumped ticket has no system panel.
#[cfg(not(target_arch = "wasm32"))]
fn retire_ticket(&mut self, window: u64, ticket: Ticket) {
if ticket.pumped && ticket.native && ticket.files.pending_pick().is_some() {
self.owned_picks.retired.push(Retired { window, id: ticket.id, files: ticket.files, panels: ticket.panels, _lease: ticket.lease });
if let Some(ctx) = &self.ctx {
ctx.request_repaint_of(egui::ViewportId::ROOT);
}
}
}
/// Whether `job`'s answer may be settled now: its owner still shows its document and, for a
/// pinned pick, the desktop still has exactly the native window it was pinned to.
#[cfg(not(target_arch = "wasm32"))]
fn owned_answer_current(&self, job: &OwnedPick) -> bool {
self.window_shows_document(job.window, job.document)
&& job.pin.is_none_or(|pin| self.pin_is_live(job.window, pin))
&& match &job.after {
AfterPick::Row(row) => self.row_form_live(job.window, job.document, row.form),
_ => true,
}
}
/// Settle an owned pick's answer in its own window, then draw the window that was drawn.
#[cfg(not(target_arch = "wasm32"))]
fn settle_owned_pick(&mut self, job: OwnedPick, picked: Picked) -> Result<Value, String> {
if let AfterPick::Row(row) = job.after {
// Nothing runs here: the row that filed the ticket takes the answer on its owner's next draw.
if let Some(ticket) = &job.ticket {
self.windowless_save_folders = ticket.files.last_folders();
}
return Ok(self.settle_row_pick(job.window, job.document, row, job.pin, picked));
}
let previous = self.windows.shown();
if !self.enter_window(job.window) || self.session.switch_document(job.document).is_err() {
if matches!(job.after, AfterPick::SaveAs { after: AfterSave::Closing, .. }) {
self.cancel_closing();
}
return Err(tl!("The document window for this Save As is no longer available.").into());
}
if let Some(ticket) = &job.ticket {
self.windowless_save_folders = ticket.files.last_folders();
}
let result = self.finish_file_answer(job.after, picked);
self.enter_window(previous);
result
}
/// Pick up the answer of an open file dialog, if it has arrived (every frame, from `logic`),
/// and finish what it was for. `None` while there is nothing to finish.
pub(crate) fn poll_file_dialog(&mut self) -> Option<Result<Value, String>> {
let id = self.file_dialog.as_ref()?.id;
let picked = self.host.files().take_answer(id)?;
// Checked again here, at its last use; an obsolete pick is left for the pump to remove
// from its original host.
#[cfg(not(target_arch = "wasm32"))]
if let Some(at) = self.owned_picks.jobs.iter().position(|job| job.answer.is_some() && self.owned_answer_current(job)) {
let mut job = self.owned_picks.jobs.remove(at);
if let Some(picked) = job.answer.take() {
return Some(self.settle_owned_pick(job, picked));
}
self.owned_picks.jobs.push(job);
}
let pending = self.file_dialog.as_ref()?;
let picked = self.host.files().take_answer(pending.id)?;
let d = self.file_dialog.take()?;
if matches!(d.after, AfterPick::Recipients) {
Some(self.finish_file_answer(d.after, picked))
}
/// Settle the selected answer in the window it belongs to.
fn finish_file_answer(&mut self, after: AfterPick, picked: Picked) -> Result<Value, String> {
if matches!(after, AfterPick::Recipients) {
self.recipient_list_pending = false;
}
match picked {
Picked::Cancelled => Some(self.finish_pick(d.after, None)),
Picked::Cancelled => self.finish_pick(after, None),
Picked::Unavailable(cause) => {
#[cfg(not(target_arch = "wasm32"))]
self.status(craft::dialogs::ui::UnavailableWords::default().sentence(&cause));
#[cfg(target_arch = "wasm32")]
self.status(format!("No file dialog can open: {cause}"));
Some(self.finish_pick(d.after, None))
self.finish_pick(after, None)
}
Picked::Failed(reason) => {
// A plain Save As has no prompt to carry the reason to and Backstage hides the
// status bar, so the Save As page says it too.
if matches!(d.after, AfterPick::SaveAs { after: AfterSave::Nothing, .. }) {
if matches!(after, AfterPick::SaveAs { after: AfterSave::Nothing, .. }) {
self.fail_save_as(&reason);
} else {
self.status(reason);
}
Some(self.finish_pick(d.after, None))
self.finish_pick(after, None)
}
Picked::Paths(paths) => {
let paths = paths.iter().map(|p| p.to_string_lossy().into_owned()).collect();
Some(self.finish_picks(d.after, paths))
self.finish_picks(after, paths)
}
Picked::Saved { path, .. } => Some(self.finish_picks(d.after, vec![path.to_string_lossy().into_owned()])),
Picked::Contents(files) => Some(self.finish_contents(d.after, files)),
Picked::Saved { path, .. } => self.finish_picks(after, vec![path.to_string_lossy().into_owned()]),
Picked::Contents(files) => self.finish_contents(after, files),
// The page handed the save over as a download: the save finishes under that name, which
// the engine answers with `downloaded`, and the document keeps the file it had.
Picked::Downloaded(name) => Some(self.finish_pick(d.after, Some(name))),
Picked::Downloaded(name) => self.finish_pick(after, Some(name)),
}
}
@@ -174,6 +940,34 @@ impl WordApp {
/// returns the format of the export it was for, if any. `ui.fileBrowser` reuses it.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn give_up_file_dialog(&mut self) -> Option<String> {
let shown = self.windows.shown();
if let Some(at) = self.owned_picks.jobs.iter().position(|job| job.window == shown) {
// An in-app chooser or Replace question already shows (asked for, or the system
// dialog's fallback): do not replace it or an in-progress close with the browser
// recovery command, nor leave it showing for a pick that no longer answers.
let job = &self.owned_picks.jobs[at];
if job.in_app || job.answer.is_some() || job.ticket.as_ref().is_some_and(|t| t.chooser.is_some() || t.replace.is_some()) {
return None;
}
if matches!(job.after, AfterPick::Row(_)) {
// A `PathRow` pick keeps its row as its completion: its system dialog is given up for the in-app
// chooser on the same window, which answers the same row.
let job = &mut self.owned_picks.jobs[at];
job.in_app = true;
let window = job.window;
if let Some(ticket) = job.ticket.take() {
self.retire_ticket(window, ticket);
}
return None;
}
let job = self.owned_picks.jobs.remove(at);
if let Some(ticket) = job.ticket {
self.retire_ticket(job.window, ticket);
}
let export = if let AfterPick::Export { ext } = &job.after { Some(ext.clone()) } else { None };
let _ = self.finish_pick(job.after, None);
return export;
}
let d = self.file_dialog.take()?;
self.host.files().forget(d.id);
let export = if let AfterPick::Export { ext } = &d.after { Some(ext.clone()) } else { None };
@@ -278,6 +1072,9 @@ impl WordApp {
let Some(path) = picked else { return Ok(json!({"cancelled": true})) };
self.add_fonts(vec![(path.clone(), json!({"path": path}))])
}
// Settled by `settle_owned_pick` into the row's own ticket; no command runs for it.
#[cfg(not(target_arch = "wasm32"))]
AfterPick::Row(_) => Ok(json!({"cancelled": picked.is_none()})),
#[cfg(not(target_arch = "wasm32"))]
AfterPick::Sources => {
let Some(path) = picked else { return Ok(json!({"cancelled": true})) };
@@ -321,9 +1118,11 @@ impl WordApp {
}
// Word XML even over a Word 2003 XML file, which a save by path would keep.
let format = if ext == "xml" { wordcraft_engine::cmd::file::FORMAT_FLAT_OPC } else { crate::print_page::EXPORT_WORD_2003 };
self.run("file.saveAs", json!({"path": path, "format": format}))
// An export is a copy: the document keeps its own file and changes (#6131).
self.run("file.saveAs", json!({"path": path, "format": format, "copy": true}))
} else {
self.run("file.saveAs", json!({"path": path}))
// An export is a copy: the document keeps its own file and changes (#6131).
self.run("file.saveAs", json!({"path": path, "copy": true}))
};
match &r {
Ok(_) => {
@@ -0,0 +1,465 @@
//! The windowless trial's route for the SDK `PathRow`'s own picks (Compare and Combine, Templates and Add-ins, the
//! Organizer). A `PathRow` with `.pick(..)` files its Browse request through the `Env` host itself
//! (`host.files().pick`) and keeps the ticket in its row's memory, so `WordApp::ask_file` never sees it. The `Env` host
//! comes from the frame input, one for every viewport, so in the trial the frame's host carries [`RowFiles`], an
//! app-owned wrapper over the app's own host:
//!
//! - `WordApp` sets a draw scope around each window's drawing: the logical window, the document it shows and its exact
//! native window (viewport, mount attempt, incarnation) when it has one. Around the window's dialog run it adds the
//! openings of its dialogs (id and open serial), read before the run: a dialog opened during a run shows only from
//! the next pass, so every dialog that runs is in it.
//! - A pick is bound when it is filed: to that scope and to the dialog running it (`overlay::running_dialog`) at the
//! serial of that opening. It is staged under a ticket of the wrapper's own numbering.
//! - After the owner's drawing, `WordApp::admit_row_picks` hands it to the owned route (`push_owned_pick`, the one
//! admission point), which pins the native window and launches the system dialog only there, under its lease.
//! - The settled answer is posted here under the row's exact ticket. The row takes it only from a drawing of the same
//! window, document, native window and dialog opening; otherwise it is dropped. A pick whose window, document,
//! native window or dialog goes before then is cancelled by the route and posts nothing.
//!
//! A pick filed outside any window's drawing, or from a dialog whose opening cannot be told apart, answers Cancelled at
//! once: nothing launches without an exact owner. Every other file-service call goes straight to the app's own host,
//! and outside the trial the frame gets that host unchanged.
use std::num::NonZeroU64;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, MutexGuard};
use craft::host::{FileError, Files, Host, PendingPick, PickId, PickRequest, Picked, WriteIntent};
use craft::ui::dialog::DialogId;
use super::{AfterPick, Asked, NativeOwner, PickEnd};
use crate::WordApp;
/// The wrapper's tickets have this bit set; the app's own service counts up from 1 and never reaches it, so every
/// ticket names one side.
const ROW_TICKETS: u64 = 1 << 63;
/// Answers kept for picks filed outside any window's drawing (each answered Cancelled at once) until their row takes
/// them; the oldest goes first.
const MAX_OWNERLESS: usize = 4;
/// Answers kept for one window's rows until they take them: the newest for each dialog opening, and at most this many
/// in all; the oldest goes first.
const MAX_PER_WINDOW: usize = 2;
/// The logical window being drawn and the document it shows: who a row pick belongs to.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) struct RowOwner {
pub(crate) window: u64,
pub(crate) document: u64,
}
/// The exact native window a window draws in: viewport, mount attempt and incarnation. `None` while it has none the
/// desktop can name (still mounting, or no window lookup).
pub(crate) type RowSurface = Option<(egui::ViewportId, u64, NonZeroU64)>;
/// The dialog opening a row pick was filed from on its owner's host: its id and that opening's serial. `None` for a
/// row outside any hosted dialog.
pub(crate) type RowForm = Option<(DialogId, u64)>;
/// Where an owned row pick's answer goes: the row's ticket, the dialog opening it was filed from, and the native
/// window its owner drew in then.
#[derive(Clone, Copy)]
pub(crate) struct RowTarget {
pub(crate) id: PickId,
pub(crate) form: RowForm,
pub(crate) surface: RowSurface,
}
/// A window's drawing, while it runs.
#[derive(Clone)]
struct Scope {
owner: RowOwner,
surface: RowSurface,
ctx: egui::Context,
/// The window's dialog openings, read right before its dialog run; empty outside the run.
forms: Vec<(DialogId, u64)>,
}
impl Scope {
/// The opening of the dialog running now, as the scope knows it. `Ok(None)` outside any hosted dialog; `Err`
/// when the dialog running is not one opening of this window's host (two openings of one id, or another host).
fn running_form(&self) -> Result<RowForm, ()> {
let Some(id) = craft::ui::runtime::overlay::running_dialog(&self.ctx) else { return Ok(None) };
let mut openings = self.forms.iter().filter(|(open, _)| *open == id);
match (openings.next(), openings.next()) {
(Some(&opening), None) => Ok(Some(opening)),
_ => Err(()),
}
}
}
/// A row pick filed in a window's drawing, not yet handed to the owned route.
pub(crate) struct Staged {
pub(crate) id: PickId,
pub(crate) owner: RowOwner,
pub(crate) form: RowForm,
pub(crate) surface: RowSurface,
pub(crate) request: PickRequest,
}
/// An answer waiting for its row.
struct Answer {
id: PickId,
owner: Option<RowOwner>,
form: RowForm,
surface: RowSurface,
picked: Picked,
}
#[derive(Default)]
struct RowState {
/// The window being drawn, while it is.
scope: Option<Scope>,
next: u64,
/// At most one per window: a second Browse in the same drawing answers Cancelled.
staged: Vec<Staged>,
/// At most [`MAX_PER_WINDOW`] per owner window, and [`MAX_OWNERLESS`] without one.
answers: Vec<Answer>,
/// Row tickets forgotten after they were handed to the owned route; that route cancels them.
forgotten: Vec<PickId>,
}
impl RowState {
/// Post `picked` for ticket `id`. An older answer for the same window and dialog opening is dropped (its row has
/// either taken it already or is no longer shown), and the bounds above hold.
fn post(&mut self, id: PickId, owner: Option<RowOwner>, form: RowForm, surface: RowSurface, picked: Picked) {
if owner.is_some() {
self.answers.retain(|a| a.owner != owner || a.form != form);
}
let window = owner.map(|o| o.window);
let same = |a: &Answer| a.owner.map(|o| o.window) == window;
let bound = if owner.is_some() { MAX_PER_WINDOW } else { MAX_OWNERLESS };
while self.answers.iter().filter(|a| same(a)).count() >= bound
&& let Some(at) = self.answers.iter().position(same)
{
self.answers.remove(at);
}
self.answers.push(Answer { id, owner, form, surface, picked });
}
}
/// The state the router and the wrapper share. Kept in `OwnedPicks`, app-wide, so a window swap never moves it.
#[derive(Clone, Default)]
pub(crate) struct RowRoute(Arc<Mutex<RowState>>);
/// What [`WordApp::enter_row_scope`] replaced, for [`WordApp::leave_row_scope`] to put back.
pub(crate) struct Entered {
window: u64,
previous: Option<Scope>,
}
impl RowRoute {
fn lock(&self) -> MutexGuard<'_, RowState> {
self.0.lock().unwrap_or_else(|e| e.into_inner())
}
/// Whether window `window` has a row pick staged and not yet handed to the owned route.
pub(crate) fn staged_for(&self, window: u64) -> bool {
self.lock().staged.iter().any(|s| s.owner.window == window)
}
/// The staged picks, `window`'s only when given, in filing order.
fn take_staged(&self, window: Option<u64>) -> Vec<Staged> {
let mut state = self.lock();
let (taken, kept): (Vec<Staged>, Vec<Staged>) =
std::mem::take(&mut state.staged).into_iter().partition(|s| window.is_none_or(|w| s.owner.window == w));
state.staged = kept;
taken
}
/// Post the answer of row ticket `id`.
fn answer(&self, id: PickId, owner: RowOwner, form: RowForm, surface: RowSurface, picked: Picked) {
self.lock().post(id, Some(owner), form, surface, picked);
}
/// Drop the answers whose owner window, document or dialog opening `live` says is gone, Cancelled ones included.
fn prune(&self, mut live: impl FnMut(RowOwner, RowForm) -> bool) {
self.lock().answers.retain(|a| a.owner.is_none_or(|owner| live(owner, a.form)));
}
}
/// Whether `id` is one of the wrapper's tickets.
pub(crate) fn is_row_ticket(id: PickId) -> bool {
id.0 & ROW_TICKETS != 0
}
/// The frame host's file service in the windowless trial: row picks go to the owned route, everything else to the app's
/// own host's service.
pub(crate) struct RowFiles {
inner: Arc<Host>,
route: RowRoute,
}
impl RowFiles {
pub(crate) fn new(inner: Arc<Host>, route: RowRoute) -> Self {
RowFiles { inner, route }
}
}
impl Files for RowFiles {
fn pick(&self, request: PickRequest) -> PickId {
let mut state = self.route.lock();
state.next += 1;
let id = PickId(ROW_TICKETS | state.next);
let Some(scope) = state.scope.clone() else {
log::warn!("a file pick was filed outside any window's drawing; nothing opens for it ({request:?})");
state.post(id, None, None, None, Picked::Cancelled);
return id;
};
let (owner, surface) = (scope.owner, scope.surface);
match scope.running_form() {
Err(()) => {
// Not one opening of this window's dialogs: no exact owner to bind to, and no answer can reach it.
log::warn!("a file pick was filed from a dialog WordCraft cannot tell apart; nothing opens for it ({request:?})");
}
// One pick per window: the route admits the first; this one answers Cancelled to its own row.
Ok(form) if state.staged.iter().any(|s| s.owner.window == owner.window) => state.post(id, Some(owner), form, surface, Picked::Cancelled),
Ok(form) => state.staged.push(Staged { id, owner, form, surface, request }),
}
id
}
fn take_answer(&self, id: PickId) -> Option<Picked> {
if !is_row_ticket(id) {
return self.inner.files().take_answer(id);
}
let mut state = self.route.lock();
let at = state.answers.iter().position(|a| a.id == id)?;
let answer = state.answers.remove(at);
let Some(owner) = answer.owner else { return Some(answer.picked) };
// Read only from a drawing of the window, document, native window and dialog opening it was filed from; a row
// reading it anywhere else (its window detached or remounted since, say) gets nothing, and the answer is gone.
let current = state
.scope
.as_ref()
.is_some_and(|scope| scope.owner == owner && scope.surface == answer.surface && scope.running_form() == Ok(answer.form));
if current {
Some(answer.picked)
} else {
log::debug!("dropped a file pick's answer read outside the drawing it was filed from");
None
}
}
fn forget(&self, id: PickId) {
if !is_row_ticket(id) {
self.inner.files().forget(id);
return;
}
let mut state = self.route.lock();
let staged = state.staged.len();
state.staged.retain(|s| s.id != id);
let answered = state.answers.len();
state.answers.retain(|a| a.id != id);
if state.staged.len() == staged && state.answers.len() == answered {
// Neither staged nor answered: it may be with the owned route, which cancels it.
state.forgotten.push(id);
}
}
fn pending_pick(&self) -> Option<PendingPick> {
self.inner.files().pending_pick()
}
fn read_metadata(&self, path: &Path) -> Result<(bool, u64), FileError> {
self.inner.files().read_metadata(path)
}
fn read(&self, path: &Path) -> Result<Vec<u8>, FileError> {
self.inner.files().read(path)
}
fn write(&self, path: &Path, bytes: &[u8], intent: WriteIntent) -> Result<bool, FileError> {
self.inner.files().write(path, bytes, intent)
}
fn exists(&self, path: &Path) -> bool {
self.inner.files().exists(path)
}
fn last_folder(&self, purpose: &str) -> Option<PathBuf> {
self.inner.files().last_folder(purpose)
}
fn save(&self, request: PickRequest, bytes: Vec<u8>) -> PickId {
self.inner.files().save(request, bytes)
}
fn can_pick(&self) -> bool {
self.inner.files().can_pick()
}
fn browser_saves(&self) -> bool {
self.inner.files().browser_saves()
}
fn saves_to_page(&self) -> bool {
self.inner.files().saves_to_page()
}
fn answer_next(&self, picked: Picked) -> Result<(), FileError> {
self.inner.files().answer_next(picked)
}
}
impl WordApp {
/// The host the frame hands every viewport's `Env`. In the windowless trial it carries [`RowFiles`] over the app's
/// own host, built again only when that host is (a language change); otherwise the app's own host, unchanged.
pub(crate) fn frame_host(&mut self) -> Arc<Host> {
if !self.windows.windowless_trial() {
return self.host.clone();
}
let generation = self.host.generation();
if let Some((built, host)) = &self.owned_picks.env_host
&& *built == generation
{
return host.clone();
}
let files = RowFiles::new(self.host.clone(), self.owned_picks.rows.clone());
let host = Arc::new(self.host.with_files(Arc::new(files)));
self.owned_picks.env_host = Some((generation, host.clone()));
host
}
/// The exact native window window `window` showing `document` draws in now, from the desktop's lookup.
fn row_surface(&self, ctx: &egui::Context, window: u64, document: u64) -> RowSurface {
match self.pick_owner_surface(ctx, window, document) {
crate::windows::OwnerSurface::Attached { viewport, attempt } => {
self.live_native_owner(viewport, attempt).map(|native| (native.viewport, native.attempt, native.incarnation))
}
_ => None,
}
}
/// Start drawing the shown window: `PathRow` picks filed until [`leave_row_scope`](Self::leave_row_scope) belong
/// to it, the document it shows and the native window it draws in now. `None` outside the trial, where nothing
/// changes.
pub(crate) fn enter_row_scope(&mut self, ctx: &egui::Context) -> Option<Entered> {
if !self.windows.windowless_trial() {
return None;
}
let owner = RowOwner { window: self.windows.shown(), document: self.shown_document };
let surface = self.row_surface(ctx, owner.window, owner.document);
let scope = Scope { owner, surface, ctx: ctx.clone(), forms: Vec::new() };
let previous = self.owned_picks.rows.lock().scope.replace(scope);
Some(Entered { window: owner.window, previous })
}
/// End the drawing [`enter_row_scope`](Self::enter_row_scope) began, putting back the scope it replaced (a nested
/// drawing's caller's, else none), then hand that window's picks to the owned route. Runs however the drawing
/// ended, also when it brought another window's state in.
pub(crate) fn leave_row_scope(&mut self, entered: Option<Entered>) {
let Some(Entered { window, previous }) = entered else { return };
self.owned_picks.rows.lock().scope = previous;
self.admit_row_picks(Some(window));
}
/// Right before the drawn window's dialog run: its dialog openings, so a pick filed in the run is bound to the
/// exact opening running it. Every dialog the run shows is open before it starts.
pub(crate) fn begin_row_forms(&mut self) {
if !self.windows.windowless_trial() {
return;
}
let forms: Vec<(DialogId, u64)> =
self.dialog_host.open_dialogs().iter().filter_map(|dialog| Some((dialog.id, self.dialog_host.open_serial(dialog.id)?))).collect();
if let Some(scope) = self.owned_picks.rows.lock().scope.as_mut() {
scope.forms = forms;
}
}
/// Right after the drawn window's dialog run: a pick filed after it is outside every dialog.
pub(crate) fn end_row_forms(&mut self) {
if !self.windows.windowless_trial() {
return;
}
if let Some(scope) = self.owned_picks.rows.lock().scope.as_mut() {
scope.forms.clear();
}
}
/// Hand staged `PathRow` picks (`window`'s, or every window's) to the owned route, bound to the window, document,
/// native window and dialog opening they were filed from. A pick whose window no longer stands so, or whose
/// window already has a pick, answers its row Cancelled. Then cancel forgotten row tickets and drop answers whose
/// window, document or dialog opening is gone.
pub(crate) fn admit_row_picks(&mut self, window: Option<u64>) {
let rows = self.owned_picks.rows.clone();
let ctx = self.ctx.clone().unwrap_or_default();
for Staged { id, owner, form, surface, request } in rows.take_staged(window) {
let current = self.row_form_live(owner.window, owner.document, form)
&& (surface.is_none() || self.row_surface(&ctx, owner.window, owner.document) == surface);
if !current {
self.status(tl!("The document window for this file dialog changed. Try again."));
rows.answer(id, owner, form, surface, Picked::Cancelled);
continue;
}
let target = RowTarget { id, form, surface };
// Busy (the window has a pick) says so in its status line.
if let Asked::Busy = self.push_owned_pick(owner.window, owner.document, request, AfterPick::Row(target)) {
rows.answer(id, owner, form, surface, Picked::Cancelled);
}
}
let forgotten = std::mem::take(&mut rows.lock().forgotten);
if !forgotten.is_empty() {
let (gone, kept): (Vec<_>, Vec<_>) = std::mem::take(&mut self.owned_picks.jobs)
.into_iter()
.partition(|job| matches!(&job.after, AfterPick::Row(row) if forgotten.contains(&row.id)));
self.owned_picks.jobs = kept;
for job in gone {
self.cancel_owned_pick(&ctx, job, PickEnd::Forgotten);
}
}
rows.prune(|owner, form| self.row_form_live(owner.window, owner.document, form));
}
/// Whether window `window` still shows open `document` and, for a pick filed from a dialog, that same opening of it
/// is still open on the window's own host (a closed and reopened dialog is another opening).
pub(crate) fn row_form_live(&self, window: u64, document: u64, form: RowForm) -> bool {
self.window_shows_document(window, document)
&& form.is_none_or(|(id, serial)| self.window_dialog_host(window).is_some_and(|host| host.open_serial(id) == Some(serial)))
}
/// Tell a row its pick will not open (the window's close or quit prompt took its place): Cancelled under its
/// ticket, bound as it was filed, so only that row reads it.
pub(super) fn cancel_row_pick(&mut self, window: u64, document: u64, row: RowTarget) {
self.owned_picks.rows.answer(row.id, RowOwner { window, document }, row.form, row.surface, Picked::Cancelled);
}
/// Post a settled row pick's answer under its exact ticket, bound to the native window it was pinned to (or, for
/// an owner that had none at filing, the one it has now); its row takes it on the owner's next draw. A system
/// dialog that could not show, or failed, says so in the owner window.
pub(super) fn settle_row_pick(
&mut self,
window: u64,
document: u64,
row: RowTarget,
pin: Option<NativeOwner>,
picked: Picked,
) -> serde_json::Value {
let note = match &picked {
Picked::Unavailable(cause) => Some(craft::dialogs::ui::UnavailableWords::default().sentence(cause)),
Picked::Failed(reason) => Some(reason.clone()),
_ => None,
};
if let Some(note) = note {
let previous = self.windows.shown();
if self.enter_window(window) {
self.status(note);
self.enter_window(previous);
}
}
let ctx = self.ctx.clone().unwrap_or_default();
let surface = pin
.map(|native| (native.viewport, native.attempt, native.incarnation))
.or(row.surface)
.or_else(|| self.row_surface(&ctx, window, document));
let cancelled = picked.first_path().is_none();
self.owned_picks.rows.answer(row.id, RowOwner { window, document }, row.form, surface, picked);
// The owner draws in its own viewport; every viewport is asked, as the owner's is not known here.
ctx.request_repaint();
serde_json::json!({"cancelled": cancelled})
}
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,238 @@
//! The `PathRow` route in the windowless trial, driven through real frames: each window draws (`draw_entry`, its dialog
//! run), and a dialog files and reads picks through the `Env` host exactly as `PathRow::show` does with `.pick(..)`
//! (`host.files().pick` on Browse, `take_answer` for its ticket on later passes). The in-app chooser stands in for the
//! system dialog (`fallback_chooser`); which native window parents a panel is the owned route's own tests.
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use craft::dialogs::ui::FileChooser;
use craft::host::{PickId, PickRequest, Picked, ScriptedFiles};
use craft::ui::dialog::{DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
use craft::ui::runtime::env::Env;
use serde_json::json;
use super::super::{AfterPick, NativeWindowLookup};
use crate::{Services, WordApp};
use wordcraft_engine::Session;
/// What a path row holds: its ticket, the answers it took, and a Browse press for its next pass.
#[derive(Default)]
struct Row {
browse: bool,
ticket: Option<PickId>,
got: Vec<Picked>,
}
/// A dialog with one path row, doing what `PathRow::show` does through the `Env` host: take its ticket's answer,
/// then file a pick when Browse was pressed.
struct RowDialog {
row: Arc<Mutex<Row>>,
}
impl StackDialog for RowDialog {
type Result = ();
fn id(&self) -> DialogId {
dialog_id("pathRowFixture")
}
fn show(&mut self, ui: &mut egui::Ui, _: &DialogStack) -> Option<DialogResult<()>> {
let host = Env::of(ui).view().host().cloned()?;
let mut row = self.row.lock().unwrap();
if let Some(ticket) = row.ticket
&& let Some(picked) = host.files().take_answer(ticket)
{
row.ticket = None;
row.got.push(picked);
}
if std::mem::take(&mut row.browse) {
row.ticket = Some(host.files().pick(PickRequest::open("template")));
}
None
}
}
/// Another dialog, opened over the row's.
struct Cover;
impl StackDialog for Cover {
type Result = ();
fn id(&self) -> DialogId {
dialog_id("pathRowCover")
}
fn show(&mut self, _: &mut egui::Ui, _: &DialogStack) -> Option<DialogResult<()>> {
None
}
}
/// The desktop's native windows: viewport to the incarnation of its live window.
#[derive(Default)]
struct Natives(Mutex<HashMap<egui::ViewportId, std::num::NonZeroU64>>);
impl NativeWindowLookup for Natives {
fn incarnation(&self, viewport: egui::ViewportId) -> Option<std::num::NonZeroU64> {
self.0.lock().unwrap().get(&viewport).copied()
}
}
/// Two windows in the windowless trial, each on its own unsaved document, using the in-app chooser.
fn two_windows() -> (WordApp, Arc<ScriptedFiles>, egui::Context, u64, u64) {
let files = Arc::new(ScriptedFiles::held());
let host =
craft::host::Host::builder(craft::host::AppInfo { id: "wordcraft-test", name: "WordCraft", version: "0" }).files(files.clone()).build();
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), Services::default()).with_host(Arc::new(host));
app.enable_windowless_trial(true);
app.fallback_chooser = true;
app.run("text.insert", json!({"text": "First"})).unwrap();
let first = app.windows.shown();
app.run("file.new", json!({})).unwrap();
app.run("text.insert", json!({"text": "Peer"})).unwrap();
let peer = app.windows.shown();
assert_ne!(first, peer);
(app, files, crate::test_harness::context(), first, peer)
}
/// Open a row dialog on window `window`'s host.
fn row_dialog(app: &mut WordApp, window: u64) -> (DialogId, Arc<Mutex<Row>>) {
let row = Arc::new(Mutex::new(Row::default()));
assert!(app.enter_window(window));
(app.dialog_host_mut().open(RowDialog { row: row.clone() }), row)
}
/// One frame drawing window `window`.
fn draw(app: &mut WordApp, ctx: &egui::Context, window: u64) {
app.show_window(window);
crate::test_harness::pass(ctx, app, egui::RawInput::default());
}
/// Press Browse in window `window`'s row and draw the frame that files it.
fn browse(app: &mut WordApp, ctx: &egui::Context, window: u64, row: &Arc<Mutex<Row>>) -> PickId {
row.lock().unwrap().browse = true;
draw(app, ctx, window);
row.lock().unwrap().ticket.expect("the row filed its pick")
}
fn pump(app: &mut WordApp, ctx: &egui::Context) {
app.pump_windowless_save_as(ctx, |panels, host| panels.pump_with::<eframe::Frame>(host, None));
}
fn row_target(app: &WordApp) -> super::RowTarget {
match &app.owned_picks.jobs[..] {
[job] => match &job.after {
AfterPick::Row(target) => *target,
_ => panic!("the pick is the row's"),
},
jobs => panic!("one owned pick, not {}", jobs.len()),
}
}
#[test]
fn a_row_pick_is_bound_to_the_dialog_running_it_not_the_top_one() {
let (mut app, _, ctx, first, _) = two_windows();
let (form, row) = row_dialog(&mut app, first);
app.dialog_host_mut().open(Cover);
let top = app.dialog_host_mut().open_dialogs().last().unwrap().id;
assert_ne!(top, form, "the fixture covers the row's dialog");
browse(&mut app, &ctx, first, &row);
let serial = app.window_dialog_host(first).unwrap().open_serial(form);
assert_eq!(row_target(&app).form, Some((form, serial.unwrap())), "bound to the row's own opening when it was filed");
}
#[test]
fn a_row_answer_reaches_only_its_row_in_its_own_window() {
let (mut app, files, ctx, first, peer) = two_windows();
let dir = std::env::temp_dir().join(format!("wordcraft-path-rows-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let template = dir.join("letter.dotx");
std::fs::write(&template, b"template").unwrap();
let (_, row) = row_dialog(&mut app, first);
let (_, peer_row) = row_dialog(&mut app, peer);
browse(&mut app, &ctx, first, &row);
draw(&mut app, &ctx, peer);
pump(&mut app, &ctx);
assert!(!app.window_dialog_host_mut(peer).unwrap().is_open::<FileChooser>(), "nothing opens on the focused peer");
let host = app.window_dialog_host_mut(first).unwrap();
let chooser = host.get::<FileChooser>().expect("the chooser opens on the row's window").id();
host.set_json_field(&ctx, chooser, "folder", json!(dir)).unwrap();
host.set_json_field(&ctx, chooser, "name", json!("letter.dotx")).unwrap();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
while !app.window_dialog_host_mut(first).unwrap().confirm_by_id(&ctx, chooser) {
assert!(std::time::Instant::now() < deadline, "the chooser lists the folder");
std::thread::sleep(std::time::Duration::from_millis(5));
}
pump(&mut app, &ctx);
// The peer draws while the answer settles: it is not the peer's.
draw(&mut app, &ctx, peer);
assert!(app.owned_picks.jobs.is_empty(), "settled");
assert!(row.lock().unwrap().got.is_empty() && peer_row.lock().unwrap().got.is_empty());
draw(&mut app, &ctx, first);
let got = row.lock().unwrap().got.iter().map(|picked| picked.first_path().and_then(|p| p.file_name().map(|n| n.to_owned()))).collect::<Vec<_>>();
assert_eq!(got, vec![template.file_name().map(|n| n.to_owned())], "its own row takes the chosen file, once");
draw(&mut app, &ctx, first);
assert_eq!(row.lock().unwrap().got.len(), 1);
assert!(peer_row.lock().unwrap().got.is_empty());
assert!(files.requests().is_empty(), "the app's shared file service never saw the pick");
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn a_row_answer_is_not_read_after_its_native_window_is_recreated() {
let (mut app, _, ctx, first, peer) = two_windows();
let natives = Arc::new(Natives::default());
let viewport = egui::ViewportId::from_hash_of("first");
app.attach_window_for_test(first, viewport);
natives.0.lock().unwrap().insert(viewport, std::num::NonZeroU64::new(1).unwrap());
app.set_native_window_lookup(Some(natives.clone() as Arc<dyn NativeWindowLookup + Send + Sync>));
let (_, row) = row_dialog(&mut app, first);
browse(&mut app, &ctx, first, &row);
assert!(row_target(&app).surface.is_some(), "filed on a named native window");
pump(&mut app, &ctx);
assert!(app.window_dialog_host_mut(first).unwrap().cancel::<FileChooser>(&ctx));
pump(&mut app, &ctx);
draw(&mut app, &ctx, peer);
assert!(app.owned_picks.jobs.is_empty(), "posted for the row");
// The OS window is recreated under the same viewport after the answer was posted, before the row reads it.
natives.0.lock().unwrap().insert(viewport, std::num::NonZeroU64::new(2).unwrap());
draw(&mut app, &ctx, first);
draw(&mut app, &ctx, first);
assert!(row.lock().unwrap().got.is_empty(), "an answer for the earlier native window is never read");
}
#[test]
fn a_reopened_dialog_never_reads_the_earlier_openings_answer() {
let (mut app, _, ctx, first, peer) = two_windows();
let (form, row) = row_dialog(&mut app, first);
let ticket = browse(&mut app, &ctx, first, &row);
pump(&mut app, &ctx);
assert!(app.window_dialog_host_mut(first).unwrap().cancel::<FileChooser>(&ctx));
pump(&mut app, &ctx);
draw(&mut app, &ctx, peer);
assert!(app.owned_picks.jobs.is_empty(), "posted for the row");
// The same dialog closes and opens again before its row draws; the new row even holds the old ticket.
assert!(app.enter_window(first));
assert!(app.dialog_host_mut().cancel_by_id(&ctx, form));
let reopened = Arc::new(Mutex::new(Row { ticket: Some(ticket), ..Row::default() }));
assert_eq!(app.dialog_host_mut().open(RowDialog { row: reopened.clone() }), form);
draw(&mut app, &ctx, first);
draw(&mut app, &ctx, first);
assert!(reopened.lock().unwrap().got.is_empty(), "another opening of the same dialog gets nothing");
assert!(row.lock().unwrap().got.is_empty());
}
#[test]
fn picks_outside_a_window_drawing_open_nothing_and_outside_the_trial_the_host_is_the_apps() {
let (mut app, files, _, _, _) = two_windows();
let host = app.frame_host();
let ticket = host.files().pick(PickRequest::open("document"));
app.admit_row_picks(None);
assert!(app.owned_picks.jobs.is_empty(), "no window is made the owner of a pick filed outside every drawing");
assert_eq!(host.files().take_answer(ticket), Some(Picked::Cancelled));
assert!(files.requests().is_empty(), "nothing went to the shared service either");
let plain = Arc::new(craft::host::Host::builder(craft::host::AppInfo { id: "wordcraft-test", name: "WordCraft", version: "0" }).build());
let mut ordinary = WordApp::new(Session::new(wordcraft_doc::Document::new()), Services::default()).with_host(plain.clone());
assert!(Arc::ptr_eq(&ordinary.frame_host(), &plain), "ordinary windows and the web keep the app's own host");
}
+929
View File
@@ -993,3 +993,932 @@ fn entries_expose_names_selection_and_picking() {
let answer = h.state_mut().dialog_host.take::<FileChooser>();
assert_eq!(answer, Some(DialogResult::Ok(Answer::Paths(vec![PathBuf::from("/d/chapter.docx")]))));
}
/// #6131: File › Export to DOCX, ODT or RTF writes a copy. It ran a plain Save As, which made
/// the copy the document's file and cleared its unsaved changes, so the next Save updated the
/// copy and the original kept its old text.
#[test]
fn export_writes_a_copy_and_keeps_the_documents_file() {
let dir = scratch("export-copy");
for ext in ["docx", "odt", "rtf"] {
let original = dir.join(format!("a-{ext}.docx"));
let (mut a, _) = async_app();
a.run("text.insert", json!({"text": "first"})).unwrap();
a.run("file.save", json!({"path": original.to_string_lossy()})).unwrap();
a.run("text.insert", json!({"text": " edited"})).unwrap();
let copy = dir.join(format!("copy.{ext}"));
a.finish_pick(AfterPick::Export { ext: ext.into() }, Some(copy.to_string_lossy().into_owned())).unwrap();
assert_eq!(saved_text(&copy), "first edited", "{ext}: the copy has the edits");
assert_eq!(a.session.path.as_deref(), Some(original.as_path()), "{ext}: the document keeps its file");
assert!(a.session.dirty, "{ext}: the document keeps its unsaved changes");
a.run("file.save", json!({})).unwrap();
assert_eq!(saved_text(&original), "first edited", "{ext}: Save still writes the original");
}
let _ = std::fs::remove_dir_all(&dir);
}
/// #6131, browser: exporting a DOCX, ODT or RTF copy downloads it and leaves the document's
/// unsaved changes and save stamps alone.
#[test]
fn web_export_downloads_a_copy_and_keeps_unsaved_changes() {
let files = Arc::new(ScriptedFiles::new().in_browser().saving_suggested());
let mut a = app_over(&files, wordcraft_doc::Document::new());
typed(&mut a);
for ext in ["docx", "odt", "rtf"] {
let revision = a.session.doc.core.revision;
let name = format!("copy.{ext}");
let result = a.finish_pick(AfterPick::Export { ext: ext.into() }, Some(name.clone())).unwrap();
assert_eq!(result["downloaded"], name, "{ext}");
let request = files.requests().pop().unwrap();
assert_eq!(request.file_name.as_deref(), Some(name.as_str()), "{ext}");
assert!(!request.save_as, "{ext}: a copy is never Save As");
let bytes = files.file(std::path::Path::new(&name)).unwrap();
let back = wordcraft_engine::io::open_bytes(&name, &bytes).unwrap();
assert_eq!(back.plain_text(wordcraft_doc::StoryRef::Body), UNSAVED, "{ext}: the copy has the text");
a.settle_saves();
assert!(a.session.dirty, "{ext}: the document keeps its unsaved changes");
assert!(a.session.path.is_none(), "{ext}: the document keeps no file of its own");
assert_eq!(a.session.doc.core.revision, revision, "{ext}: the document's save stamps are untouched");
}
}
#[cfg(not(target_arch = "wasm32"))]
fn two_windowless_drafts() -> (WordApp, Arc<ScriptedFiles>, u64, u64, u64, u64) {
let (mut app, files) = async_app();
app.enable_windowless_trial(true);
app.run("text.insert", json!({"text": "First unsaved draft"})).unwrap();
let (first, first_doc) = (app.windows.shown(), app.session.document_id());
app.run("file.new", json!({})).unwrap();
app.run("text.insert", json!({"text": "Peer unsaved draft"})).unwrap();
let (peer, peer_doc) = (app.windows.shown(), app.session.document_id());
assert_ne!(first, peer);
assert_ne!(first_doc, peer_doc);
assert!(app.session.path.is_none() && app.session.document_dirty(first_doc) && app.session.document_dirty(peer_doc));
(app, files, first, first_doc, peer, peer_doc)
}
#[cfg(not(target_arch = "wasm32"))]
fn begin_trial_save(app: &mut WordApp, first: u64, peer: u64) {
app.close_window(first);
assert_eq!(app.run("ui.saveChanges", json!({"answer": "save"})).unwrap()["pending"], "saveAs");
app.show_window(peer);
assert_eq!(app.windows.shown(), peer, "the peer takes focus before the next panel pump");
}
#[cfg(not(target_arch = "wasm32"))]
fn pump_trial_save(app: &mut WordApp, ctx: &egui::Context) {
app.pump_windowless_save_as(ctx, |panels, host| panels.pump_with::<eframe::Frame>(host, None));
}
#[cfg(not(target_arch = "wasm32"))]
fn choose_trial_save_path(app: &mut WordApp, ctx: &egui::Context, window: u64, path: &std::path::Path) {
let host = app.window_dialog_host_mut(window).unwrap();
let chooser = host.get::<FileChooser>().unwrap().id();
host.set_json_field(ctx, chooser, "folder", json!(path.parent().unwrap())).unwrap();
host.set_json_field(ctx, chooser, "name", json!(path.file_name().unwrap().to_string_lossy())).unwrap();
// The real chooser waits for its background folder listing before accepting a new path.
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
loop {
if host.confirm_by_id(ctx, chooser) {
break;
}
assert!(std::time::Instant::now() < deadline, "the temporary folder should become available to the chooser");
std::thread::sleep(std::time::Duration::from_millis(5));
}
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn windowless_untitled_close_save_as_stays_with_its_document_after_peer_focus() {
let (mut app, files, first, first_doc, peer, peer_doc) = two_windowless_drafts();
let dir = scratch("windowless-save-as");
let destination = dir.join("draft.docx");
let ctx = egui::Context::default();
begin_trial_save(&mut app, first, peer);
pump_trial_save(&mut app, &ctx);
assert_eq!(app.session.document_id(), peer_doc);
assert!(!app.dialog_host_mut().is_open::<FileChooser>(), "the chooser is not on the focused peer's host");
assert!(app.window_dialog_host_mut(first).unwrap().cancel::<FileChooser>(&ctx), "the initiating window owns the in-app chooser");
pump_trial_save(&mut app, &ctx);
assert_eq!(app.poll_file_dialog().unwrap().unwrap()["done"], false);
assert!(!destination.exists() && !app.quit_requested);
assert_eq!(app.window_count(), 2);
assert!(app.session.document_dirty(first_doc) && app.session.document_dirty(peer_doc));
assert!(app.enter_window(first));
assert!(app.session.path.is_none());
assert_eq!(body_text(&app).trim(), "First unsaved draft");
assert!(app.enter_window(peer));
assert!(app.session.path.is_none());
assert_eq!(body_text(&app).trim(), "Peer unsaved draft");
let sentinel = b"Existing file stays until Replace is answered";
std::fs::write(&destination, sentinel).unwrap();
begin_trial_save(&mut app, first, peer);
pump_trial_save(&mut app, &ctx);
// The chooser answers the bare name; adding .docx produces a collision the panels must ask about.
choose_trial_save_path(&mut app, &ctx, first, &destination.with_extension(""));
pump_trial_save(&mut app, &ctx);
assert!(app.poll_file_dialog().is_none());
assert_eq!(std::fs::read(&destination).unwrap(), sentinel);
assert!(!app.dialog_host_mut().is_open::<StandardPrompt>());
assert!(app.window_dialog_host_mut(first).unwrap().confirm::<StandardPrompt>(&ctx), "the initiating window also owns Replace");
pump_trial_save(&mut app, &ctx);
assert_eq!(app.poll_file_dialog().unwrap().unwrap()["done"], true);
let saved = saved_text(&destination);
assert!(saved.contains("First unsaved draft"));
assert!(!saved.contains("Peer unsaved draft"));
assert!(!app.session.is_open(first_doc) && !app.quit_requested);
assert_eq!(app.window_count(), 1);
assert_eq!(app.session.document_id(), peer_doc);
assert!(app.session.dirty && app.session.path.is_none());
assert_eq!(body_text(&app).trim(), "Peer unsaved draft");
assert!(files.requests().is_empty(), "the shared native file service never received the request");
let _ = std::fs::remove_dir_all(dir);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn windowless_save_as_discards_its_late_answer_when_the_owner_closes() {
let (mut app, files, first, first_doc, peer, peer_doc) = two_windowless_drafts();
let dir = scratch("windowless-stale-save-as");
let destination = dir.join("stale.docx");
let ctx = egui::Context::default();
begin_trial_save(&mut app, first, peer);
pump_trial_save(&mut app, &ctx);
choose_trial_save_path(&mut app, &ctx, first, &destination);
pump_trial_save(&mut app, &ctx);
// Put the answer in the service, then invalidate the owner before WordApp sees it.
app.session.close_document(first_doc).unwrap();
app.prune_windows();
assert!(app.poll_file_dialog().is_none());
app.pump_windowless_save_as(&ctx, |_, _| panic!("a stale job must not be pumped on the survivor"));
assert!(!destination.exists() && !app.quit_requested);
assert_eq!(app.session.document_id(), peer_doc);
assert!(app.session.dirty && app.session.path.is_none());
assert_eq!(body_text(&app).trim(), "Peer unsaved draft");
app.close_window(peer);
assert_eq!(app.run("ui.saveChanges", json!({"answer": "save"})).unwrap()["pending"], "saveAs");
pump_trial_save(&mut app, &ctx);
assert!(app.dialog_host_mut().is_open::<FileChooser>(), "a fresh ticket can open on the survivor's own host");
assert!(files.requests().is_empty(), "no routed ticket leaked into the shared file service");
let _ = std::fs::remove_dir_all(dir);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn windowless_save_as_does_not_cancel_a_later_replace_prompt_with_the_same_id() {
let (mut app, _, first, first_doc, peer, peer_doc) = two_windowless_drafts();
let dir = scratch("windowless-reused-replace");
let destination = dir.join("existing.docx");
let sentinel = b"Existing file";
std::fs::write(&destination, sentinel).unwrap();
let ctx = egui::Context::default();
begin_trial_save(&mut app, first, peer);
pump_trial_save(&mut app, &ctx);
choose_trial_save_path(&mut app, &ctx, first, &destination.with_extension(""));
pump_trial_save(&mut app, &ctx);
let ticket = app.owned_picks.jobs[0].ticket.as_ref().unwrap().id.0;
let host = app.window_dialog_host_mut(first).unwrap();
let first_prompt = host.get::<StandardPrompt>().unwrap().id();
let first_serial = host.open_serial(first_prompt).unwrap();
// Another panel service can produce the same instance key from its own local ticket count.
let unrelated = host.open(StandardPrompt::replace_file("other.docx", None).instance(("craft-dialogs.replace", ticket)));
assert_eq!(unrelated, first_prompt, "the fixture must reuse the framework's Replace ID");
let unrelated_serial = host.open_serial(unrelated).unwrap();
assert_ne!(unrelated_serial, first_serial);
app.pump_windowless_save_as(&ctx, |_, _| panic!("a displaced job must not collect the later prompt's answer"));
assert!(!app.file_dialog_open() && app.closing.is_none());
assert_eq!(app.window_dialog_host_mut(first).unwrap().open_serial(unrelated), Some(unrelated_serial));
assert_eq!(std::fs::read(&destination).unwrap(), sentinel);
assert!(app.session.document_dirty(first_doc) && app.session.document_dirty(peer_doc));
let _ = std::fs::remove_dir_all(dir);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn windowless_save_as_cancels_when_its_own_surface_is_rejected() {
let (mut app, files, first, first_doc, peer, peer_doc) = two_windowless_drafts();
let ctx = egui::Context::default();
begin_trial_save(&mut app, first, peer);
pump_trial_save(&mut app, &ctx);
app.cancel_windowless_save_as_for_mount_failure(&ctx, peer);
assert_eq!(app.owned_picks.jobs.len(), 1, "a rejected peer is not the picker's owner");
assert!(app.window_dialog_host_mut(first).unwrap().is_open::<FileChooser>());
app.cancel_windowless_save_as_for_mount_failure(&ctx, first);
assert!(app.owned_picks.jobs.is_empty() && app.closing.is_none());
assert!(!app.window_dialog_host_mut(first).unwrap().is_open::<FileChooser>());
assert!(app.session.document_dirty(first_doc) && app.session.document_dirty(peer_doc));
assert_eq!(app.session.document_id(), peer_doc);
assert!(files.requests().is_empty());
assert!(!app.quit_requested);
}
/// The desktop's native windows, for routing tests: viewport to the incarnation of its live
/// native window, changed by the test to model attach, detach and recreation.
#[cfg(not(target_arch = "wasm32"))]
#[derive(Default)]
struct TestWindows(std::sync::Mutex<std::collections::HashMap<egui::ViewportId, std::num::NonZeroU64>>);
#[cfg(not(target_arch = "wasm32"))]
impl TestWindows {
fn set(&self, viewport: egui::ViewportId, incarnation: Option<u64>) {
let mut map = self.0.lock().unwrap();
match incarnation {
Some(n) => map.insert(viewport, nz(n)),
None => map.remove(&viewport),
};
}
}
#[cfg(not(target_arch = "wasm32"))]
impl NativeWindowLookup for TestWindows {
fn incarnation(&self, viewport: egui::ViewportId) -> Option<std::num::NonZeroU64> {
self.0.lock().unwrap().get(&viewport).copied()
}
}
/// The desktop's panel pumps, for routing tests. Its panels are scripted (`SCRIPTED_PANELS`),
/// so a test never shows a system dialog: this checks routing, ownership and lease bookkeeping,
/// not that a native panel looks or parents right, nor native window lifetime.
///
/// `pending` models a system dialog whose backend has not answered yet. The pinned SDK has no
/// public panel that stays open after its queue drains (its scripted panels answer at once), so
/// while pending the double pumps nothing at all, neither the launch nor later pumps; the first
/// pump after release drains, shows and answers in one go. The launch itself is still exact: it
/// happens only through `pump_parented` on the pinned window, and returns its lease.
#[cfg(not(target_arch = "wasm32"))]
#[derive(Default)]
struct Desk {
lookup: Arc<TestWindows>,
parented: Vec<(egui::ViewportId, std::num::NonZeroU64)>,
unparented: usize,
/// Each viewport's stand-in for its window; a lease holds a clone.
windows: std::collections::HashMap<egui::ViewportId, Arc<()>>,
pending: bool,
}
#[cfg(not(target_arch = "wasm32"))]
impl Desk {
fn leases(&self, viewport: egui::ViewportId) -> usize {
self.windows.get(&viewport).map_or(0, |w| Arc::strong_count(w) - 1)
}
}
#[cfg(not(target_arch = "wasm32"))]
impl OwnerPanels for Desk {
fn pump_parented(
&mut self,
viewport: egui::ViewportId,
incarnation: std::num::NonZeroU64,
panels: &mut FilePanels,
host: &mut DialogHost,
) -> Option<ParentLease> {
if self.lookup.incarnation(viewport) != Some(incarnation) {
return None;
}
assert!(SCRIPTED_PANELS.with(|s| s.borrow().is_some()), "a routing test never shows a real system dialog");
self.parented.push((viewport, incarnation));
if !self.pending {
panels.pump_with::<eframe::Frame>(host, None);
}
Some(ParentLease::new(self.windows.entry(viewport).or_default().clone()))
}
fn pump_unparented(&mut self, panels: &mut FilePanels, host: &mut DialogHost) {
self.unparented += 1;
if !self.pending {
panels.pump_with::<eframe::Frame>(host, None);
}
}
}
#[cfg(not(target_arch = "wasm32"))]
fn nz(n: u64) -> std::num::NonZeroU64 {
std::num::NonZeroU64::new(n).unwrap()
}
#[cfg(not(target_arch = "wasm32"))]
fn script_panels(answers: Vec<craft::dialogs::Answer>) {
script_each_panel(vec![answers]);
}
#[cfg(not(target_arch = "wasm32"))]
fn script_each_panel(lists: Vec<Vec<craft::dialogs::Answer>>) {
SCRIPTED_PANELS.with(|s| *s.borrow_mut() = Some(lists.into()));
}
/// A desk whose lookup the app reads, and a context the app knows (the gesture reads surfaces).
#[cfg(not(target_arch = "wasm32"))]
fn connect_desk(app: &mut WordApp) -> (Desk, egui::Context) {
let desk = Desk::default();
app.set_native_window_lookup(Some(desk.lookup.clone()));
let ctx = egui::Context::default();
app.ctx = Some(ctx.clone());
(desk, ctx)
}
/// Two drafts whose windows are attached at their own viewports, both with live native windows.
#[cfg(not(target_arch = "wasm32"))]
fn attached_drafts() -> (WordApp, Arc<ScriptedFiles>, u64, u64, u64, u64, Desk, egui::Context) {
let (mut app, files, first, first_doc, peer, peer_doc) = two_windowless_drafts();
let (desk, ctx) = connect_desk(&mut app);
app.attach_window_for_test(first, va());
app.attach_window_for_test(peer, vb());
desk.lookup.set(va(), Some(1));
desk.lookup.set(vb(), Some(2));
(app, files, first, first_doc, peer, peer_doc, desk, ctx)
}
#[cfg(not(target_arch = "wasm32"))]
fn va() -> egui::ViewportId {
egui::ViewportId::from_hash_of("first")
}
#[cfg(not(target_arch = "wasm32"))]
fn vb() -> egui::ViewportId {
egui::ViewportId::from_hash_of("peer")
}
#[cfg(not(target_arch = "wasm32"))]
fn next_pass(ctx: &egui::Context) {
ctx.run_ui(Default::default(), |_| {}).drop_without_applying_deltas();
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn windowless_save_as_opens_the_system_dialog_on_its_own_window_after_peer_focus() {
let (mut app, files, first, first_doc, peer, peer_doc, mut desk, ctx) = attached_drafts();
let dir = scratch("windowless-native-save-as");
let destination = dir.join("draft.docx");
script_panels(vec![craft::dialogs::Answer::Saved { path: destination.clone(), filter: None }]);
begin_trial_save(&mut app, first, peer);
app.pump_owned_picks(&ctx, &mut desk);
assert_eq!(desk.parented, vec![(va(), nz(1))], "only the initiating window's live native window parents the dialog");
assert_eq!(desk.unparented, 0);
assert!(!app.dialog_host_mut().is_open::<FileChooser>() && !app.window_dialog_host_mut(first).unwrap().is_open::<FileChooser>());
assert_eq!(desk.leases(va()), 0, "an answered panel no longer holds its window");
assert_eq!(app.poll_file_dialog().unwrap().unwrap()["done"], true);
let saved = saved_text(&destination);
assert!(saved.contains("First unsaved draft") && !saved.contains("Peer unsaved draft"));
assert!(!app.session.is_open(first_doc) && !app.quit_requested);
assert_eq!(app.session.document_id(), peer_doc);
assert!(app.session.dirty && app.session.path.is_none());
assert!(files.requests().is_empty(), "the shared file service never received the request");
let _ = std::fs::remove_dir_all(dir);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn windowless_save_as_pinned_at_the_gesture_ends_if_its_window_is_recreated_before_launch() {
let (mut app, _, first, first_doc, peer, peer_doc, mut desk, ctx) = attached_drafts();
script_panels(vec![craft::dialogs::Answer::Cancelled]);
begin_trial_save(&mut app, first, peer);
// Recreated between the gesture and the first pump: the pick must not move to the new window.
desk.lookup.set(va(), Some(3));
app.pump_owned_picks(&ctx, &mut desk);
assert!(desk.parented.is_empty() && app.owned_picks.jobs.is_empty());
assert!(app.closing.is_none() && !app.quit_requested);
assert!(app.session.document_dirty(first_doc) && app.session.document_dirty(peer_doc));
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn windowless_save_as_does_not_settle_an_answer_after_its_window_is_recreated() {
let (mut app, _, first, first_doc, peer, peer_doc, mut desk, ctx) = attached_drafts();
let dir = scratch("windowless-native-replaced");
let destination = dir.join("stale.docx");
script_panels(vec![craft::dialogs::Answer::Saved { path: destination.clone(), filter: None }]);
begin_trial_save(&mut app, first, peer);
app.pump_owned_picks(&ctx, &mut desk);
assert!(app.owned_picks.jobs[0].answer.is_some(), "the answer is in");
// Recreated after the answer and before its consumption, with no pump in between.
desk.lookup.set(va(), Some(3));
assert!(app.poll_file_dialog().is_none(), "the last use checks the exact window itself");
assert!(!destination.exists());
app.pump_owned_picks(&ctx, &mut desk);
assert!(app.owned_picks.jobs.is_empty() && app.closing.is_none() && !app.quit_requested);
assert!(app.owned_picks.retired.is_empty(), "an answered panel needs no cleanup");
assert_eq!(desk.leases(va()), 0);
assert!(app.session.document_dirty(first_doc) && app.session.document_dirty(peer_doc));
begin_trial_save(&mut app, first, peer);
app.pump_owned_picks(&ctx, &mut desk);
assert_eq!(desk.parented.last(), Some(&(va(), nz(3))), "a new gesture pins the new window");
let _ = std::fs::remove_dir_all(dir);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn windowless_save_as_does_not_settle_an_answer_after_its_surface_remounts() {
let (mut app, _, first, first_doc, peer, peer_doc, mut desk, ctx) = attached_drafts();
let dir = scratch("windowless-native-remount");
let destination = dir.join("stale.docx");
script_panels(vec![craft::dialogs::Answer::Saved { path: destination.clone(), filter: None }]);
begin_trial_save(&mut app, first, peer);
app.pump_owned_picks(&ctx, &mut desk);
app.remount_window_for_test(first);
assert!(app.poll_file_dialog().is_none(), "an answer for the earlier surface is not settled");
app.pump_owned_picks(&ctx, &mut desk);
assert!(app.owned_picks.jobs.is_empty() && !destination.exists());
assert!(app.session.document_dirty(first_doc) && app.session.document_dirty(peer_doc));
let _ = std::fs::remove_dir_all(dir);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn windowless_save_as_binds_a_mounting_owner_on_its_first_attachment() {
let (mut app, _, first, _, peer, _) = two_windowless_drafts();
let (mut desk, ctx) = connect_desk(&mut app);
app.attach_window_for_test(peer, vb());
desk.lookup.set(vb(), Some(2));
script_panels(vec![craft::dialogs::Answer::Cancelled]);
begin_trial_save(&mut app, first, peer);
for _ in 0..2 * super::MISSING_PASSES {
app.pump_owned_picks(&ctx, &mut desk);
next_pass(&ctx);
}
assert!(desk.parented.is_empty() && desk.unparented == 0, "nothing shows before the owner's surface exists");
assert!(!app.window_dialog_host_mut(first).unwrap().is_open::<FileChooser>(), "mounting is not a failure");
assert_eq!(app.owned_picks.jobs.len(), 1);
app.attach_window_for_test(first, va());
desk.lookup.set(va(), Some(1));
app.pump_owned_picks(&ctx, &mut desk);
assert_eq!(desk.parented, vec![(va(), nz(1))], "its own first window, never the peer's");
assert_eq!(app.poll_file_dialog().unwrap().unwrap()["done"], false);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn windowless_save_as_uses_the_owner_chooser_after_its_native_window_stays_missing() {
let (mut app, files, first, first_doc, peer, peer_doc, mut desk, ctx) = attached_drafts();
desk.lookup.set(va(), None);
begin_trial_save(&mut app, first, peer);
for _ in 1..super::MISSING_PASSES {
// Two pumps a frame, as the desktop runs them: only scheduled passes count.
app.pump_owned_picks(&ctx, &mut desk);
app.pump_owned_picks(&ctx, &mut desk);
next_pass(&ctx);
}
assert!(!app.window_dialog_host_mut(first).unwrap().is_open::<FileChooser>(), "a missing window is retried before falling back");
// Attached-but-missing at the gesture never binds later: the window that appears is not pinned.
desk.lookup.set(va(), Some(4));
app.pump_owned_picks(&ctx, &mut desk);
assert!(desk.parented.is_empty(), "no other or later window stands in for the missing one");
assert!(desk.unparented > 0);
assert!(app.window_dialog_host_mut(first).unwrap().cancel::<FileChooser>(&ctx), "the chooser opens on the initiating window");
assert!(!app.dialog_host_mut().is_open::<FileChooser>());
app.pump_owned_picks(&ctx, &mut desk);
assert_eq!(app.poll_file_dialog().unwrap().unwrap()["done"], false);
assert!(app.session.document_dirty(first_doc) && app.session.document_dirty(peer_doc));
assert!(files.requests().is_empty());
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn windowless_save_as_keeps_the_built_in_chooser_preference() {
let (mut app, _, first, _, peer, _, mut desk, ctx) = attached_drafts();
app.fallback_chooser = true;
begin_trial_save(&mut app, first, peer);
app.pump_owned_picks(&ctx, &mut desk);
assert!(desk.parented.is_empty(), "the preference bypasses the system dialog");
assert!(app.window_dialog_host_mut(first).unwrap().is_open::<FileChooser>());
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn windowless_save_as_falls_back_on_its_own_window_when_the_system_dialog_cannot_show() {
let (mut app, _, first, first_doc, peer, peer_doc, mut desk, ctx) = attached_drafts();
script_panels(vec![craft::dialogs::Answer::Unavailable("no file chooser portal".into())]);
begin_trial_save(&mut app, first, peer);
app.pump_owned_picks(&ctx, &mut desk);
assert_eq!(desk.parented, vec![(va(), nz(1))]);
assert!(!app.dialog_host_mut().is_open::<FileChooser>());
assert!(app.window_dialog_host_mut(first).unwrap().cancel::<FileChooser>(&ctx), "the shared fallback opens on the owner");
app.pump_owned_picks(&ctx, &mut desk);
assert_eq!(app.poll_file_dialog().unwrap().unwrap()["done"], false);
assert!(app.closing.is_none() && app.session.document_dirty(first_doc) && app.session.document_dirty(peer_doc));
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn windowless_picks_belong_to_their_windows_and_end_only_with_them() {
let (mut app, files, first, first_doc, peer, _) = two_windowless_drafts();
let (mut desk, ctx) = connect_desk(&mut app);
begin_trial_save(&mut app, first, peer);
app.pick_picture();
assert_eq!(app.owned_picks.jobs.len(), 2, "the peer window has its own pick");
app.open_dialog();
assert_eq!(app.owned_picks.jobs.len(), 2, "one pick per window");
app.pump_owned_picks(&ctx, &mut desk);
assert!(desk.parented.is_empty(), "mounting owners wait");
app.session.close_document(first_doc).unwrap();
app.prune_windows();
app.pump_owned_picks(&ctx, &mut desk);
assert_eq!(app.owned_picks.jobs.len(), 1);
assert_eq!(app.owned_picks.jobs[0].window, peer, "closing one window cancels only its pick");
assert!(app.file_dialog_open());
assert!(files.requests().is_empty());
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_cancelled_picture_pick_clears_only_its_own_windows_change_picture_target() {
let (mut app, _, first, _, peer, _, mut desk, ctx) = attached_drafts();
assert!(app.enter_window(first));
app.change_picture_target = Some("first-picture".into());
app.pick_picture();
app.show_window(peer);
app.change_picture_target = Some("peer-picture".into());
// The owner's window is recreated before launch: its pick ends.
desk.lookup.set(va(), Some(3));
app.pump_owned_picks(&ctx, &mut desk);
assert!(app.owned_picks.jobs.is_empty());
assert_eq!(app.change_picture_target.as_deref(), Some("peer-picture"), "the drawn peer's target is not touched");
assert!(app.enter_window(first));
assert_eq!(app.change_picture_target, None, "the owner's pending Change Picture is cleared");
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_home_window_open_ends_when_its_start_screen_placeholder_is_replaced() {
let (mut app, files) = async_app();
app.enable_windowless_trial(true);
let (mut desk, ctx) = connect_desk(&mut app);
app.run("file.close", json!({})).unwrap();
assert!(!app.has_document(), "the Start screen's window shows no document");
let (home, placeholder) = (app.windows.shown(), app.shown_document);
app.open_dialog();
assert_eq!((app.owned_picks.jobs[0].window, app.owned_picks.jobs[0].document), (home, placeholder), "Home's Open is owned by Home");
app.run("file.new", json!({})).unwrap();
assert!(!app.window_shows_document(home, placeholder), "the placeholder was replaced");
app.pump_owned_picks(&ctx, &mut desk);
assert!(app.owned_picks.jobs.is_empty(), "a replaced Home placeholder ends its Open");
assert!(desk.parented.is_empty() && files.requests().is_empty());
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn windowless_export_opens_the_system_dialog_on_its_own_window() {
let (mut app, files, first, first_doc, peer, peer_doc, mut desk, ctx) = attached_drafts();
let dir = scratch("windowless-native-export");
let destination = dir.join("first.html");
script_panels(vec![craft::dialogs::Answer::Saved { path: destination.clone(), filter: None }]);
assert!(app.enter_window(first));
app.export_dialog("html");
app.show_window(peer);
app.pump_owned_picks(&ctx, &mut desk);
assert_eq!(desk.parented, vec![(va(), nz(1))]);
app.poll_file_dialog().unwrap().unwrap();
let exported = std::fs::read_to_string(&destination).unwrap();
assert!(exported.contains("First unsaved draft") && !exported.contains("Peer unsaved draft"));
assert_eq!(app.session.document_id(), peer_doc);
assert!(app.session.document_dirty(first_doc), "an export is a copy");
assert!(files.requests().is_empty());
let _ = std::fs::remove_dir_all(dir);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_document_closed_under_its_pending_system_dialog_keeps_that_window_leased_until_the_dialog_settles() {
let (mut app, _, first, first_doc, peer, peer_doc, mut desk, ctx) = attached_drafts();
let dir = scratch("windowless-native-close-while-open");
let destination = dir.join("late.docx");
// The first window's dialog answers late; the peer's Open is cancelled.
script_each_panel(vec![vec![craft::dialogs::Answer::Saved { path: destination.clone(), filter: None }], vec![craft::dialogs::Answer::Cancelled]]);
desk.pending = true;
begin_trial_save(&mut app, first, peer);
app.open_dialog();
app.pump_owned_picks(&ctx, &mut desk);
assert_eq!(desk.parented, vec![(va(), nz(1)), (vb(), nz(2))], "each window's pick launched on its own window");
assert_eq!((desk.leases(va()), desk.leases(vb())), (1, 1));
// An agent closes the document under its open dialog (no app Close entry point is involved).
app.session.close_document(first_doc).unwrap();
app.prune_windows();
app.pump_owned_picks(&ctx, &mut desk);
assert_eq!(app.owned_picks.jobs.len(), 1);
assert_eq!(app.owned_picks.jobs[0].window, peer, "only the closed window's pick ends");
assert_eq!(app.owned_picks.retired.len(), 1, "its pending dialog is left to finish, not cancelled");
assert_eq!(desk.leases(va()), 1, "so its parent stays leased");
assert_eq!(desk.leases(vb()), 1, "the peer's lease is untouched");
assert!(app.native_file_panels_open());
// The dialog finishes: its late answer is dropped, then the parent is released.
desk.pending = false;
app.pump_owned_picks(&ctx, &mut desk);
assert!(app.owned_picks.retired.is_empty());
assert_eq!(desk.leases(va()), 0);
assert_eq!(app.poll_file_dialog().unwrap().unwrap(), json!({"cancelled": true}), "the peer's own pick settles in its window");
assert_eq!(desk.leases(vb()), 0);
assert!(!destination.exists(), "the closed document's late answer saves nothing");
assert!(app.session.is_open(peer_doc) && !app.quit_requested);
let _ = std::fs::remove_dir_all(dir);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn native_dialogs_are_admitted_within_a_bound_that_counts_settling_ones() {
let (mut app, _, first, first_doc, peer, _, mut desk, ctx) = attached_drafts();
script_panels(vec![craft::dialogs::Answer::Cancelled]);
desk.pending = true;
begin_trial_save(&mut app, first, peer);
app.open_dialog();
app.pump_owned_picks(&ctx, &mut desk);
assert_eq!(desk.parented.len(), super::MAX_NATIVE_OPERATIONS);
app.session.close_document(first_doc).unwrap();
app.prune_windows();
app.pump_owned_picks(&ctx, &mut desk);
assert_eq!(app.owned_picks.retired.len(), 1);
// A third window asks while one dialog settles and one is live: it waits, holding nothing.
app.run("file.new", json!({})).unwrap();
let third = app.windows.shown();
let vc = egui::ViewportId::from_hash_of("third");
app.attach_window_for_test(third, vc);
desk.lookup.set(vc, Some(5));
app.open_dialog();
app.pump_owned_picks(&ctx, &mut desk);
assert_eq!(desk.parented.len(), super::MAX_NATIVE_OPERATIONS, "no third system dialog while two may use their windows");
assert_eq!(desk.leases(vc), 0);
desk.pending = false;
app.pump_owned_picks(&ctx, &mut desk);
app.pump_owned_picks(&ctx, &mut desk);
assert_eq!(desk.parented.last(), Some(&(vc, nz(5))), "it launches once the earlier ones have ended");
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn quit_waits_for_a_pending_system_dialog_then_goes_on_through_the_unsaved_prompt() {
let (mut app, _, _, first_doc, _, peer_doc, mut desk, ctx) = attached_drafts();
script_panels(vec![craft::dialogs::Answer::Cancelled]);
desk.pending = true;
app.save_as_dialog();
app.pump_owned_picks(&ctx, &mut desk);
assert_eq!(desk.leases(vb()), 1);
// The entry point the app menu, the OS Quit intake and the last window's close all use.
assert!(!app.quit());
assert_eq!(app.close_decision(), craft::ui::shell::embed::CloseDecision::Hold, "the platform's close is held too");
assert!(!app.quit_requested && app.closing.is_none(), "no unsaved-changes prompt was started or answered");
assert!(app.session.document_dirty(first_doc) && app.session.document_dirty(peer_doc));
desk.pending = false;
app.pump_owned_picks(&ctx, &mut desk);
assert_eq!(desk.leases(vb()), 0, "the lease ends with the dialog's answer");
assert_eq!(app.poll_file_dialog().unwrap().unwrap()["saved"], false);
app.pump_owned_picks(&ctx, &mut desk);
assert!(app.closing.is_some(), "the quit goes on by itself and asks about the drafts as usual");
assert!(!app.quit_requested);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn closing_a_window_waits_for_its_own_pending_system_dialog_but_not_for_others() {
let (mut app, _, first, first_doc, peer, peer_doc, mut desk, ctx) = attached_drafts();
script_panels(vec![craft::dialogs::Answer::Cancelled]);
desk.pending = true;
app.save_as_dialog();
app.pump_owned_picks(&ctx, &mut desk);
assert_eq!(desk.leases(vb()), 1);
app.close_window(peer);
assert!(app.closing.is_none() && app.window_shows_document(peer, peer_doc), "the peer's close waits for its dialog");
assert_eq!(app.run("file.close", json!({})).unwrap()["deferred"], true, "File › Close in it waits too");
app.close_window(first);
assert!(app.closing.as_ref().is_some_and(|c| c.window == first), "an unrelated window closes as usual");
app.cancel_closing();
desk.pending = false;
app.pump_owned_picks(&ctx, &mut desk);
assert_eq!(app.poll_file_dialog().unwrap().unwrap()["saved"], false);
app.pump_owned_picks(&ctx, &mut desk);
assert!(app.closing.as_ref().is_some_and(|c| c.window == peer), "the deferred close goes on through its unsaved prompt");
assert!(app.session.document_dirty(first_doc) && app.session.document_dirty(peer_doc));
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn no_more_than_two_system_dialogs_launch_in_one_pass() {
let (mut app, _, first, _, peer, _, mut desk, ctx) = attached_drafts();
script_panels(vec![craft::dialogs::Answer::Cancelled]);
desk.pending = true;
begin_trial_save(&mut app, first, peer);
app.open_dialog();
app.run("file.new", json!({})).unwrap();
let third = app.windows.shown();
let vc = egui::ViewportId::from_hash_of("third");
app.attach_window_for_test(third, vc);
desk.lookup.set(vc, Some(5));
app.open_dialog();
assert_eq!(app.owned_picks.jobs.len(), 3);
app.pump_owned_picks(&ctx, &mut desk);
assert_eq!(desk.parented.len(), super::MAX_NATIVE_OPERATIONS, "three picks in one pass launch two dialogs");
assert_eq!(desk.leases(vc), 0, "the third waits, holding nothing");
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_given_up_system_dialog_still_holds_its_windows_close() {
let (mut app, _, _, _, peer, peer_doc, mut desk, ctx) = attached_drafts();
script_panels(vec![craft::dialogs::Answer::Cancelled]);
desk.pending = true;
app.save_as_dialog();
app.pump_owned_picks(&ctx, &mut desk);
// `ui.fileBrowser` gives the system dialog up: it is not cancelled, and its window stays leased.
let _ = app.give_up_file_dialog();
assert!(app.owned_picks.jobs.is_empty());
assert_eq!(app.owned_picks.retired.len(), 1);
assert_eq!(desk.leases(vb()), 1);
app.close_window(peer);
assert!(app.closing.is_none() && app.window_shows_document(peer, peer_doc), "its window's close waits for it");
desk.pending = false;
app.pump_owned_picks(&ctx, &mut desk);
assert!(app.owned_picks.retired.is_empty());
assert_eq!(desk.leases(vb()), 0);
assert!(app.closing.as_ref().is_some_and(|c| c.window == peer), "the close goes on once the dialog has finished");
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn quiescing_admits_and_launches_nothing_and_drains_launched_dialogs() {
let (mut app, _, first, _, peer, _, mut desk, ctx) = attached_drafts();
script_panels(vec![craft::dialogs::Answer::Cancelled]);
desk.pending = true;
desk.lookup.set(va(), None);
assert!(app.enter_window(first));
app.open_dialog();
app.show_window(peer);
app.save_as_dialog();
app.pump_owned_picks(&ctx, &mut desk);
assert_eq!(desk.parented, vec![(vb(), nz(2))]);
app.quiesce_native_file_panels();
assert!(app.owned_picks.jobs.is_empty(), "the waiting pick is dropped unpumped");
assert!(app.native_file_panels_open(), "the launched dialog still uses its window");
app.open_dialog();
assert!(app.owned_picks.jobs.is_empty(), "nothing is admitted while exiting");
desk.lookup.set(va(), Some(1));
app.pump_owned_picks(&ctx, &mut desk);
assert_eq!(desk.parented.len(), 1, "a final pass launches nothing");
assert!(!app.window_dialog_host_mut(first).unwrap().is_open::<FileChooser>());
desk.pending = false;
app.pump_owned_picks(&ctx, &mut desk);
assert!(!app.native_file_panels_open(), "the drain ends once the dialog has finished");
assert_eq!(desk.leases(vb()), 0);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn the_updaters_quit_waits_for_a_pending_system_dialog_without_prompting() {
let (mut app, _, _, _, _, _, mut desk, ctx) = attached_drafts();
script_panels(vec![craft::dialogs::Answer::Cancelled]);
desk.pending = true;
app.save_as_dialog();
app.pump_owned_picks(&ctx, &mut desk);
assert_eq!(app.ask_before_quit(), json!({"quit": false, "deferred": true}));
assert!(app.closing.is_none() && !app.quit_requested);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn quiescing_leaves_no_chooser_showing_for_a_system_dialogs_fallback() {
let (mut app, _, _, _, peer, _, mut desk, ctx) = attached_drafts();
script_panels(vec![craft::dialogs::Answer::Unavailable("no file chooser portal".into())]);
app.save_as_dialog();
app.pump_owned_picks(&ctx, &mut desk);
assert!(app.window_dialog_host_mut(peer).unwrap().is_open::<FileChooser>(), "the fallback shows on the owner");
app.quiesce_native_file_panels();
assert!(!app.window_dialog_host_mut(peer).unwrap().is_open::<FileChooser>(), "no chooser is left with nothing to answer it");
app.pump_owned_picks(&ctx, &mut desk);
assert!(!app.native_file_panels_open(), "its retired pick settles on the cleanup host");
assert_eq!(desk.leases(vb()), 0);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_waiting_quit_launches_no_queued_dialog_but_its_own_save_as() {
let (mut app, _, first, _, peer, _, mut desk, ctx) = attached_drafts();
script_panels(vec![craft::dialogs::Answer::Cancelled]);
desk.pending = true;
assert!(app.enter_window(first));
app.save_as_dialog();
app.show_window(peer);
app.open_dialog();
app.run("file.new", json!({})).unwrap();
let third = app.windows.shown();
let vc = egui::ViewportId::from_hash_of("third");
app.attach_window_for_test(third, vc);
desk.lookup.set(vc, Some(5));
app.open_dialog();
app.pump_owned_picks(&ctx, &mut desk);
assert_eq!(desk.parented.len(), 2, "two open, the third queued");
assert!(!app.quit(), "quit waits for the two open dialogs");
desk.pending = false;
app.pump_owned_picks(&ctx, &mut desk);
assert!(!app.native_file_panels_open(), "both dialogs have answered");
assert_eq!(desk.parented.len(), 2, "the queued third does not launch while the quit waits");
while app.poll_file_dialog().is_some() {}
app.pump_owned_picks(&ctx, &mut desk);
assert!(app.closing.is_some(), "the quit goes on, asking about the drafts");
assert_eq!(desk.parented.len(), 2, "still nothing new while the quit asks");
assert_eq!(desk.leases(vc), 0);
// Save in the quit's prompt asks where: that Save As opens, on the prompt's own window.
let prompt_window = app.closing.as_ref().unwrap().window;
assert_eq!(app.run("ui.saveChanges", json!({"answer": "save"})).unwrap()["pending"], "saveAs");
app.pump_owned_picks(&ctx, &mut desk);
assert_eq!(desk.parented.len(), 3);
let expected = if prompt_window == first { va() } else { vb() };
assert_eq!(desk.parented.last().map(|p| p.0), Some(expected));
assert_eq!(desk.leases(vc), 0, "the queued third is still not launched");
}
/// Three windows with their own clean documents and live native attachments; the third is drawn.
/// If `third_untitled` is set, the third is still a new blank document awaiting its first edit.
#[cfg(not(target_arch = "wasm32"))]
fn three_attached_windows(third_untitled: bool) -> (WordApp, [u64; 3], [egui::ViewportId; 3], Desk, egui::Context) {
let (mut app, _) = async_app();
app.enable_windowless_trial(true);
let dir = scratch("windowless-three-windows");
let mut windows = Vec::new();
for n in 0..3 {
if n > 0 {
app.run("file.new", json!({})).unwrap();
}
if n != 2 || !third_untitled {
app.run("text.insert", json!({"text": format!("Saved document {n}")})).unwrap();
app.run("file.save", json!({"path": dir.join(format!("saved-{n}.docx"))})).unwrap();
}
assert!(!app.session.document_dirty(app.session.document_id()));
windows.push(app.windows.shown());
}
let [one, two, three] = [windows[0], windows[1], windows[2]];
assert!(one != two && two != three && one != three);
let (desk, ctx) = connect_desk(&mut app);
let viewports = [va(), vb(), egui::ViewportId::from_hash_of("third")];
for (n, (window, viewport)) in [one, two, three].into_iter().zip(viewports).enumerate() {
app.attach_window_for_test(window, viewport);
desk.lookup.set(viewport, Some(n as u64 + 1));
}
(app, [one, two, three], viewports, desk, ctx)
}
/// Each window asks to open a file; two dialogs launch and the third queues; quit waits; both answer.
#[cfg(not(target_arch = "wasm32"))]
fn quit_after_two_dialogs_with_a_third_queued(app: &mut WordApp, windows: [u64; 3], desk: &mut Desk, ctx: &egui::Context) {
script_panels(vec![craft::dialogs::Answer::Cancelled]);
desk.pending = true;
for window in windows {
assert!(app.enter_window(window));
app.open_dialog();
}
app.pump_owned_picks(ctx, desk);
assert_eq!(desk.parented.len(), 2);
assert!(!app.quit());
desk.pending = false;
app.pump_owned_picks(ctx, desk);
while app.poll_file_dialog().is_some() {}
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_clean_quit_replayed_in_a_pump_launches_nothing_after_it() {
let (mut app, windows, viewports, mut desk, ctx) = three_attached_windows(false);
quit_after_two_dialogs_with_a_third_queued(&mut app, windows, &mut desk, &ctx);
app.pump_owned_picks(&ctx, &mut desk);
assert!(app.quit_requested, "nothing unsaved: the replayed quit is decided in this pump");
assert_eq!(desk.parented.len(), 2, "the queued third does not launch after it");
assert_eq!(desk.leases(viewports[2]), 0);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn the_quit_prompts_save_as_takes_the_place_of_its_windows_queued_pick() {
let (mut app, windows, viewports, mut desk, ctx) = three_attached_windows(true);
assert!(app.enter_window(windows[2]));
assert!(app.session.path.is_none(), "the quit guard's Save must use Save As");
app.run("text.insert", json!({"text": "Third unsaved draft"})).unwrap();
let third_doc = app.session.document_id();
quit_after_two_dialogs_with_a_third_queued(&mut app, windows, &mut desk, &ctx);
app.pump_owned_picks(&ctx, &mut desk);
assert!(app.closing.as_ref().is_some_and(|c| c.window == windows[2] && c.document == third_doc), "the third window owns the quit's prompt");
assert_eq!(desk.parented.len(), 2);
assert_eq!(app.run("ui.saveChanges", json!({"answer": "save"})).unwrap()["pending"], "saveAs");
assert_eq!(app.owned_picks.jobs.len(), 1, "the queued Open gave way to the prompt's Save As");
assert!(matches!(app.owned_picks.jobs[0].after, AfterPick::SaveAs { after: AfterSave::Closing, .. }));
app.pump_owned_picks(&ctx, &mut desk);
assert_eq!(desk.parented.last(), Some(&(viewports[2], nz(3))), "the Save As opens on the prompt's window");
assert!(app.closing.is_some(), "the guard still waits for that Save As");
}
+86
View File
@@ -636,4 +636,90 @@ mod tests {
});
assert!(!shapes.is_empty(), "{KEY} icon must paint");
}
/// #7450: the Dictate microphone icon parses cleanly on a `0 0 20 20` viewBox, keeps a
/// rounded capsule (`rx >= width / 2`) clear of the U-stand cradle, and renders at 16–22 pt.
#[test]
fn dictate_icon_geometry_and_rendering() {
use craft::theme::{Contrast, Mode};
use craft::ui::testing::{Frames, style};
let (_, bytes) = WORDCRAFT_ICONS.icons.iter().find(|(name, _)| *name == "dictate").expect("dictate is registered");
let svg = std::str::from_utf8(bytes).expect("an SVG document is text");
let tree = craft::ui::primitives::svg_tree::parse(bytes).expect("dictate.svg must parse as a valid SVG document");
let size = tree.size();
assert_eq!(size.width(), 20.0, "icon viewBox width must be 20");
assert_eq!(size.height(), 20.0, "icon viewBox height must be 20");
fn attr_str<'a>(tag: &'a str, name: &str) -> &'a str {
let elem = tag.split('>').next().unwrap_or(tag);
let needle = format!("{name}=\"");
let start = elem
.match_indices(&needle)
.find(|&(idx, _)| idx == 0 || elem.as_bytes()[idx - 1].is_ascii_whitespace())
.map(|(idx, _)| idx + needle.len())
.unwrap_or_else(|| panic!("missing {name} on {elem}"));
&elem[start..elem[start..].find('"').map_or(elem.len(), |i| start + i)]
}
let attr = |tag: &str, name: &str| -> f32 {
let val = attr_str(tag, name);
val.parse::<f32>().unwrap_or_else(|_| panic!("non-numeric {name}: {val}"))
};
let root = svg.split("<svg").nth(1).expect("dictate.svg must contain a root <svg> element");
assert_eq!(attr_str(root, "viewBox"), "0 0 20 20", "root SVG viewBox must be 0 0 20 20");
let rect = svg.split("<rect").nth(1).expect("dictate.svg must contain a <rect> capsule");
let cap_x = attr(rect, "x");
let cap_y = attr(rect, "y");
let width = attr(rect, "width");
let height = attr(rect, "height");
let rx = attr(rect, "rx");
let cap_stroke = attr(rect, "stroke-width");
let cradle = svg.split("<path").nth(1).expect("dictate.svg must contain a cradle <path>");
let cradle_stroke = attr(cradle, "stroke-width");
let half_strokes = (cap_stroke + cradle_stroke) / 2.0;
assert!(rx >= width / 2.0, "capsule corner radius ({rx}) must be at least half the width ({width})");
assert!(cap_y + height < 15.0, "capsule bottom ({}) must stay clear of the cradle bottom (15.0)", cap_y + height);
assert!(cap_x > 5.0 && cap_x + width < 15.0, "capsule x-span ({}..{}) must stay inside the cradle arms (5..15)", cap_x, cap_x + width);
fn dist_point_to_seg(p: (f32, f32), a: (f32, f32), b: (f32, f32)) -> f32 {
let (vx, vy) = (b.0 - a.0, b.1 - a.1);
let len_sq = vx * vx + vy * vy;
let t = if len_sq > 0.0 { (((p.0 - a.0) * vx + (p.1 - a.1) * vy) / len_sq).clamp(0.0, 1.0) } else { 0.0 };
let (dx, dy) = (p.0 - (a.0 + t * vx), p.1 - (a.1 + t * vy));
(dx * dx + dy * dy).sqrt()
}
let cradle_segs = [((5.0_f32, 9.5_f32), (5.0, 11.0)), ((5.0, 11.0), (10.0, 15.0)), ((10.0, 15.0), (15.0, 11.0)), ((15.0, 11.0), (15.0, 9.5))];
let mut cap_points = vec![(cap_x, 9.5_f32), (cap_x + width, 9.5_f32), (cap_x + width / 2.0, cap_y + height)];
let (arc_cx, arc_cy, arc_r) = (cap_x + width / 2.0, cap_y + height - rx, rx);
for step in 0..=8 {
let angle = std::f32::consts::PI * (step as f32) / 8.0;
cap_points.push((arc_cx - arc_r * angle.cos(), arc_cy + arc_r * angle.sin()));
}
let min_clearance =
cap_points.iter().flat_map(|&p| cradle_segs.iter().map(move |&(a, b)| dist_point_to_seg(p, a, b))).fold(f32::INFINITY, f32::min);
assert!(min_clearance > half_strokes, "capsule outline clearance ({min_clearance:.2}) must exceed combined half-strokes ({half_strokes:.2})");
register();
let tokens = style::tokens(Mode::Light, Contrast::Standard);
let mut frames = Frames::new();
for pt in [16.0_f32, 19.0, 20.0, 22.0] {
let target = Rect::from_min_size(Pos2::ZERO, egui::vec2(pt, pt));
let icon = IconSpec::svg(IconId::new("dictate"));
let (shapes, _) = style::paint_frame(&mut frames, &tokens, craft::i18n::Direction::Ltr, craft::ui::style::Ink::OnPanel, |draw| {
draw.icon(target, &icon)
});
assert!(!shapes.is_empty(), "dictate icon must paint at {pt} pt");
let bounds = shapes.iter().map(|s| s.visual_bounding_rect()).fold(Rect::NOTHING, |acc, r| acc.union(r));
assert!(bounds.is_positive(), "dictate icon must have positive rendered bounds at {pt} pt, got {bounds:?}");
assert!(target.expand(1.0).contains_rect(bounds), "dictate icon at {pt} pt overflowed target {target:?}: {bounds:?}");
assert!(
bounds.width() >= pt * 0.5 && bounds.height() >= pt * 0.5 && bounds.width() <= 22.5 && bounds.height() <= 22.5,
"dictate icon rendered size at {pt} pt out of 16-22 pt bounds: {bounds:?}"
);
}
}
}
+1 -1
View File
@@ -11,7 +11,7 @@ mod canvas;
mod ime;
mod shortcuts;
pub(crate) use canvas::{page_input, window_cancel};
pub(crate) use canvas::{page_input, tick_paste_wait, window_cancel};
pub(crate) use ime::report_editor;
#[cfg(test)]
use ime::{ImeProof, MAX_IME_COMMIT_BYTES, MAX_IME_PREEDIT_BYTES, classify_ime_proof};
+65
View File
@@ -75,6 +75,13 @@ pub fn page_input(app: &mut WordApp, inputs: &[EditorInput], pass: &ToolPass, ct
if stale_composition(app, e, &mut batch) {
continue;
}
if ignored_paste(app, ctx, e) {
continue;
}
if is_key_input(e) || matches!(e, EditorInput::Text(_)) {
app.canvas.ignore_next_paste = false;
app.canvas.paste_wait_since = None;
}
if is_key_input(e) {
app.canvas.ime_join_text = None;
// A key between a deletion and its text means that text is fresh input, not the
@@ -105,6 +112,64 @@ pub fn page_input(app: &mut WordApp, inputs: &[EditorInput], pass: &ToolPass, ct
}
}
/// How long the browser paste event paired with Mod+Shift+V is waited for (#5616).
const PASTE_WAIT: f64 = 1.0;
/// Ends the wait for the browser paste event paired with Mod+Shift+V on a pointer press,
/// focus change, or after `PASTE_WAIT` without one (#5616). Key and typing order against a
/// queued paste is handled in `page_input` (after `craft` extracts `Event::Paste` into
/// `EditorInput::Edit(EditCommand::Paste)`) and non-paste key commands clear it in `run_fired`.
pub(crate) fn tick_paste_wait(app: &mut WordApp, ctx: &egui::Context) {
if !app.canvas.ignore_next_paste {
app.canvas.paste_wait_since = None;
return;
}
let (now, clear) = ctx.input(|i| {
let clear = i.events.iter().any(|e| matches!(e, egui::Event::PointerButton { pressed: true, .. } | egui::Event::WindowFocused(_)));
(i.time, clear)
});
if clear || app.canvas.paste_wait_since.is_some_and(|t| now - t > PASTE_WAIT) {
app.canvas.ignore_next_paste = false;
app.canvas.paste_wait_since = None;
}
}
fn mod_shift_v_pressed_this_frame(ctx: &egui::Context) -> bool {
let mac = craft::ui::runtime::windows::os_of(ctx) == craft::host::target::Os::Mac;
let chord_pressed = ctx.input(|i| {
i.events.iter().any(|ev| {
matches!(ev, egui::Event::Key { key: Key::V, pressed: true, modifiers, .. } if modifiers.command && modifiers.shift && !modifiers.alt && (!mac || !modifiers.ctrl))
})
});
if !chord_pressed {
return false;
}
craft::keymap::Chord::parse("Mod+Shift+V").ok().is_some_and(|chord| {
craft::ui::runtime::commands::holder(ctx, &chord) == Some(craft::ui::runtime::commands::CommandRef::new("edit.pasteFormat"))
})
}
/// The browser's paste event that follows a Mod+Shift+V that pasted formatting is the same
/// keystroke: ignored before an equation or document paste can take it (#5616).
fn ignored_paste(app: &mut WordApp, ctx: &egui::Context, e: &EditorInput) -> bool {
if !matches!(e, EditorInput::Edit(EditCommand::Paste)) {
return false;
}
if std::mem::take(&mut app.canvas.ignore_next_paste) {
app.canvas.paste_wait_since = None;
return true;
}
if app.canvas.paste_event_follows_chord
&& !app.canvas.paste_event_consumed_same_frame
&& (app.session.painter.is_some() || app.session.copied_format.is_some())
&& mod_shift_v_pressed_this_frame(ctx)
{
app.canvas.paste_event_consumed_same_frame = true;
return true;
}
false
}
/// Whether the input is a key's, not text or an input method's.
fn is_key_input(e: &EditorInput) -> bool {
matches!(
+70
View File
@@ -349,6 +349,41 @@ fn an_unrelated_keys_modifiers_do_not_steer_a_later_paste() {
}
}
/// #5616: the browser paste event after a formatting paste is dropped before an open equation
/// can type it (while the same paste without Mod+Shift+V first reaches the equation).
#[test]
fn the_ignored_paste_event_never_reaches_an_open_equation() {
// Control: without Mod+Shift+V first, the paste reaches the open equation.
let mut control = app_harness(copied_bold_app());
control.state_mut().canvas.paste_event_follows_chord = true;
offer(&control, vec![ClipItem::Text("zzz".into())]);
run(&mut control, "insert.equation", json!({"linear": "abc"}));
mods_frame(&mut control, mod_held(), vec![egui::Event::Paste("zzz".into())]);
assert_eq!(linear(&mut control), "abczzz", "control: Paste reaches an open equation without Mod+Shift+V first");
// Same-frame and delayed browser paste after Mod+Shift+V (Paste Formatting) are both ignored.
for same_frame in [false, true] {
let mut h = app_harness(copied_bold_app());
h.state_mut().canvas.paste_event_follows_chord = true;
offer(&h, vec![ClipItem::Text("zzz".into())]);
run(&mut h, "insert.equation", json!({"linear": "abc"}));
let chord = Modifiers { shift: true, ..mod_held() };
let before = h.state().session.math.clone();
assert!(before.is_some());
if same_frame {
batch_frame(&mut h, vec![key_event(Key::V, true, chord), egui::Event::Paste("zzz".into())]);
crate::test_harness::frame(&mut h);
} else {
mods_frame(&mut h, chord, vec![key_event(Key::V, true, chord)]);
mods_frame(&mut h, Modifiers::NONE, vec![key_event(Key::V, false, Modifiers::NONE)]);
mods_frame(&mut h, mod_held(), vec![egui::Event::Paste("zzz".into())]);
}
assert_eq!(h.state().session.math, before, "same_frame={same_frame}: Paste Formatting keeps the equation open");
assert_eq!(linear(&mut h), "abc", "same_frame={same_frame}: the ignored paste typed nothing into the equation");
assert_eq!(body(h.state()), "source abc", "same_frame={same_frame}: the ignored paste did not paste into the body");
}
}
/// Paste Formatting on a chord the user bound pastes the copied formatting once.
#[test]
fn paste_formatting_on_another_key_pastes_the_copied_formatting() {
@@ -362,6 +397,41 @@ fn paste_formatting_on_another_key_pastes_the_copied_formatting() {
assert!(is_bold(&mut h), "the formatting was pasted onto the selection");
}
/// F4 bound alongside Mod+Shift+V neither falls back to plain-text paste nor arms browser paste
/// suppression when its modifiers are released.
#[test]
fn paste_formatting_on_f4_alongside_mod_shift_v_leaves_later_paste_alone() {
let mut app = copied_bold_app();
app.session.keymap_mut().insert(craft::keymap::CommandRef::new("edit.pasteFormat").key(), vec!["Mod+Shift+V".to_string(), "F4".to_string()]);
let mut h = app_harness(app);
h.state_mut().canvas.paste_event_follows_chord = true;
mods_frame(&mut h, Modifiers::NONE, vec![key_event(Key::F4, true, Modifiers::NONE)]);
mods_frame(&mut h, Modifiers::NONE, vec![key_event(Key::F4, false, Modifiers::NONE)]);
assert!(is_bold(&mut h), "F4 pasted formatting");
assert!(!h.state().canvas.ignore_next_paste, "F4 does not arm browser paste suppression even while Mod+Shift+V is bound");
offer(&h, vec![ClipItem::Text("!".into())]);
batch_frame(&mut h, vec![egui::Event::Paste("!".into())]);
crate::test_harness::frame(&mut h);
assert_eq!(body(h.state()), "source !", "a standalone paste right after F4 is not swallowed");
}
/// A delayed browser paste followed immediately by typing in the same frame after Mod+Shift+V
/// still suppresses the paired paste before typing runs.
#[test]
fn delayed_ignored_paste_followed_by_typing_in_same_frame_drops_only_paste() {
let mut h = app_harness(copied_bold_app());
h.state_mut().canvas.paste_event_follows_chord = true;
offer(&h, vec![ClipItem::Text("zzz".into())]);
let chord = Modifiers { shift: true, ..mod_held() };
mods_frame(&mut h, chord, vec![key_event(Key::V, true, chord)]);
mods_frame(&mut h, Modifiers::NONE, vec![key_event(Key::V, false, Modifiers::NONE)]);
assert!(h.state().canvas.ignore_next_paste);
batch_frame(&mut h, vec![egui::Event::Paste("zzz".into()), key_event(Key::A, true, Modifiers::NONE), egui::Event::Text("a".into())]);
crate::test_harness::frame(&mut h);
assert_eq!(body(h.state()), "source a", "paired paste dropped, subsequent typing kept");
}
/// A press or release of `key` with `modifiers`.
fn key_event(key: Key, pressed: bool, modifiers: Modifiers) -> egui::Event {
egui::Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers }
+10
View File
@@ -515,6 +515,16 @@ pub struct WordApp {
pub(crate) closing: Option<app::Closing>,
/// The file dialog the host is showing, and what its answer is for ([`file_dialogs`]).
file_dialog: Option<file_dialogs::PendingDialog>,
/// Remember the folder for each purpose served by the isolated windowless chooser.
#[cfg(not(target_arch = "wasm32"))]
windowless_save_folders: std::collections::HashMap<String, std::path::PathBuf>,
/// Windowless trial: the file picks bound to the window that asked, and the cleanup of a cancelled one. App-wide,
/// so focusing another window never moves it ([`file_dialogs`]).
#[cfg(not(target_arch = "wasm32"))]
owned_picks: file_dialogs::OwnedPicks,
/// The desktop's read-only view of document viewports' native windows; `None` where it has none.
#[cfg(not(target_arch = "wasm32"))]
native_windows: Option<std::sync::Arc<dyn file_dialogs::NativeWindowLookup + Send + Sync>>,
/// Whether the in-app file chooser is forced in place of the system one.
pub(crate) fallback_chooser: bool,
/// File › Info: the property field being typed in and the document revision after its last
+7 -1
View File
@@ -71,7 +71,11 @@ pub(super) fn insert(row: &mut RibbonRow<'_>, app: &mut WordApp) {
|ui, cx| {
let out = TableSizePicker::new(crate::tl!("Insert Table")).show(ui);
if let Some((rows, cols)) = out.picked {
let _ = app.run("insert.table", json!({"rows": rows, "cols": cols}));
// The new table's first cell has the caret: the page takes the keyboard so typing goes into it,
// as after a WordArt style pick. The closing menu would hand focus back to the Table button.
if app.run("insert.table", json!({"rows": rows, "cols": cols})).is_ok() {
app.canvas.focus_page(ui.ctx());
}
app.canvas.table_preview = None;
cx.request_close();
} else {
@@ -378,6 +382,8 @@ fn symbol_grid(ui: &mut Ui, cx: &mut BodyCx<'_>, app: &mut WordApp) {
let params = if font.is_empty() { json!({"char": c}) } else { json!({"char": c, "font": font}) };
if app.run("insert.symbol", params).is_ok() {
crate::dialogs_insert::remember_symbol(app, c, font);
// The page takes the keyboard so typing goes on after the symbol, as after a pick on the Table grid.
app.canvas.focus_page(ui.ctx());
cx.request_close();
}
}
+60
View File
@@ -1103,6 +1103,28 @@ fn bullets_dropdown_renders_compact_bullet_tiles() {
assert!((rect.width() - rect.height()).abs() <= 2.0, "bullet tile should be square: {}x{}", rect.width(), rect.height());
}
/// The Bullet Library and the Symbol drop-down draw their symbols with the interface's own faces, under kittest's
/// strict missing-glyph policy: neither the optional craft-fonts faces nor installed fonts may supply them.
#[test]
fn the_bullet_and_symbol_menus_draw_their_symbols_without_optional_or_installed_fonts() {
use egui::accesskit::Role;
for (tab, menu, symbols) in [("Home", "Bullets options", ["○", "▪", "◆", "✓"]), ("Insert", "Symbol", ["✓", "★", "♥", "©"])] {
let app = WordApp::new(Session::new(wordcraft_doc::Document::from_text("Sample")), crate::Services::default());
let mut h = tab_harness(app, tab);
crate::app::fonts::ui_fonts_with_optional_faces(crate::i18n::Lang::EN, &[])
.system_fonts(craft::ui::fonts::SystemFonts::Off)
.stack()
.install(&h.ctx);
// Bullets is a split button whose arrow node ("Bullets options") opens the menu; Symbol has one node.
h.query_all(By::new().role(Role::Button).label(menu)).last().expect("the menu's button").click();
crate::test_harness::frames(&mut h, 3);
for symbol in symbols {
assert!(h.query_all_by_label(symbol).next().is_some(), "{menu} shows {symbol}");
}
}
}
/// #7310: unimplemented stub ribbon buttons (Dictate, Ink to Math, Translate, Block Authors)
/// resolve disabled in the ribbon UI and are known to the command catalog without warnings.
#[test]
@@ -1128,6 +1150,44 @@ fn unimplemented_stub_ribbon_buttons_are_disabled() {
.find(|n| n.accesskit_node().label().is_some_and(|l| l.split_whitespace().collect::<Vec<_>>().join(" ") == expected_label))
.unwrap_or_else(|| panic!("{tab}: ribbon button '{expected_label}' should exist"));
assert!(button.accesskit_node().is_disabled(), "{tab}: stub button {:?} ({id}) must be disabled", button.accesskit_node().label());
if expected_label == "Dictate" {
fn push_icon_rects(shape: &egui::Shape, clip: egui::Rect, btn_rect: egui::Rect, out: &mut Vec<egui::Rect>) {
match shape {
egui::Shape::Vec(items) => {
for item in items {
push_icon_rects(item, clip, btn_rect, out);
}
}
egui::Shape::Text(_) | egui::Shape::Noop => {}
other => {
let r = other.visual_bounding_rect().intersect(clip);
if r.is_positive()
&& btn_rect.expand(1.0).contains_rect(r)
&& r.width() < btn_rect.width() * 0.9
&& r.height() < btn_rect.height() * 0.9
{
out.push(r);
}
}
}
}
let btn_rect = button.rect();
let mut icon_rects = Vec::new();
for c in &h.output().shapes {
push_icon_rects(&c.shape, c.clip_rect, btn_rect, &mut icon_rects);
}
let icon_rect = icon_rects
.into_iter()
.reduce(|a, b| a.union(b))
.unwrap_or_else(|| panic!("Dictate button ({btn_rect:?}) must paint a bounded icon shape"));
assert!(
icon_rect.width() >= 16.0 && icon_rect.height() >= 16.0,
"Dictate ribbon icon must render at >= 16 pt, got {}x{} ({icon_rect:?})",
icon_rect.width(),
icon_rect.height()
);
assert!((icon_rect.width() - icon_rect.height()).abs() <= 2.0, "Dictate icon should be square: {icon_rect:?}");
}
}
}
+20
View File
@@ -2648,6 +2648,26 @@ fn host_save_as_a_copy_format_is_not_save_as() {
assert_eq!(a.session.path.as_deref(), Some(std::path::Path::new("report.docx")));
}
/// A copy named like the opened file can't go to the host page, whose Save would overwrite the
/// opened file with it (#6131 review). The bridge strips any directory from `path`, so a path
/// whose file name matches the opened document is refused too.
#[test]
fn host_copy_with_the_opened_name_is_refused() {
let (mut a, got) = host_app(false);
host_open(&mut a, "report.docx");
for path in ["report.docx", "./report.docx", "/tmp/report.docx"] {
let e = a.execute("file.saveAs", json!({"path": path, "copy": true})).unwrap_err();
assert!(e.contains("same name"), "{path}: {e}");
}
assert!(got.borrow().is_empty(), "nothing reached the host");
assert!(a.session.dirty);
a.execute("file.saveAs", json!({"path": "other.docx", "copy": true})).unwrap();
a.settle_saves();
assert_eq!(got.borrow().first().map(|(n, s, _)| (n.as_str(), *s)), Some(("other.docx", false)));
assert_eq!(a.session.path.as_deref(), Some(std::path::Path::new("report.docx")));
assert!(a.session.dirty);
}
/// The page not getting the file is a failed save: the document keeps its changes.
#[test]
fn a_host_save_that_fails_leaves_the_document_unsaved() {
+36
View File
@@ -160,3 +160,39 @@ fn citations_provider_menu_has_zotero_checked() {
let checked = items.first().map(|n| n.accesskit_node().toggled().is_some() || n.accesskit_node().is_selected().is_some());
assert_eq!(checked, Some(true), "and it is marked as the chosen one");
}
/// A size picked on Insert › Table's grid, with the pointer or the keys, hands the keyboard to the new table, so
/// what is typed next goes into its first cell. The menu's close gave focus back to the Table button, and the typing
/// was lost.
#[test]
fn typing_after_a_table_grid_pick_goes_into_the_new_table() {
use egui::accesskit::Role;
for by_keys in [false, true] {
let how = if by_keys { "keys" } else { "pointer" };
let mut a = app();
a.ui.mini_toolbar = false;
a.run("ui.tab", json!({"tab": "Insert"})).unwrap();
let mut h = crate::test_harness::builder().with_size(egui::vec2(1920.0, 900.0)).build_eframe(|_| a);
h.run_steps(2);
if by_keys {
// Enter on the focused Table button opens the grid on 1 × 1; the arrows move to 2 × 2 and Enter picks it.
h.get_by_role_and_label(Role::Button, "Table").focus();
h.run_steps(3);
for key in [egui::Key::Enter, egui::Key::ArrowRight, egui::Key::ArrowDown, egui::Key::Enter] {
h.key_press(key);
h.run_steps(3);
}
} else {
h.get_by_role_and_label(Role::Button, "Table").click();
h.run_steps(3);
h.get_by_role_and_label(Role::GridCell, "2x2 Table").click();
h.run_steps(3);
}
assert!(h.state().session.sel.focus.path.cell().is_some(), "{how}: the caret is in the new table");
assert!(h.state().canvas.focused(&h.ctx), "{how}: the page has the keyboard after the pick");
h.event(egui::Event::Text("Copper".into()));
h.run_steps(2);
let s = &h.state().session;
assert_eq!(s.doc.para_at(&s.sel.focus).unwrap().text, "Copper", "{how}: the typing went into the first cell");
}
}
+6
View File
@@ -179,6 +179,12 @@ impl WordApp {
ctx: _,
read_aloud_error: _,
saves_in_flight: _,
#[cfg(not(target_arch = "wasm32"))]
windowless_save_folders: _,
#[cfg(not(target_arch = "wasm32"))]
owned_picks: _,
#[cfg(not(target_arch = "wasm32"))]
native_windows: _,
recovery_seen: _,
no_document: _,
windows: _,
+338 -39
View File
@@ -1,6 +1,6 @@
//! One native window per open document. The app's windows are a [`craft_window::WindowList`]: one
//! entry is the root OS window (drawn by the app's own shell), every other entry is shown as a
//! [`DocumentWindow`] in an OS window of its own. Each draws the whole interface (title bar,
//! entry normally uses the root OS window. Other entries (or all entries in the windowless trial)
//! use [`DocumentWindow`] in OS windows of their own. Each draws the whole interface (title bar,
//! ribbon, page, status bar, dialogs) for its own document. [`WordApp`]'s fields hold the drawn
//! window's state ([`crate::window_ui`]); the other windows keep theirs in their [`Window`].
//! Between frames the fields hold the active window's (the one focused last), so the control
@@ -71,6 +71,25 @@ fn window_container_id(id: WindowId) -> egui::Id {
egui::Id::unique(("wordcraft.window", id.get()))
}
/// The native surface of a window in the windowless trial.
#[derive(Clone, Copy, PartialEq, Eq)]
enum NativeMount {
Pending,
Attached,
Rejected,
}
/// Where an owned file pick's window stands ([`crate::file_dialogs`]).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum OwnerSurface {
/// The window closed, shows another document, its document closed, or its surface was rejected.
Gone,
/// Live, its native surface not attached yet.
Pending,
/// Attached: the viewport its host names for it (if any) and the mount attempt that attached.
Attached { viewport: Option<ViewportId>, attempt: u64 },
}
/// An open window.
pub(crate) struct Window {
/// The document it shows.
@@ -88,12 +107,34 @@ pub(crate) struct Window {
raise: bool,
/// Its OS window opens cascaded from the window before it; used once, when it first shows.
place: bool,
mount: NativeMount,
/// A retry uses a fresh declaration: eframe blocks a rejected id until it has seen a full pass without it.
mount_attempt: u64,
/// Tests: the viewport an attached window reports without a window host.
#[cfg(test)]
test_viewport: Option<ViewportId>,
}
impl Window {
/// A window on `doc`; `place` cascades its OS window from the others when it first shows.
fn new(doc: u64, ui: Option<Box<WindowUi>>, view: Option<WindowView>, place: bool) -> Window {
Window { doc, ui, requests: Vec::new(), view, raise: false, place }
Window {
doc,
ui,
requests: Vec::new(),
view,
raise: false,
place,
mount: NativeMount::Pending,
mount_attempt: 0,
#[cfg(test)]
test_viewport: None,
}
}
fn container_id(&self, id: WindowId) -> egui::Id {
let base = window_container_id(id);
if self.mount_attempt == 0 { base } else { base.with(self.mount_attempt) }
}
}
@@ -103,8 +144,9 @@ pub struct Windows {
native: bool,
/// Every window, in opening and focus order.
list: WindowList<Window>,
/// The entry the root OS window shows.
/// The entry the root OS window shows in the ordinary windowed mode.
root: WindowId,
windowless_trial: bool,
/// The window whose state is in [`WordApp`]'s fields.
shown: WindowId,
/// View › Window: Side by Side and Synchronous Scrolling (#322).
@@ -119,7 +161,21 @@ impl Windows {
pub(crate) fn new(doc: u64) -> Windows {
let mut list = WindowList::new();
let id = list.open(Window::new(doc, None, None, false));
Windows { native: cfg!(not(target_arch = "wasm32")), list, root: id, shown: id, arranged: arrange::State::default(), root_focused: false }
Windows {
native: cfg!(not(target_arch = "wasm32")),
list,
root: id,
windowless_trial: false,
shown: id,
arranged: arrange::State::default(),
root_focused: false,
}
}
/// Whether every native document is drawn in a child viewport.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn windowless_trial(&self) -> bool {
self.windowless_trial
}
/// Whether documents get native windows of their own.
@@ -151,7 +207,7 @@ impl Windows {
/// The key of the window drawn now: `main` for the root entry, else one of its own, so two
/// windows never share a placement or shell key.
pub(crate) fn window_key(&self) -> WindowKey {
if self.shown == self.root { WindowKey::main() } else { WindowKey::new(format!("window-{}", self.shown.get())) }
if !self.windowless_trial && self.shown == self.root { WindowKey::main() } else { WindowKey::new(format!("window-{}", self.shown.get())) }
}
/// The viewports whose OS window is open: the root's and every other window's.
@@ -176,9 +232,17 @@ impl Windows {
self.list.get_mut(id)
}
/// The window showing document `doc`, the most recently focused if several do.
/// The most recently focused window showing document `doc`, preferring an attached view.
fn of_doc(&self, doc: u64) -> Option<u64> {
self.list.recent().find(|&id| self.list.get(id).is_some_and(|w| w.doc == doc)).map(WindowId::get)
let mut fallback = None;
for id in self.list.recent() {
let Some(w) = self.list.get(id).filter(|w| w.doc == doc) else { continue };
if !self.windowless_trial || w.mount == NativeMount::Attached {
return Some(id.get());
}
fallback.get_or_insert(id.get());
}
fallback
}
/// The document of the window focused last before `key`'s, if any.
@@ -192,10 +256,18 @@ impl Windows {
/// The viewport window `id` draws in, while its OS window is open: the root's for the root
/// entry, else the one the window host names for the window's container.
fn viewport_of(&self, ctx: &egui::Context, id: WindowId) -> Option<ViewportId> {
if id == self.root {
if !self.windowless_trial && id == self.root {
return Some(ViewportId::ROOT);
}
WindowHost::of(ctx).viewport_of(window_container_id(id))
let window = self.list.get(id)?;
if self.windowless_trial && window.mount != NativeMount::Attached {
return None;
}
#[cfg(test)]
if let Some(viewport) = window.test_viewport {
return Some(viewport);
}
WindowHost::of(ctx).viewport_of(window.container_id(id))
}
/// [`Windows::viewport_of`] for the window with the app's key `key`.
@@ -205,25 +277,46 @@ impl Windows {
}
impl WordApp {
/// How many windows are open.
pub fn window_count(&self) -> usize {
if self.windows.native { self.windows.list.len() } else { 1 }
/// Match the private native trial's logical root. Call only at startup.
pub fn enable_windowless_trial(&mut self, enabled: bool) {
self.windows.windowless_trial = enabled && self.windows.native;
}
/// The egui viewport of the active window, the one focused last: control input,
/// `ui.screenshot` and `ui.resize` are its. The root viewport when the windows don't have
/// viewports of their own (the web app, embedded viewports) or the window has none yet.
/// How many windows are open.
pub fn window_count(&self) -> usize {
if self.windows.windowless_trial {
self.windows.list.iter().filter(|(_, w)| w.mount != NativeMount::Rejected).count()
} else if self.windows.native {
self.windows.list.len()
} else {
1
}
}
/// The egui viewport of the active window, the one focused last. Returns ROOT when there is
/// no viewport yet, or in a host without separate windows. Use `control_viewport` for effects.
pub fn active_viewport(&self) -> ViewportId {
let Some(ctx) = self.ctx.as_ref().filter(|ctx| self.windows.native && WindowHost::of(ctx).opens_windows()) else { return ViewportId::ROOT };
let id = self.windows.list.active().unwrap_or(self.windows.shown);
self.windows.viewport_of(ctx, id).unwrap_or(ViewportId::ROOT)
}
/// A target for control input and native effects. In the trial, an unregistered child cannot
/// fall back to logical ROOT: sending Close there means Quit, and other effects are discarded.
pub(crate) fn control_viewport(&self) -> Result<ViewportId, &'static str> {
let viewport = self.active_viewport();
if self.windows.windowless_trial && viewport == ViewportId::ROOT {
Err("the active document window is not ready; retry once it opens")
} else {
Ok(viewport)
}
}
/// Whether a close request for the root viewport closes only the window drawn there: true
/// while other windows are open. The root adopts another entry then, and the host keeps the
/// app running.
pub fn closes_a_window(&self) -> bool {
self.window_count() > 1 && !self.quit_requested
!self.windows.windowless_trial && self.window_count() > 1 && !self.quit_requested
}
/// Quit the app (the app menu's Quit): ask about every document with unsaved work, each in
@@ -242,6 +335,79 @@ impl WordApp {
self.windows.get(key).is_some_and(|w| w.doc == document)
}
/// Where window `key`, owning a pick for `document`, stands (windowless trial).
pub(crate) fn pick_owner_surface(&self, ctx: &egui::Context, key: u64, document: u64) -> OwnerSurface {
if !self.window_shows_document(key, document) {
return OwnerSurface::Gone;
}
let Some(w) = self.windows.get(key) else { return OwnerSurface::Gone };
match w.mount {
NativeMount::Rejected => OwnerSurface::Gone,
NativeMount::Pending => OwnerSurface::Pending,
NativeMount::Attached => OwnerSurface::Attached { viewport: self.windows.viewport(ctx, key), attempt: w.mount_attempt },
}
}
/// Whether window `key` shows open document `document` now. The drawn window's entry is updated
/// only when another window is drawn, so its document is read from the drawn state.
pub(crate) fn window_shows_document(&self, key: u64, document: u64) -> bool {
self.window_document(key) == Some(document) && self.session.is_open(document)
}
/// The document window `key` shows, read from the drawn state for the drawn window.
pub(crate) fn window_document(&self, key: u64) -> Option<u64> {
if key == self.windows.shown() { Some(self.shown_document) } else { self.windows.get(key).map(|w| w.doc) }
}
/// Clear the per-window state a pick of window `key` left pending (Change Picture's target, a
/// recipient list being chosen), in its parked state when another window is drawn.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn clear_window_pick_state(&mut self, key: u64, picture: bool, recipients: bool) {
if key == self.windows.shown() {
if picture {
self.change_picture_target = None;
}
if recipients {
self.recipient_list_pending = false;
}
} else if let Some(ui) = self.windows.get_mut(key).and_then(|w| w.ui.as_mut()) {
if picture {
ui.change_picture_target = None;
}
if recipients {
ui.recipient_list_pending = false;
}
}
}
/// The mount attempt window `key` is attached with, if it is attached.
pub(crate) fn attached_attempt(&self, key: u64) -> Option<u64> {
self.windows.get(key).filter(|w| w.mount == NativeMount::Attached).map(|w| w.mount_attempt)
}
/// Tests: window `key`'s surface attached, its host naming `viewport` for it.
#[cfg(test)]
pub(crate) fn attach_window_for_test(&mut self, key: u64, viewport: ViewportId) {
if let Some(w) = self.windows.get_mut(key) {
w.mount = NativeMount::Attached;
w.test_viewport = Some(viewport);
}
}
/// Tests: window `key`'s surface rejected and mounted again, as a retry after a failed attach does.
#[cfg(test)]
pub(crate) fn remount_window_for_test(&mut self, key: u64) {
if let Some(w) = self.windows.get_mut(key) {
w.mount = NativeMount::Rejected;
}
self.focus_window(key);
}
/// Window `key`'s dialog host, wherever its state is.
pub(crate) fn window_dialog_host(&self, key: u64) -> Option<&craft::ui::dialog::DialogHost> {
if key == self.windows.shown() { Some(&self.dialog_host) } else { self.windows.get(key)?.ui.as_ref().map(|ui| &ui.dialog_host) }
}
pub(crate) fn window_dialog_host_mut(&mut self, key: u64) -> Option<&mut craft::ui::dialog::DialogHost> {
if key == self.windows.shown() { Some(&mut self.dialog_host) } else { self.windows.get_mut(key)?.ui.as_mut().map(|ui| &mut ui.dialog_host) }
}
@@ -331,10 +497,13 @@ impl WordApp {
}
/// Close the drawn window alone: other windows show its document, which stays open as it is.
pub(crate) fn close_window_only(&mut self) -> bool {
let Some(next) = self.other_window_on_document() else { return false };
pub(crate) fn close_window_only(&mut self) -> Result<bool, String> {
let Some(next) = self.other_window_on_document() else { return Ok(false) };
if let Some(error) = self.rejected_draft_blocks_last_surface_close() {
return Err(error);
}
self.close_shown_window(next);
true
Ok(true)
}
/// The drawn window's document has closed: draw window `to` and close this one.
@@ -353,6 +522,14 @@ impl WordApp {
self.windows.list.focus(id);
if let Some(w) = self.windows.list.get_mut(id) {
w.raise = true;
if w.mount == NativeMount::Rejected {
w.mount = NativeMount::Pending;
w.mount_attempt = w.mount_attempt.wrapping_add(1);
w.place = true;
if let Some(ctx) = &self.ctx {
ctx.request_repaint();
}
}
}
}
self.settle_windows();
@@ -361,7 +538,8 @@ impl WordApp {
/// The root OS window shows an entry that is open: when its own closed, the active one moves
/// in. Each window's page state is its own, so the page keeps its place.
fn settle_windows(&mut self) {
if !self.windows.list.contains(self.windows.root)
if !self.windows.windowless_trial
&& !self.windows.list.contains(self.windows.root)
&& let Some(next) = self.windows.list.active()
{
self.windows.root = next;
@@ -436,6 +614,9 @@ impl WordApp {
/// it comes forward; else the window shows the next document. The session leaves a new blank
/// document when it was the last.
pub(crate) fn close_shown_document(&mut self) -> Result<(), String> {
if let Some(error) = self.rejected_draft_blocks_last_surface_close() {
return Err(error);
}
let doc = self.session.document_id();
let next = self.windows.next_doc(self.windows.shown());
self.session.close_document(doc).map_err(|e| e.to_string())?;
@@ -535,27 +716,32 @@ impl WordApp {
self.after_windows();
return;
}
let raise_root = self.windows.list.get_mut(self.windows.root).is_some_and(|w| std::mem::take(&mut w.raise));
if raise_root {
WindowHost::of(&ctx).act(ViewportId::ROOT, WindowAction::Focus);
if !self.windows.windowless_trial {
let raise_root = self.windows.list.get_mut(self.windows.root).is_some_and(|w| std::mem::take(&mut w.raise));
if raise_root {
WindowHost::of(&ctx).act(ViewportId::ROOT, WindowAction::Focus);
}
self.draw_entry(ui, self.windows.root.get());
// The root window gaining OS focus makes its entry the active one, as a child's `focus_gained` does.
let root_focused = WindowHost::of(&ctx).facts(ViewportId::ROOT).is_some_and(|facts| facts.focused);
if root_focused && !std::mem::replace(&mut self.windows.root_focused, root_focused) {
self.windows.list.focus(self.windows.root);
}
self.windows.root_focused = root_focused;
}
self.draw_entry(ui, self.windows.root.get());
let root = self.windows.root;
// The root window gaining OS focus makes its entry the active one, as a child's `focus_gained` does.
let root_focused = WindowHost::of(&ctx).facts(ViewportId::ROOT).is_some_and(|facts| facts.focused);
if root_focused && !std::mem::replace(&mut self.windows.root_focused, root_focused) {
self.windows.list.focus(root);
}
self.windows.root_focused = root_focused;
let menu = self.window_menu();
let step = StyleCx::with_root(&ctx, |cx| cx.tokens.size.window.cascade);
let ids: Vec<WindowId> = self.windows.list.ids().filter(|&id| id != root).collect();
let ids: Vec<WindowId> = self.windows.list.ids().filter(|&id| self.windows.windowless_trial || id != self.windows.root).collect();
let mut closes = Vec::new();
let mut rejected = Vec::new();
for id in ids {
let Some(w) = self.windows.list.get_mut(id) else { continue };
if w.mount == NativeMount::Rejected {
continue;
}
let (raise, place) = (std::mem::take(&mut w.raise), std::mem::take(&mut w.place));
let mut window = DocumentWindow::new(Self::title_in(&menu, id))
.id(window_container_id(id))
.id(w.container_id(id))
.overlay(|overlay| overlay.size_limits(SizeLimits::at_least(MIN_SIZE)));
if raise {
window = window.raise();
@@ -563,7 +749,29 @@ impl WordApp {
if place && let Some(rect) = self.cascade_from(ui, id, step) {
window = window.first_placed(rect);
}
let out = window.show(ui, |ui, cx| self.draw_window(ui, cx, id)).output;
let shown = if self.windows.windowless_trial {
match window.try_show(ui, |ui, cx| self.draw_window(ui, cx, id)) {
Ok(shown) => shown,
Err(_) => {
if let Some(w) = self.windows.list.get_mut(id) {
w.mount = NativeMount::Rejected;
rejected.push(id);
}
#[cfg(not(target_arch = "wasm32"))]
self.cancel_windowless_save_as_for_mount_failure(&ctx, id.get());
continue;
}
}
} else {
window.show(ui, |ui, cx| self.draw_window(ui, cx, id))
};
if self.windows.windowless_trial
&& shown.inner.is_some()
&& let Some(w) = self.windows.list.get_mut(id)
{
w.mount = NativeMount::Attached;
}
let out = shown.output;
if out.focus_gained {
self.windows.list.focus(id);
}
@@ -571,10 +779,84 @@ impl WordApp {
closes.push(id);
}
}
self.window_events(&closes);
self.recover_rejected_mounts(&rejected, &ctx);
self.window_events(&closes, &ctx);
self.after_windows();
}
/// Quit cannot ask about a draft while every view of it lacks a native surface.
pub(crate) fn rejected_draft_blocks_quit(&mut self) -> Option<String> {
self.report_unavailable_draft(None)
}
/// Closing a document or its view must not retire the last surface if another unsaved
/// document may still be inaccessible. The user can retry its view first.
pub(crate) fn rejected_draft_blocks_last_surface_close(&mut self) -> Option<String> {
let shown = self.windows.shown;
if !self.windows.windowless_trial
|| self.windows.list.get(shown).is_none_or(|w| w.mount != NativeMount::Attached)
|| self.windows.list.iter().any(|(id, w)| id != shown && w.mount == NativeMount::Attached)
{
return None;
}
self.report_unavailable_draft(Some(shown))
}
fn report_unavailable_draft(&mut self, without: Option<WindowId>) -> Option<String> {
if !self.windows.windowless_trial {
return None;
}
let blocked = self.windows.list.iter().any(|(_, window)| {
window.mount != NativeMount::Attached
&& (window.mount_attempt > 0 || window.mount == NativeMount::Rejected)
&& (self.document_unsaved_by_id(window.doc) || self.document_has_comment_drafts(window.doc))
&& !self.windows.list.iter().any(|(id, other)| Some(id) != without && other.doc == window.doc && other.mount == NativeMount::Attached)
});
if !blocked {
return None;
}
let message = tl!("An unsaved document's window did not open. Use View > Switch Windows to retry before closing.").to_string();
self.status_long(message.clone());
if let Some(ctx) = &self.ctx {
ctx.request_repaint_of(ViewportId::ROOT);
}
Some(message)
}
/// Stop declaring failed surfaces without closing their documents or taking down other windows.
fn recover_rejected_mounts(&mut self, rejected: &[WindowId], ctx: &egui::Context) {
if rejected.is_empty() {
return;
}
for id in rejected {
log::warn!("native document window {} could not be opened", id.get());
}
if self.closing.as_ref().is_some_and(|c| rejected.iter().any(|id| id.get() == c.window)) {
// Its dialog cannot be answered. End the close operation without deciding for the user.
self.cancel_closing();
}
let survivor = self
.windows
.list
.recent()
.find(|&id| self.windows.list.get(id).is_some_and(|w| w.mount == NativeMount::Attached && self.session.is_open(w.doc)));
if let Some(survivor) = survivor {
self.enter_window(survivor.get());
self.windows.list.focus(survivor);
self.status_long(tl!("A document window could not open. Use View > Switch Windows to try again."));
} else if self.window_count() == 0 {
// All native declarations failed. A clean startup can exit normally rather than wait
// on an invisible window; never discard work that automation has already changed.
if self.has_unsaved_documents() {
log::error!("no native document window opened; WordCraft is keeping unsaved documents open");
} else {
log::error!("no native document window opened; restart WordCraft without the windowless trial");
self.quit();
}
}
ctx.request_repaint();
}
/// After the frame's drawing: windows opened or closed meanwhile settle, and the active
/// window's state comes back.
fn after_windows(&mut self) {
@@ -614,19 +896,31 @@ impl WordApp {
if self.windows.shown() != key {
return;
}
// `PathRow` picks filed while this window draws belong to it and its document (windowless trial).
#[cfg(not(target_arch = "wasm32"))]
let rows = self.enter_row_scope(&ctx);
self.window_ui(ui);
#[cfg(not(target_arch = "wasm32"))]
self.leave_row_scope(rows);
arrange::forward_scroll(self, &ctx);
}
/// The close requests of the windows' close buttons from this frame: File › Close in that
/// window, which asks about unsaved changes first. The last window's close quits, which the
/// host asks about ([`WordApp::close_requested`]).
fn window_events(&mut self, closes: &[WindowId]) {
fn window_events(&mut self, closes: &[WindowId], ctx: &egui::Context) {
for &id in closes {
if self.quit_requested || self.windows.list.len() <= 1 || !self.windows.list.contains(id) {
if self.quit_requested || !self.windows.list.contains(id) {
continue;
}
self.close_window(id.get());
if self.window_count() > 1 {
self.close_window(id.get());
} else if self.windows.windowless_trial && self.closing.is_none() && self.enter_window(id.get()) {
// No native root close will follow. Quit through the existing guard, then let
// the host's next logic pass send Close to the logical root.
self.quit();
ctx.request_repaint();
}
}
}
@@ -636,6 +930,11 @@ impl WordApp {
if self.raise_closing().is_some() {
return;
}
// Its own system file dialog may still use this window: close it once that has ended.
#[cfg(not(target_arch = "wasm32"))]
if self.defer_close_for_native_panel(key) {
return;
}
if !self.enter_window(key) {
return;
}
+242 -1
View File
@@ -32,6 +32,12 @@ impl Rig {
Rig { kit: Kit::new(), focused: None, closing: Vec::new(), commands: Vec::new(), drawn: Vec::new(), builders: Vec::new() }
}
fn with_clipboard() -> Rig {
let spec = craft::ui::InstallSpec::new(craft::host::target::ShellInfo::default(), Arc::new(craft::ui::testing::windows::FakeSystem::new()))
.clipboard(craft::platform::clipboard::Clipboard::new(craft::platform::clipboard::MemoryClipboard::default()));
Rig { kit: Kit::with(spec), focused: None, closing: Vec::new(), commands: Vec::new(), drawn: Vec::new(), builders: Vec::new() }
}
fn ctx(&self) -> egui::Context {
self.kit.ctx.clone()
}
@@ -48,6 +54,11 @@ impl Rig {
/// One frame of every window.
fn frame(&mut self, a: &mut WordApp) {
self.frame_events(a, Vec::new(), Vec::new());
}
/// One frame of every window with explicit root and child input events.
fn frame_events(&mut self, a: &mut WordApp, root: Vec<egui::Event>, child: Vec<egui::Event>) {
self.kit.root_info(self.info(false));
self.kit.child_info(self.info(true));
if let Some(focused) = self.focused {
@@ -58,7 +69,7 @@ impl Rig {
}
// PLAN: assumed `embed::before_input(ctx, |out| app.frame_input(out))` (sh.A2) from app-hub.
craft::ui::shell::embed::before_input(&self.kit.ctx, |out| a.frame_input(out));
let out = self.kit.frame(Vec::new(), Vec::new(), |ui| {
let out = self.kit.frame(root, child, |ui| {
a.logic(ui.ctx());
// The root window's close request goes through the app's close decision, as the host's frame runs it.
craft::ui::shell::embed::logic(ui.ctx(), || a.close_decision());
@@ -108,6 +119,155 @@ fn text(a: &WordApp) -> String {
a.session.doc.plain_text(StoryRef::Body).trim().to_string()
}
/// Run through the real immediate viewport declaration with a renderer that declines one
/// attachment as eframe does: it returns without calling that viewport's body.
fn rejecting_frame(kit: &Kit, a: &mut WordApp, rejected: Option<ViewportId>) -> (Vec<ViewportId>, Vec<ViewportId>) {
mount_frame(kit, a, rejected, None)
}
fn mount_frame(kit: &Kit, a: &mut WordApp, rejected: Option<ViewportId>, closing: Option<ViewportId>) -> (Vec<ViewportId>, Vec<ViewportId>) {
use std::{cell::RefCell, rc::Rc};
let calls = Rc::new(RefCell::new((Vec::new(), Vec::new())));
// egui's renderer is thread-local and libtest runs each case on its own thread. The
// weak reference also disarms rejection and close injection after this frame returns.
let rendered = Rc::downgrade(&calls);
let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0));
egui::Context::set_immediate_viewport_renderer(move |ctx, mut viewport| {
let id = viewport.ids.this;
let frame = rendered.upgrade();
if let Some(frame) = &frame {
frame.borrow_mut().0.push(id);
if rejected == Some(id) {
return;
}
}
let events = if frame.is_some() && closing == Some(id) { vec![ViewportEvent::Close] } else { Vec::new() };
let info = ViewportInfo { parent: Some(viewport.ids.parent), inner_rect: Some(rect), outer_rect: Some(rect), events, ..Default::default() };
let mut input = egui::RawInput { viewport_id: id, screen_rect: Some(rect), ..Default::default() };
input.viewports.insert(id, info);
ctx.run_ui(input, |ui| (viewport.viewport_ui_cb)(ui)).drop_without_applying_deltas();
if let Some(frame) = frame {
frame.borrow_mut().1.push(id);
}
});
craft::ui::shell::embed::before_input(&kit.ctx, |out| a.frame_input(out));
// Both passes discard texture deltas: don't mix this fake renderer with Kit's backing
// texture store, which would then see root updates for allocations discarded by the child.
let input = egui::RawInput { screen_rect: Some(rect), ..Default::default() };
kit.ctx
.run_ui(input, |ui| {
a.logic(ui.ctx());
a.ui(ui);
})
.drop_without_applying_deltas();
std::mem::take(&mut *calls.borrow_mut())
}
#[test]
fn rejected_child_keeps_its_draft_and_the_survivor_can_edit_and_retry() {
let kit = Kit::new();
let mut a = app("Survivor draft");
a.enable_windowless_trial(true);
let survivor = a.windows.shown();
let survivor_doc = a.session.document_id();
let (_, drawn) = rejecting_frame(&kit, &mut a, None);
let survivor_view = a.windows.viewport(&kit.ctx, survivor).unwrap();
assert!(drawn.contains(&survivor_view));
a.run("file.new", json!({})).unwrap();
a.run("text.insert", json!({"text": "Parked draft"})).unwrap();
let parked = a.windows.shown();
let parked_doc = a.session.document_id();
let rejected = ViewportId::from_hash_of(super::window_container_id(a.windows.id_of(parked).unwrap()));
let (attempted, drawn) = rejecting_frame(&kit, &mut a, Some(rejected));
assert!(attempted.contains(&rejected) && !drawn.contains(&rejected));
assert!(drawn.contains(&survivor_view));
assert_eq!((a.windows.shown(), a.session.document_id()), (survivor, survivor_doc));
assert_eq!(a.windows.viewport(&kit.ctx, survivor), Some(survivor_view));
assert_eq!(a.windows.viewport(&kit.ctx, parked), None);
assert!(a.status_message().is_some(), "the surviving window is warned");
assert!(!a.quit_requested && a.closing.is_none());
assert!(a.session.document_dirty(parked_doc));
a.run("text.insert", json!({"text": " continues"})).unwrap();
assert_eq!(text(&a), "Survivor draft continues");
let (attempted, _) = rejecting_frame(&kit, &mut a, Some(rejected));
assert!(!attempted.contains(&rejected), "an unrelated repaint cannot retry the failed declaration");
mount_frame(&kit, &mut a, Some(rejected), Some(survivor_view));
assert!(!a.quit_requested && a.closing.is_none(), "native Close cannot consume the only attached surface or start an invisible guard");
assert_eq!(a.windows.viewport(&kit.ctx, survivor), Some(survivor_view));
assert!(a.run("file.close", json!({})).is_err(), "interactive File Close cannot open an unrelated Save Changes prompt");
assert!(a.closing.is_none());
let quit = a.ask_before_quit();
assert_eq!(quit["quit"], false);
assert!(quit["error"].is_string() && a.closing.is_none(), "explicit Quit reports why it is refused");
assert!(a.session.document_dirty(survivor_doc) && a.session.document_dirty(parked_doc));
a.show_window(parked);
let (_, drawn) = rejecting_frame(&kit, &mut a, Some(rejected));
let new_view = a.windows.viewport(&kit.ctx, parked).unwrap();
assert_ne!(new_view, rejected);
assert!(drawn.contains(&new_view) && drawn.contains(&survivor_view));
assert_eq!(a.session.document_id(), parked_doc);
assert_eq!(text(&a), "Parked draft");
assert!(!a.quit());
assert!(a.closing.is_some(), "after a successful retry, Quit can ask in the document's own window");
a.run("ui.saveChanges", json!({"answer": "cancel"})).unwrap();
assert!(!a.quit_requested && a.closing.is_none());
assert!(a.session.document_dirty(survivor_doc) && a.session.document_dirty(parked_doc));
}
#[test]
fn closing_an_attached_view_does_not_close_the_dirty_document_behind_its_rejected_peer() {
let kit = Kit::new();
let mut a = app("Shared unsaved draft");
a.enable_windowless_trial(true);
let doc = a.session.document_id();
let survivor = a.windows.shown();
rejecting_frame(&kit, &mut a, None);
a.new_window();
let peer = a.windows.id_of(a.windows.shown()).unwrap();
let rejected = ViewportId::from_hash_of(super::window_container_id(peer));
rejecting_frame(&kit, &mut a, Some(rejected));
assert!(a.closes_only_its_window("file.close", &json!({})));
assert!(a.execute("file.close", json!({})).is_err(), "the rejected view-only close is not retried as a document close");
assert_eq!(a.windows.shown(), survivor);
assert_eq!(a.session.document_id(), doc);
assert!(a.session.dirty && a.closing.is_none());
assert_eq!(text(&a), "Shared unsaved draft");
}
#[test]
fn a_clean_start_with_no_attached_document_window_requests_shutdown() {
let kit = Kit::new();
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), Services::default());
a.enable_windowless_trial(true);
let first = a.windows.id_of(a.windows.shown()).unwrap();
let rejected = ViewportId::from_hash_of(super::window_container_id(first));
let (attempted, drawn) = rejecting_frame(&kit, &mut a, Some(rejected));
assert!(attempted.contains(&rejected) && drawn.is_empty());
assert!(a.quit_requested && a.closing.is_none(), "a clean invisible app shouldn't wait for input");
assert!(a.windows.viewports(&kit.ctx).is_empty());
}
#[test]
fn a_rejected_first_window_does_not_discard_preexisting_edits() {
let kit = Kit::new();
let mut a = app("Unsaved before attach");
a.enable_windowless_trial(true);
let first = a.windows.id_of(a.windows.shown()).unwrap();
let rejected = ViewportId::from_hash_of(super::window_container_id(first));
let (_, drawn) = rejecting_frame(&kit, &mut a, Some(rejected));
assert!(drawn.is_empty());
assert!(!a.quit_requested && a.closing.is_none());
assert!(a.session.dirty);
assert_eq!(text(&a), "Unsaved before attach");
let (attempted, _) = rejecting_frame(&kit, &mut a, Some(rejected));
assert!(attempted.is_empty());
}
#[test]
fn closing_a_shared_document_window_returns_to_its_peer_not_an_unrelated_document() {
let mut a = app("Shared draft");
@@ -276,6 +436,52 @@ fn replacing_a_guarded_document_does_not_leave_a_permanent_close_hold() {
assert_eq!(text(&a), "Replacement");
}
#[test]
fn control_waits_for_the_windowless_target_and_never_closes_root() {
let mut rig = Rig::new();
let mut a = app("Untouched draft");
a.enable_windowless_trial(true);
let survivor = a.session.document_id();
rig.frames(&mut a, 2);
let survivor_viewport = a.control_viewport().unwrap();
assert_ne!(survivor_viewport, ViewportId::ROOT);
// A second automation request can arrive before this new active window gets its first draw.
a.run("file.new", json!({})).unwrap();
a.run("text.insert", json!({"text": "New draft"})).unwrap();
let target = a.session.document_id();
assert_ne!(target, survivor);
for (method, params) in [
("ui.closeWindow", json!({})),
("ui.resize", json!({"width": 400, "height": 300})),
("ui.focus", json!({"label": "Find"})),
("ui.screenshot", json!({})),
("ui.type", json!({"text": "must not be queued"})),
] {
let (req, _) = ControlRequest::new(method, params);
let Reply::Done(result) = crate::control::handle(&mut a, &rig.ctx(), &req) else { panic!("{method} was queued") };
assert_eq!(result["ok"], false, "{method}: {result}");
assert!(result["error"].as_str().unwrap_or_default().contains("retry once it opens"), "{method}: {result}");
}
rig.frames(&mut a, 2);
assert!(!rig.sent(ViewportId::ROOT, &ViewportCommand::Close));
assert!(!a.quit_requested && a.closing.is_none());
assert_eq!(text(&a), "New draft");
let target_viewport = a.control_viewport().unwrap();
assert_ne!(target_viewport, ViewportId::ROOT);
assert_ne!(target_viewport, survivor_viewport);
let (req, _) = ControlRequest::new("ui.closeWindow", json!({}));
let Reply::Done(result) = crate::control::handle(&mut a, &rig.ctx(), &req) else { panic!("close did not answer") };
assert_eq!(result["result"]["requested"], true);
rig.frame(&mut a);
assert!(rig.sent(target_viewport, &ViewportCommand::Close));
assert!(!rig.sent(ViewportId::ROOT, &ViewportCommand::Close));
rig.frames(&mut a, 2);
assert_eq!(a.closing.as_ref().and_then(|c| c.guard.current()), Some(&target));
assert!(a.session.is_open(survivor) && a.session.document_dirty(survivor) && !a.quit_requested);
}
#[test]
fn a_queued_request_wakes_the_window_that_must_handle_it() {
let mut rig = Rig::new();
@@ -1054,3 +1260,38 @@ fn root_viewport_receives_promoted_windows_title_after_root_closes() {
let idle_titles = rig.commands.iter().filter(|(v, c)| *v == ViewportId::ROOT && matches!(c, ViewportCommand::Title(_))).count();
assert_eq!(idle_titles, 0, "idle frame after promotion sends no duplicate title");
}
/// Mod+Shift+V with nothing copied pastes the clipboard as text in desktop windows other than
/// the first, even when quickly tapped so modifiers release before `run_fired`.
#[test]
fn mod_shift_v_with_nothing_copied_pastes_text_in_second_window() {
use craft::ui::runtime::commands::{ClipItem, ClipboardHandle};
let mut rig = Rig::with_clipboard();
let mut a = app("First");
rig.frames(&mut a, 2);
a.run("file.new", json!({})).unwrap();
rig.frames(&mut a, 2);
let child = a.active_viewport();
assert_ne!(child, ViewportId::ROOT);
rig.focus(child);
rig.frames(&mut a, 2);
assert_eq!(text(&a), "");
let _ = ClipboardHandle::of(&rig.ctx()).offer(&[ClipItem::Text("pasted".into())]).expect("clipboard takes offer");
let chord = if cfg!(target_os = "macos") {
egui::Modifiers { mac_cmd: true, command: true, shift: true, ..Default::default() }
} else {
egui::Modifiers { ctrl: true, command: true, shift: true, ..Default::default() }
};
let press_and_release = vec![
egui::Event::ModifiersChanged(chord),
egui::Event::Key { key: egui::Key::V, physical_key: Some(egui::Key::V), pressed: true, repeat: false, modifiers: chord },
egui::Event::Key { key: egui::Key::V, physical_key: Some(egui::Key::V), pressed: false, repeat: false, modifiers: egui::Modifiers::NONE },
egui::Event::ModifiersChanged(egui::Modifiers::NONE),
];
rig.frame_events(&mut a, Vec::new(), press_and_release);
rig.frame(&mut a);
assert_eq!(text(&a), "pasted", "Mod+Shift+V with nothing copied pastes text in the second OS window");
}
+89
View File
@@ -500,3 +500,92 @@ checker verifies the pairing (CT-MISMATCH, Error, observed — this row).
The corpus was regenerated; MANIFEST.md carries the fixed hashes.
The remaining nine stress files have not yet been shown to this consumer.
## Corpus probes — DrawingML geometry coordinate typing (#8231)
A real-world corpus document (`d60c276dc845`) containing a `wps` custom-geometry
shape (`a:custGeom`) inside `mc:AlternateContent` whose four `a:arcTo` elements
carried decimal `wR`/`hR` values was refused by Word for Windows (census) and
fell into the open-failure class on Word for Mac. Rounding only those eight
values to integers caused the full original document to open cleanly.
Follow-up probes derived from `d60c276dc845` (whose only decimals are the eight
`a:arcTo` radii) were measured in fresh instances of **Word for Mac 16.114.4
(2026-12-02)** (modal open-error alert / 0 documents opened on refusal):
| Form | Example | Word for Mac 16.114.4 |
|---|---|---|
| Plain decimal fraction | `407.666666666667` | REFUSES (original finding) |
| Integer | `407` | OPENS |
| Sign-prefixed fraction | `-407.666666666667` | REFUSES |
| Space-padded fraction | `" 407.666666666667 "` | REFUSES |
| Zero fraction | `407.0` | REFUSES |
| Strict-namespace `arcTo` (`http://purl.oclc.org/ooxml/drawingml/main`) in a Transitional package | — | REFUSES |
Context probes derived from `d60c276dc845` (one variable per probe; controls: original refuses, integer opens) were measured in **Word for Mac 16.114.4**:
| Context | Fractional radii in `custGeom` |
|---|---|
| Selected `mc:Choice` (first Supported, `Requires="wps"`; corpus document context) | REFUSES |
| Selected `mc:Choice` with no `Requires` attribute (`r1`) | REFUSES |
| Second, unselected `mc:Choice` (after Supported `mc:Choice`) | OPENS |
| `mc:Fallback` while a Supported `mc:Choice` precedes it | OPENS |
| `mc:Fallback` behind a foreign-namespace `mc:Choice` (`q1b`) | CONFOUNDED (Word refuses the MCE construction; geometry attribution unmeasurable) |
| Strict package (`http://purl.oclc.org/ooxml/...` namespaces, `conformance="strict"`) | OPENS |
| Outside any `mc:AlternateContent` (bare `w:drawing`, Transitional; `r2`) | REFUSES |
`DML-COORDINATE` is graded `Error` with `Observed` evidence only when ALL three
conditions hold:
1. **Transitional part profile**: the part's root element namespace resolves to
a non-Strict URI (not under `http://purl.oclc.org/ooxml/`). Strict parts and
parts whose root namespace cannot be resolved by the scanner (for example,
entity-obscured `xmlns`, undeclared prefix, or no namespace binding) never
emit `Error`.
2. **Supported-selected branch**: outside every `mc:AlternateContent`, or inside
the Supported-selected branch of every enclosing `mc:AlternateContent`. Each
`mc:Choice` evaluates to one of three states:
- **Supported**: `Requires` is absent (measured `r1`), or every
whitespace-delimited prefix resolves by exact URI equality to the closed
allowlist of Word MCE capability URIs (`w`, anchored on `wps`, plus Word's
shipped 2010/2012 WordprocessingML and DrawingML capability URIs).
- **Unresolved**: any `Requires` prefix resolves to an unlisted URI, fails to
resolve (undeclared, malformed, or entity-obscured), or `Requires` is empty
or entity-obscured. An Unresolved `Choice` makes the whole enclosing
`mc:AlternateContent`'s selection uncertain; no branch in it (that Choice,
later Choices, or `mc:Fallback`) may be treated as selected.
- **Unsupported**: reserved for capabilities a Word measurement proves Word
rejects without confounding MCE rejection; currently unpopulated (no
capability is populated by inference).
`mc:Fallback` is treated as selected only when `mc:AlternateContent` contains
no `Choice` at all; a `mc:Fallback` behind any `Choice` (`Supported`,
`Unresolved`, or `Unsupported`) is never treated as selected.
3. **Measured fractional geometry**: raw (undecoded, unnormalized) XML attribute
values matching `[ ]*-?[0-9]+\.[0-9]+[ ]*` with an `i64`-representable signed
whole part in `wR`/`hR` on `a:arcTo` in either the Transitional
(`http://schemas.openxmlformats.org/drawingml/2006/main`) or Strict
(`http://purl.oclc.org/ooxml/drawingml/main`) DrawingML namespace.
Every other invalid geometry finding is graded `Warning` and does not fail a
package. **Warning grade precedence** for measured fractional radii:
1. **Strict parts and definitively unselected enclosing `mc:AlternateContent`
branches** (for example, a second `mc:Choice` or `mc:Fallback` after a
Supported `mc:Choice`) report `Warning` with `Observed` evidence (Word
toleration is measured).
2. **Unresolved part profiles and unresolved `AlternateContent` selections**
report `Warning` with `MsDocumented` evidence only in a non-Strict part with
no definitively unselected enclosing branch.
Unmeasured schema-typed sibling attributes
(`ST_AdjCoordinate`, `ST_AdjAngle`, `ST_PositiveCoordinate`) and all unmeasured
invalid numeric lexical classes (`+`-prefixed fractions, non-space whitespace
padding such as `\t`/`\r`/`\n`, character-reference or entity-encoded
spellings, empty or whitespace-only values, lone signs, lone dots,
leading/trailing dots, scientific/exponent notation, integers outside their
schema type's bounds (`ST_PositiveCoordinate`: `0..=27273042316900`,
`ST_CoordinateUnqualified`: `-27273042329600..=27273042316900`, `ST_Angle`:
`-2147483648..=2147483647`), out-of-`i64`-range whole parts, and non-integer
path dimensions) are graded `Warning`
with `MsDocumented` evidence and do not fail a package. In-range integers, guide names,
and unit-qualified coordinate measures are preserved.
+12 -3
View File
@@ -48,6 +48,8 @@ Recorded reader pairs (exact shapes in the policy):
| Helper | Rules/conclusion | Collections/accessors | Intentional scope | Incompleteness causes | Fallback | Unknown package identity |
|---|---|---|---|---|---|---|
| lib.rs::ran | - | field.checks*1 | report accumulator and emission budgets; no input definition collection | per-rule findings, total findings, or coverage-note budget | preserve emitted evidence and record truncation/Incomplete; never supplies definition absence | independent |
| lib.rs::ran_dml_coordinate | DML-COORDINATE | - | report applicability for custom geometry | custom geometry may be absent from the scanned XML prefix | record the rule once when the scanner reaches custom geometry | independent |
| lib.rs::add_dml_coordinate_error | DML-COORDINATE | - | document-wide measured DML-COORDINATE error count and capped emission | per-rule finding cap | count every measured error across all XML parts and emit at most cap + 1 times so truncation is noted once | independent |
| lib.rs::allow | - | field.coverage*2,field.incomplete*1,field.rule_counts*1 | report accumulator and emission budgets; no input definition collection | per-rule findings, total findings, or coverage-note budget | preserve emitted evidence and record truncation/Incomplete; never supplies definition absence | independent |
| lib.rs::add | - | field.findings*1 | report accumulator and emission budgets; no input definition collection | per-rule findings, total findings, or coverage-note budget | preserve emitted evidence and record truncation/Incomplete; never supplies definition absence | independent |
| lib.rs::add_graded | - | field.findings*1 | report accumulator and emission budgets; no input definition collection | per-rule findings, total findings, or coverage-note budget | preserve emitted evidence and record truncation/Incomplete; never supplies definition absence | independent |
@@ -74,7 +76,9 @@ Recorded reader pairs (exact shapes in the policy):
| lib.rs::listing_complete | - | access.is_complete*2,field.listings*2,field.parts*1,field.special_notes*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| lib.rs::category_complete | - | access.is_complete*1,field.parts*1,type.Observed*1,type.Vec*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| lib.rs::xml_source_complete | - | field.parts*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| lib.rs::check_xml | HEADERSOURCE-PRESENT,MATH-PLACEMENT,PROTECTION-PASSWORD,STRUCT-END-P,XML-INVALID-CHAR,XML-MALFORMED,XML-UNDECLARED-PREFIX | access.prefix*1,access.retain_budget*1,field.comment_para_ids*1,field.content_part_exemptions*2,field.content_parts*2,field.entries*1,field.ink_content_parts*2,field.note_listings*1,field.refs*5,field.special_notes*1,field.unknown_prefixes*1,type.BTreeMap*1,type.HashMap*2,type.HashSet*2,type.Vec*13 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| lib.rs::check_xml | DML-COORDINATE,HEADERSOURCE-PRESENT,MATH-PLACEMENT,PROTECTION-PASSWORD,STRUCT-END-P,XML-INVALID-CHAR,XML-MALFORMED,XML-UNDECLARED-PREFIX | access.prefix*1,access.retain_budget*1,field.comment_para_ids*1,field.content_part_exemptions*2,field.content_parts*2,field.dml_coordinate_warnings*1,field.entries*1,field.ink_content_parts*2,field.note_listings*1,field.refs*5,field.special_notes*1,field.unknown_prefixes*1,type.BTreeMap*1,type.HashMap*2,type.HashSet*2,type.Vec*15 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| lib.rs::append_dml_coordinate_warnings | - | type.Vec*2 | bounded deferred DML-COORDINATE warnings across XML parts | per-rule finding cap | retain up to one warning past the cap to exercise truncation after measured errors | independent |
| lib.rs::flush_dml_coordinate_warnings | DML-COORDINATE | type.Observed*1,type.Vec*1 | deferred DML-COORDINATE warnings emitted after all XML parts | per-rule finding cap | emit measured errors ahead of warnings and trigger truncation at most once | independent |
| lib.rs::store_relationship_observations | - | access.invalidate*2,access.project*3,field.content*3,field.exemptions*3,field.references*2,type.BTreeMap*1,type.HashSet*1,type.Vec*6 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| lib.rs::store_note_observations | - | access.invalidate*3,access.push_bounded*3,field.listings*4,field.special_notes*2,type.BTreeMap*1,type.HashMap*1,type.Vec*3 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| lib.rs::append_note_items | - | type.Vec*6 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
@@ -193,7 +197,7 @@ Recorded reader pairs (exact shapes in the policy):
| scan.rs::close | - | field.frames*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| scan.rs::declared_encoding | - | field.bytes*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| scan.rs::decode_utf16_strict | - | type.Vec*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| scan.rs::scan_part | STRUCT-TC-NO-P | access.into_complete_set*2,access.invalidate*2,field.alt_stack*2,field.content_part_exemptions*2,field.content_parts*2,field.declared*8,field.frames*10,field.note_listings*1,field.note_listings_e*1,field.note_listings_f*1,field.para_ids*1,field.special_notes*2,field.unknown_prefixes*2,parser.parse_doctype_entities*1,type.BTreeMap*1,type.HashMap*1,type.HashSet*1,type.Observed*1,type.Vec*9 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| scan.rs::scan_part | STRUCT-TC-NO-P | access.into_complete_set*2,access.invalidate*2,field.alt_stack*2,field.content_part_exemptions*2,field.content_parts*2,field.declared*8,field.frames*10,field.note_listings*1,field.note_listings_e*1,field.note_listings_f*1,field.para_ids*1,field.special_notes*2,field.unknown_prefixes*2,parser.parse_doctype_entities*1,type.BTreeMap*1,type.HashMap*1,type.HashSet*1,type.Observed*1,type.Vec*10 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| scan.rs::own_declarations | - | type.Vec*2 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| scan.rs::open_attributes | - | type.Vec*2 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| scan.rs::enter_alt | - | field.alt_stack*1,field.frames*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
@@ -206,9 +210,14 @@ Recorded reader pairs (exact shapes in the policy):
| scan.rs::check_protection | PROTECTION-PASSWORD | type.Vec*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| scan.rs::record_note_pr | - | field.frames*2,field.note_listings_e*1,field.note_listings_f*1,field.special_notes*2 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| scan.rs::check_header_source | HEADERSOURCE-PRESENT | field.frames*2,field.withheld*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| scan.rs::in_custom_geometry | - | field.frames*1 | custom geometry ancestry of the current XML event | XML event/depth budget | use ancestry of events already scanned | independent |
| scan.rs::prefix_requires_state | - | type.Vec*1 | namespace scope for one mc:Choice Requires prefix | XML event/depth budget; entity-obscured xmlns declaration | treat unlisted, undeclared, malformed, or entity-obscured prefix bindings as unresolved rather than supported or unsupported | independent |
| scan.rs::choice_requires_state | - | type.Vec*1 | mc:Choice Requires attribute evaluation in current namespace scope | XML event/depth budget; entity-obscured Requires or xmlns declaration | withhold Error by returning Unresolved when Requires or any prefix binding is unlisted, empty, undeclared, or unreadable | independent |
| scan.rs::dml_branch_selection | - | field.alt_stack*1 | enclosing mc:AlternateContent branch selection for the current XML event | XML event/depth budget | evaluate enclosing AlternateContent frames already scanned | independent |
| scan.rs::check_dml_coordinates | DML-COORDINATE | field.dml_coordinate_warnings*2,field.frames*1 | source-local custom geometry attribute values | source unavailable or malformed; XML event/depth budget | measured decimal-fraction spellings ([ ]*-?[0-9]+\\.[0-9]+[ ]* raw XML source) in a:arcTo wR/hR (Transitional or Strict DrawingML namespace) receive Error with Observed evidence only when the part profile is Transitional and every enclosing AlternateContent is Supported-selected (bare drawing, Supported Choice, or choice-less Fallback); Warning grade precedence: Strict parts and definitively unselected enclosing AlternateContent branches report Warning with Observed evidence, while unresolved part profiles and unresolved AlternateContent selections report Warning with MsDocumented evidence only in a non-Strict part with no definitively unselected enclosing branch; other invalid schema-typed custom geometry attributes and unmeasured or unresolvable lexical classes receive Warning with MsDocumented evidence; measured Errors are emitted ahead of Warnings; report invalid values in the scanned prefix | independent |
| scan.rs::record | - | field.reps*3 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| scan.rs::check_para_ids | PARAID-VALUE | field.alt_stack*1,field.para_ids*3 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| scan.rs::assign_alt_branch | - | field.alt_stack*1,field.frames*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| scan.rs::assign_alt_branch | - | field.alt_stack*1,field.declared*1,field.frames*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| scan.rs::restore_branch | - | field.alt_stack*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| scan.rs::on_empty | STRUCT-TC-NO-P | - | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| scan.rs::record_ids | - | field.docpr*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
+340 -2
View File
@@ -434,6 +434,48 @@ pub(crate) const PROTECTION_PASSWORD: RuleSpec =
/// Batch b6 (Word for the web, 2026-11-07): corruption banner, view-only
/// — observed.
pub(crate) const HEADERSOURCE_PRESENT: RuleSpec = RuleSpec { id: "HEADERSOURCE-PRESENT", severity: Severity::Error, evidence: Evidence::Observed };
/// `DML-COORDINATE`: an invalid numeric literal in an integer-typed DrawingML
/// custom geometry coordinate or angle attribute (`ST_PositiveCoordinate`,
/// `ST_AdjCoordinate`, `ST_AdjAngle`).
/// Observed (#8231): Word for Windows (census) and Word for Mac 16.114.4
/// (2026-12-02, fresh instances) on probes derived from `d60c276dc845`
/// refused decimal-fraction `wR`/`hR` values on `a:arcTo` across all five
/// refusal forms — plain (`407.666666666667`), minus-sign-prefixed
/// (`-407.666666666667`), ASCII-space-padded (`" 407.666666666667 "`),
/// zero-fraction (`407.0`), and Strict-namespace `arcTo`
/// (`http://purl.oclc.org/ooxml/drawingml/main`) in a Transitional package —
/// while opening the integer twin (`407`) cleanly.
/// Follow-up context probes (Word for Mac 16.114.4) narrowed refusal further:
/// Word refuses fractional radii in the selected `mc:Choice` (first Supported
/// Choice, including a Choice with no `Requires` attribute — probe `r1`) or
/// outside any `mc:AlternateContent` (bare `w:drawing` — probe `r2`), while
/// opening fractional radii in an unselected second `mc:Choice`, in
/// `mc:Fallback` when a Supported Choice precedes it, or in a Strict part
/// (`http://purl.oclc.org/ooxml/...` root namespace). The foreign-namespace
/// `mc:Fallback` probe is confounded (Word refuses that file for its MCE
/// construction rather than measurably for the geometry), so `mc:Fallback` is
/// treated as selected only when `mc:AlternateContent` contains no `Choice` at
/// all.
/// Error requires ALL of: Transitional part profile (root namespace resolved to
/// a non-Strict URI) + Supported-selected branch at every enclosing level (bare
/// drawing, Supported `mc:Choice`, or choice-less `mc:Fallback`, with `Requires`
/// evaluated against a closed exact-URI allowlist of Word MCE capabilities
/// including `w` and `wps`) + measured fractional geometry (raw XML attribute
/// values matching `[ ]*-?[0-9]+\.[0-9]+[ ]*` with an `i64`-representable whole
/// part in `a:arcTo` `wR`/`hR` in Transitional or Strict DrawingML namespace).
/// Every other invalid geometry finding is graded Warning via
/// [`Acc::add_graded`]. Warning grade precedence for measured fractional radii:
/// Strict parts and definitively unselected enclosing `mc:AlternateContent`
/// branches report `Warning` / `Observed`; unresolved part profiles and
/// unresolved `AlternateContent` selections (including any `Choice` with an
/// unlisted, undeclared, empty, or entity-obscured `Requires`, or a `Fallback`
/// behind any `Choice`) report `Warning` / `MsDocumented` only in a non-Strict
/// part with no definitively unselected enclosing branch. Unmeasured sibling
/// attributes and unmeasured invalid lexical classes (`+`-prefixed fractions,
/// non-space padding, entity/character-reference encodings, exponent forms,
/// leading/trailing dots, empty/whitespace-only, out-of-schema-range integers,
/// or out-of-`i64`-range whole parts) emit `Warning` / `MsDocumented`.
pub(crate) const DML_COORDINATE: RuleSpec = RuleSpec { id: "DML-COORDINATE", severity: Severity::Error, evidence: Evidence::Observed };
/// `CONTENTPART-TYPE`: a `w:contentPart` element whose relationship target's
/// effective content type is not `text/xml`. MS-OI29500 Part 1 §17.3.3.2
/// note (a): "Word will fail to load the document if the content part's
@@ -522,6 +564,7 @@ pub(crate) const RULES: &[RuleSpec] = &[
NOTE_PR_DANGLING,
PROTECTION_PASSWORD,
HEADERSOURCE_PRESENT,
DML_COORDINATE,
CONTENTPART_TYPE,
REL_DUP_ID,
REL_DANGLING,
@@ -569,6 +612,9 @@ pub(crate) struct Acc {
findings: Vec<Finding>,
coverage: Vec<String>,
checks: Vec<&'static str>,
dml_coordinate_checked: bool,
/// Document-wide count of measured `DML-COORDINATE` Error findings seen across all XML parts.
dml_coordinate_errors: usize,
incomplete: bool,
limits: Limits,
rule_counts: HashMap<&'static str, usize>,
@@ -597,6 +643,40 @@ impl Acc {
self.checks.push(rule);
}
/// Record that a custom geometry scope was reached, once per package.
fn ran_dml_coordinate(&mut self) {
observation_contract! {
rules: "DML-COORDINATE";
collections: "-";
scope: "report applicability for custom geometry";
loss: "custom geometry may be absent from the scanned XML prefix";
fallback: "record the rule once when the scanner reaches custom geometry";
package_loss: "independent";
}
if !self.dml_coordinate_checked {
self.ran(DML_COORDINATE.id);
self.dml_coordinate_checked = true;
}
}
/// Count a measured `DML-COORDINATE` Error across the whole document and emit it via
/// [`Acc::add`] at most `findings_per_rule + 1` times so repeated overflow Errors cannot
/// append duplicate truncation coverage notes.
pub(crate) fn add_dml_coordinate_error(&mut self, part: String, message: String) {
observation_contract! {
rules: "DML-COORDINATE";
collections: "-";
scope: "document-wide measured DML-COORDINATE error count and capped emission";
loss: "per-rule finding cap";
fallback: "count every measured error across all XML parts and emit at most cap + 1 times so truncation is noted once";
package_loss: "independent";
}
self.dml_coordinate_errors = self.dml_coordinate_errors.saturating_add(1);
if self.dml_coordinate_errors <= self.limits.findings_per_rule.saturating_add(1) {
self.add(DML_COORDINATE.id, Some(part), message);
}
}
/// Record that the archive holds an entry whose identity could not be recovered. Absence
/// conclusions are suppressed from here on (see [`contracts_generated::PACKAGE_ABSENCE_RULES`]).
pub(crate) fn set_unknown_unreadable(&mut self) {
@@ -1467,8 +1547,8 @@ fn xml_source_complete(xml: &XmlScan, entry: &package::Entry) -> bool {
/// Scan all XML parts for well-formedness, undeclared prefixes, illegal characters, and extract story facts.
fn check_xml(pkg: &Package, acc: &mut Acc) -> XmlScan {
observation_contract! {
rules: "HEADERSOURCE-PRESENT,MATH-PLACEMENT,PROTECTION-PASSWORD,STRUCT-END-P,XML-INVALID-CHAR,XML-MALFORMED,XML-UNDECLARED-PREFIX";
collections: "access.prefix*1,access.retain_budget*1,field.comment_para_ids*1,field.content_part_exemptions*2,field.content_parts*2,field.entries*1,field.ink_content_parts*2,field.note_listings*1,field.refs*5,field.special_notes*1,field.unknown_prefixes*1,type.BTreeMap*1,type.HashMap*2,type.HashSet*2,type.Vec*13";
rules: "DML-COORDINATE,HEADERSOURCE-PRESENT,MATH-PLACEMENT,PROTECTION-PASSWORD,STRUCT-END-P,XML-INVALID-CHAR,XML-MALFORMED,XML-UNDECLARED-PREFIX";
collections: "access.prefix*1,access.retain_budget*1,field.comment_para_ids*1,field.content_part_exemptions*2,field.content_parts*2,field.dml_coordinate_warnings*1,field.entries*1,field.ink_content_parts*2,field.note_listings*1,field.refs*5,field.special_notes*1,field.unknown_prefixes*1,type.BTreeMap*1,type.HashMap*2,type.HashSet*2,type.Vec*15";
scope: "source-local bounded extraction; no implicit document owner";
loss: "source unavailable or malformed; XML event/depth budget; category allocation cap";
fallback: "retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set";
@@ -1510,6 +1590,7 @@ fn check_xml(pkg: &Package, acc: &mut Acc) -> XmlScan {
let mut pooled_refs = 0usize;
let mut refs_pooled_capped = false;
let mut refs_pooled_part: Option<String> = None;
let mut dml_coordinate_warnings: Vec<DeferredDmlWarning> = Vec::new();
for e in pkg.entries.iter().filter(|e| !e.is_dir) {
if !package::is_xml_part(pkg, &e.name) {
continue;
@@ -1542,6 +1623,8 @@ fn check_xml(pkg: &Package, acc: &mut Acc) -> XmlScan {
let Some(text) = &e.decoded else { continue };
let mut scanned = scan::scan_part(&e.name, text, role, acc);
append_dml_coordinate_warnings(&mut dml_coordinate_warnings, &e.name, scanned.dml_coordinate_warnings, acc.limits.findings_per_rule);
*note_incomplete_parts.entry(l.clone()).or_default() |= scanned.note_loss;
if append_note_items(&mut note_listings, &mut special_notes, &e.name, scanned.note_listings, scanned.special_notes, acc.limits.facts) {
*note_incomplete_parts.entry(l.clone()).or_default() |= scan::NOTE_ALL;
@@ -1634,6 +1717,7 @@ fn check_xml(pkg: &Package, acc: &mut Acc) -> XmlScan {
acc.add("XML-INVALID-CHAR", Some(e.name.clone()), format!("{} contains {desc}, which is illegal in XML 1.0", e.name));
}
}
flush_dml_coordinate_warnings(dml_coordinate_warnings, acc);
if pooled_capped {
let part = facts_pooled_part.as_deref().unwrap_or("an unknown part");
acc.note(format!("the pooled story facts exceeded {} entries at {part}; later facts were not recorded", acc.limits.facts));
@@ -1666,6 +1750,47 @@ fn check_xml(pkg: &Package, acc: &mut Acc) -> XmlScan {
XmlScan { graph, parts, compat }
}
type DeferredDmlWarning = (String, scan::DmlWarnEvidence, String);
/// Buffer deferred `DML-COORDINATE` Warnings across XML parts up to one past the finding cap
/// so Warnings can be emitted after all parts have been scanned without crowding out Errors.
fn append_dml_coordinate_warnings(out: &mut Vec<DeferredDmlWarning>, part: &str, part_warnings: Vec<(scan::DmlWarnEvidence, String)>, cap: usize) {
observation_contract! {
rules: "-";
collections: "type.Vec*2";
scope: "bounded deferred DML-COORDINATE warnings across XML parts";
loss: "per-rule finding cap";
fallback: "retain up to one warning past the cap to exercise truncation after measured errors";
package_loss: "independent";
}
let budget = cap.saturating_add(1).saturating_sub(out.len());
out.extend(part_warnings.into_iter().take(budget).map(|(evidence, message)| (part.to_string(), evidence, message)));
}
/// Emit deferred `DML-COORDINATE` Warnings after all XML parts have been scanned, keeping at
/// most one overflow Warning when measured Errors have not already exceeded the cap.
fn flush_dml_coordinate_warnings(deferred: Vec<DeferredDmlWarning>, acc: &mut Acc) {
observation_contract! {
rules: "DML-COORDINATE";
collections: "type.Observed*1,type.Vec*1";
scope: "deferred DML-COORDINATE warnings emitted after all XML parts";
loss: "per-rule finding cap";
fallback: "emit measured errors ahead of warnings and trigger truncation at most once";
package_loss: "independent";
}
let errors_seen = acc.dml_coordinate_errors;
let remaining = if errors_seen > acc.limits.findings_per_rule { 0 } else { (acc.limits.findings_per_rule - errors_seen).saturating_add(1) };
for (part, evidence, message) in deferred.into_iter().take(remaining) {
let evidence = match evidence {
scan::DmlWarnEvidence::ObservedContext => Evidence::Observed,
scan::DmlWarnEvidence::Unmeasured => Evidence::MsDocumented,
};
acc.add_graded(DML_COORDINATE.id, Severity::Warning, evidence, Some(part), message);
}
}
/// Attach each relationship fact collection's loss to its contributing source.
fn store_relationship_observations(
parts: &mut std::collections::BTreeMap<PartId, PartFacts>,
@@ -6974,6 +7099,219 @@ mod budget_tests {
assert!(mixed.findings.iter().any(|f| f.rule == "MEDIA-MAGIC" && f.severity == Severity::Warning));
}
#[test]
fn dml_coordinate_budget_keeps_errors_ahead_of_warnings_across_orderings_and_parts() {
let wrap_doc = |arcs: &str| {
format!(
r#"<?xml version="1.0"?><w:document xmlns:w="{NS_W}" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><w:body><w:p><w:r><a:custGeom><a:pathLst><a:path w="100" h="100">{arcs}</a:path></a:pathLst></a:custGeom></w:r></w:p></w:body></w:document>"#
)
.into_bytes()
};
let wrap_hdr = |arcs: &str| {
format!(
r#"<?xml version="1.0"?><w:hdr xmlns:w="{NS_W}" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><w:p><w:r><a:custGeom><a:pathLst><a:path w="100" h="100">{arcs}</a:path></a:pathLst></a:custGeom></w:r></w:p></w:hdr>"#
)
.into_bytes()
};
let zip_doc = |arcs: &str| {
tiny_zip(&[
("[Content_Types].xml", content_types()),
("_rels/.rels", package_rels()),
("word/document.xml", wrap_doc(arcs)),
("word/_rels/document.xml.rels", doc_rels()),
])
};
let warn_arc = r#"<a:arcTo wR="+12.5" hR="+12.5" stAng="0" swAng="cd4"/>"#;
let err_arc = r#"<a:arcTo wR="12.5" hR="12.5" stAng="0" swAng="cd4"/>"#;
let limits = Limits { findings_per_rule: 4, ..Limits::default() };
// Warnings-first, Errors-first, and interleaved orderings all keep both measured Errors
// ahead of Warnings and bound total DML-COORDINATE findings to the cap.
for (label, arcs) in [
("warnings then error", format!("{warn_arc}{warn_arc}{warn_arc}{err_arc}")),
("error then warnings", format!("{err_arc}{warn_arc}{warn_arc}{warn_arc}")),
("interleaved", format!("{warn_arc}{err_arc}{warn_arc}{warn_arc}")),
] {
let report = validate_bytes_limited(&zip_doc(&arcs), limits);
assert_eq!(report.verdict, Verdict::Fail, "{label}: {report:?}");
let dml: Vec<_> = report.findings.iter().filter(|f| f.rule == "DML-COORDINATE").collect();
assert_eq!(dml.len(), 4, "{label}: {dml:?}");
assert_eq!(dml.iter().filter(|f| f.severity == Severity::Error && f.evidence == Evidence::Observed).count(), 2, "{label}: {dml:?}");
assert_eq!(dml.iter().filter(|f| f.severity == Severity::Warning && f.evidence == Evidence::MsDocumented).count(), 2, "{label}: {dml:?}");
assert_eq!(
report.coverage_notes.iter().filter(|n| n.starts_with("more than 4 DML-COORDINATE")).count(),
1,
"{label}: {:?}",
report.coverage_notes
);
}
// Cross-part: Warnings in word/document.xml exceed the cap before a measured Error in word/header1.xml.
let cross_part = tiny_zip(&[
("[Content_Types].xml", content_types()),
("_rels/.rels", package_rels()),
("word/document.xml", wrap_doc(&format!("{warn_arc}{warn_arc}{warn_arc}"))),
("word/_rels/document.xml.rels", doc_rels()),
("word/header1.xml", wrap_hdr(err_arc)),
]);
let cross_report = validate_bytes_limited(&cross_part, limits);
assert_eq!(cross_report.verdict, Verdict::Fail, "{cross_report:?}");
let cross_dml: Vec<_> = cross_report.findings.iter().filter(|f| f.rule == "DML-COORDINATE").collect();
assert_eq!(cross_dml.len(), 4, "{cross_dml:?}");
assert_eq!(
cross_dml
.iter()
.filter(|f| f.part.as_deref() == Some("word/header1.xml") && f.severity == Severity::Error && f.evidence == Evidence::Observed)
.count(),
2,
"{cross_dml:?}"
);
assert_eq!(cross_report.coverage_notes.iter().filter(|n| n.starts_with("more than 4 DML-COORDINATE")).count(), 1);
// Warnings-only overflow still yields Incomplete with bounded Warnings and one truncation note.
let warn_only = validate_bytes_limited(&zip_doc(&format!("{warn_arc}{warn_arc}{warn_arc}")), limits);
assert_eq!(warn_only.verdict, Verdict::Incomplete, "{warn_only:?}");
let warn_dml: Vec<_> = warn_only.findings.iter().filter(|f| f.rule == "DML-COORDINATE").collect();
assert_eq!(warn_dml.len(), 4, "{warn_dml:?}");
assert!(warn_dml.iter().all(|f| f.severity == Severity::Warning));
assert_eq!(warn_only.coverage_notes.iter().filter(|n| n.starts_with("more than 4 DML-COORDINATE")).count(), 1);
// Errors-only overflow with extra Warnings retains only Errors up to the cap and emits
// exactly one truncation coverage note.
let err_overflow = validate_bytes_limited(&zip_doc(&format!("{warn_arc}{err_arc}{warn_arc}{err_arc}{err_arc}")), limits);
assert_eq!(err_overflow.verdict, Verdict::Fail, "{err_overflow:?}");
let err_dml: Vec<_> = err_overflow.findings.iter().filter(|f| f.rule == "DML-COORDINATE").collect();
assert_eq!(err_dml.len(), 4, "{err_dml:?}");
assert!(err_dml.iter().all(|f| f.severity == Severity::Error && f.evidence == Evidence::Observed));
assert_eq!(
err_overflow.coverage_notes.iter().filter(|n| n.starts_with("more than 4 DML-COORDINATE")).count(),
1,
"single-part overflow errors must not duplicate truncation notes: {:?}",
err_overflow.coverage_notes
);
// Cross-part error overflow: cap 4, six measured Errors across two parts (2+4, 4+2, and
// 6+2 with extra Warnings) must retain four Errors, emit exactly one DML-COORDINATE
// truncation coverage note, and Fail.
for (label, doc_arcs, hdr_arcs) in [
("2+4 errors across two parts", err_arc.to_string(), format!("{err_arc}{err_arc}")),
("4+2 errors across two parts", format!("{err_arc}{err_arc}"), err_arc.to_string()),
("6+2 errors plus warnings across two parts", format!("{warn_arc}{err_arc}{err_arc}{err_arc}"), format!("{err_arc}{warn_arc}")),
] {
let two_part = tiny_zip(&[
("[Content_Types].xml", content_types()),
("_rels/.rels", package_rels()),
("word/document.xml", wrap_doc(&doc_arcs)),
("word/_rels/document.xml.rels", doc_rels()),
("word/header1.xml", wrap_hdr(&hdr_arcs)),
]);
let report = validate_bytes_limited(&two_part, limits);
assert_eq!(report.verdict, Verdict::Fail, "{label}: {report:?}");
let dml: Vec<_> = report.findings.iter().filter(|f| f.rule == "DML-COORDINATE").collect();
assert_eq!(dml.len(), 4, "{label}: {dml:?}");
assert!(dml.iter().all(|f| f.severity == Severity::Error && f.evidence == Evidence::Observed), "{label}: {dml:?}");
assert_eq!(
report.coverage_notes.iter().filter(|n| n.starts_with("more than 4 DML-COORDINATE")).count(),
1,
"{label}: duplicate truncation notes: {:?}",
report.coverage_notes
);
}
// Exact cap (2 Warnings + 2 Errors == 4) records all 4 with no truncation note.
let exact = validate_bytes_limited(&zip_doc(&format!("{warn_arc}{err_arc}")), limits);
assert_eq!(exact.verdict, Verdict::Fail, "{exact:?}");
let exact_dml: Vec<_> = exact.findings.iter().filter(|f| f.rule == "DML-COORDINATE").collect();
assert_eq!(exact_dml.len(), 4, "{exact_dml:?}");
assert!(exact.coverage_notes.is_empty(), "{:?}", exact.coverage_notes);
}
#[test]
fn dml_coordinate_deferred_unselected_branch_warnings_preserve_observed_evidence_and_error_priority() {
let wrap_doc = |body: &str| {
format!(
r#"<?xml version="1.0"?><w:document xmlns:w="{NS_W}" xmlns:mc="{NS_MC}" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"><w:body><w:p><w:r>{body}</w:r></w:p></w:body></w:document>"#
)
.into_bytes()
};
let wrap_hdr = |body: &str| {
format!(
r#"<?xml version="1.0"?><w:hdr xmlns:w="{NS_W}" xmlns:mc="{NS_MC}" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"><w:p><w:r>{body}</w:r></w:p></w:hdr>"#
)
.into_bytes()
};
let geom = |arcs: &str| format!(r#"<a:custGeom><a:pathLst><a:path w="100" h="100">{arcs}</a:path></a:pathLst></a:custGeom>"#);
let frac_arc = r#"<a:arcTo wR="12.5" hR="12.5" stAng="0" swAng="cd4"/>"#;
let plus_arc = r#"<a:arcTo wR="+12.5" hR="+12.5" stAng="0" swAng="cd4"/>"#;
let ok_arc = r#"<a:arcTo wR="12" hR="12" stAng="0" swAng="cd4"/>"#;
let limits = Limits { findings_per_rule: 4, ..Limits::default() };
// Unselected-branch Warnings (Fallback after satisfiable Choice) exceed cap in document.xml,
// while a selected-branch Error sits later in header1.xml. Measured Errors must survive
// ahead of unselected-branch Warnings, and retained unselected-branch Warnings must keep
// Evidence::Observed while emitting a single truncation note.
let unselected_six = format!(
r#"<mc:AlternateContent><mc:Choice Requires="wps">{}</mc:Choice><mc:Fallback>{}</mc:Fallback></mc:AlternateContent>"#,
geom(ok_arc),
geom(&format!("{frac_arc}{frac_arc}{frac_arc}"))
);
let selected_two =
format!(r#"<mc:AlternateContent><mc:Choice Requires="wps">{}</mc:Choice><mc:Fallback/></mc:AlternateContent>"#, geom(frac_arc));
let cross_part = tiny_zip(&[
("[Content_Types].xml", content_types()),
("_rels/.rels", package_rels()),
("word/document.xml", wrap_doc(&unselected_six)),
("word/_rels/document.xml.rels", doc_rels()),
("word/header1.xml", wrap_hdr(&selected_two)),
]);
let report = validate_bytes_limited(&cross_part, limits);
assert_eq!(report.verdict, Verdict::Fail, "{report:?}");
let dml: Vec<_> = report.findings.iter().filter(|f| f.rule == "DML-COORDINATE").collect();
assert_eq!(dml.len(), 4, "{dml:?}");
assert_eq!(
dml.iter()
.filter(|f| f.part.as_deref() == Some("word/header1.xml") && f.severity == Severity::Error && f.evidence == Evidence::Observed)
.count(),
2,
"{dml:?}"
);
assert_eq!(
dml.iter()
.filter(|f| f.part.as_deref() == Some("word/document.xml") && f.severity == Severity::Warning && f.evidence == Evidence::Observed)
.count(),
2,
"{dml:?}"
);
assert_eq!(report.coverage_notes.iter().filter(|n| n.starts_with("more than 4 DML-COORDINATE")).count(), 1, "{:?}", report.coverage_notes);
// Mixed deferred Warning evidences in one part preserve each finding's own evidence class
// (Observed for unselected-branch measured fraction, MsDocumented for unmeasured "+12.5").
let mixed_warns = format!(
r#"<mc:AlternateContent><mc:Choice Requires="wps">{}</mc:Choice><mc:Fallback>{}</mc:Fallback></mc:AlternateContent>"#,
geom(ok_arc),
geom(&format!("{frac_arc}{plus_arc}"))
);
let mixed_zip = tiny_zip(&[
("[Content_Types].xml", content_types()),
("_rels/.rels", package_rels()),
("word/document.xml", wrap_doc(&mixed_warns)),
("word/_rels/document.xml.rels", doc_rels()),
]);
let mixed = validate_bytes_limited(&mixed_zip, limits);
assert_eq!(mixed.verdict, Verdict::Pass, "{mixed:?}");
let mixed_dml: Vec<_> = mixed.findings.iter().filter(|f| f.rule == "DML-COORDINATE").collect();
assert_eq!(mixed_dml.len(), 4, "{mixed_dml:?}");
for (raw, want_evidence) in [("\"12.5\"", Evidence::Observed), ("\"+12.5\"", Evidence::MsDocumented)] {
for attr in ["wR", "hR"] {
let finding = mixed_dml
.iter()
.find(|f| f.message.contains(attr) && f.message.contains(raw))
.unwrap_or_else(|| panic!("missing {attr}/{raw}: {mixed_dml:?}"));
assert_eq!((finding.severity, finding.evidence), (Severity::Warning, want_evidence), "{attr}/{raw}: {finding:?}");
}
}
}
#[test]
fn media_magic_webp_preflight_respects_and_charges_decode_budget() {
let malformed = b"RIFF\x04\0\0\0WEBP";
+519 -17
View File
@@ -386,6 +386,16 @@ impl StoryFacts {
}
}
/// Evidence basis for a deferred `DML-COORDINATE` Warning.
#[derive(Clone, Copy)]
pub(crate) enum DmlWarnEvidence {
/// Word-measured toleration (Strict part or definitively unselected `mc:AlternateContent` branch).
ObservedContext,
/// Unresolved part profile, unresolved `AlternateContent` selection, unmeasured attribute,
/// lexical class, entity encoding, or out-of-schema-range integer.
Unmeasured,
}
/// The result of scanning one XML or `.rels` part.
pub(crate) struct PartScan {
pub malformed: Option<String>,
@@ -426,6 +436,10 @@ pub(crate) struct PartScan {
pub fact_capped: bool,
/// The per-part reference budget dropped at least one `r:id`/`r:embed`/`r:link`.
pub refs_capped: bool,
/// Deferred `DML-COORDINATE` warning `(evidence, message)` pairs collected during this part
/// scan, bounded so Warnings can be flushed after all XML parts without crowding out measured
/// Errors.
pub dml_coordinate_warnings: Vec<(DmlWarnEvidence, String)>,
/// All XML events and story facts were examined; absence joins may use this part.
pub facts_complete: bool,
/// XML events completed independently of individual fact/reference allocation caps.
@@ -451,6 +465,10 @@ impl ElemId<'_> {
fn wp(&self) -> bool {
self.local_w(NS_WP)
}
/// Whether this element belongs to the DrawingML main namespace (`a:`).
fn a(&self) -> bool {
matches!(self.ns, Some(ns) if ns == NS_A.as_bytes() || ns == b"http://purl.oclc.org/ooxml/drawingml/main")
}
/// Whether this element belongs to the Office Math namespace (`m:`).
fn m(&self) -> bool {
self.local_w(NS_M)
@@ -679,6 +697,10 @@ struct Frame {
/// A `w:customXml` frame: likewise a prohibited direct parent only at block,
/// cell, or row level — a run-level `customXml` inside a paragraph is not.
is_custom_xml: bool,
/// This element is within an `a:custGeom` subtree.
in_custom_geometry: bool,
/// Distinguishes `a:CT_Path2D` from the gradient-fill `a:path` variant.
is_path_lst: bool,
tc_has_block: bool,
/// A block of known kind (or a skipped `AlternateContent`) was seen directly in this cell.
tc_known_block: bool,
@@ -691,9 +713,9 @@ struct Frame {
/// This frame is an `mc:AlternateContent` element.
alt: bool,
/// For an `mc:Choice` / `mc:Fallback` frame that assigned the
/// enclosing block's current branch: the branch value to restore
/// when this frame closes.
alt_branch_prev: Option<u32>,
/// enclosing block's current branch: the `(branch, in_selected_branch)`
/// pair to restore when this frame closes.
alt_branch_prev: Option<(u32, bool)>,
/// The element was opened inside a skipped `mc:AlternateContent` subtree, so its closing event
/// must not touch the frame counters or report structural findings.
suppressed: bool,
@@ -768,6 +790,8 @@ struct State {
alt_depth: usize,
/// One coverage note per part that contains `mc:AlternateContent`.
alt_noted: bool,
/// Profile of this part's root element namespace (Transitional, Strict, or Unresolved).
part_profile: PartProfile,
/// The per-category fact budget, copied from [`crate::Limits`].
fact_cap: usize,
/// A fact budget was exhausted; no further facts are collected.
@@ -1055,7 +1079,7 @@ fn decode_utf16_strict(bytes: &[u8], little_endian: bool) -> Result<String, Deco
pub(crate) fn scan_part(part: &str, text: &str, role: PartRole, acc: &mut Acc) -> PartScan {
observation_contract! {
rules: "STRUCT-TC-NO-P";
collections: "access.into_complete_set*2,access.invalidate*2,field.alt_stack*2,field.content_part_exemptions*2,field.content_parts*2,field.declared*8,field.frames*10,field.note_listings*1,field.note_listings_e*1,field.note_listings_f*1,field.para_ids*1,field.special_notes*2,field.unknown_prefixes*2,parser.parse_doctype_entities*1,type.BTreeMap*1,type.HashMap*1,type.HashSet*1,type.Observed*1,type.Vec*9";
collections: "access.into_complete_set*2,access.invalidate*2,field.alt_stack*2,field.content_part_exemptions*2,field.content_parts*2,field.declared*8,field.frames*10,field.note_listings*1,field.note_listings_e*1,field.note_listings_f*1,field.para_ids*1,field.special_notes*2,field.unknown_prefixes*2,parser.parse_doctype_entities*1,type.BTreeMap*1,type.HashMap*1,type.HashSet*1,type.Observed*1,type.Vec*10";
scope: "source-local bounded extraction; no implicit document owner";
loss: "source unavailable or malformed; XML event/depth budget; category allocation cap";
fallback: "retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set";
@@ -1086,6 +1110,7 @@ pub(crate) fn scan_part(part: &str, text: &str, role: PartRole, acc: &mut Acc) -
note_loss: 0,
fact_capped: false,
refs_capped: false,
dml_coordinate_warnings: Vec::new(),
facts_complete: false,
syntax_complete: false,
};
@@ -1116,7 +1141,8 @@ pub(crate) fn scan_part(part: &str, text: &str, role: PartRole, acc: &mut Acc) -
}
Ok(Event::Eof) => break,
Ok(Event::Start(e)) => {
if state.frames.is_empty() {
let is_root = state.frames.is_empty();
if is_root {
if root_count >= 1 {
out.malformed = Some("more than one document element".to_string());
break;
@@ -1139,11 +1165,13 @@ pub(crate) fn scan_part(part: &str, text: &str, role: PartRole, acc: &mut Acc) -
let decls = declarations(&attrs);
state.declared.push(decls);
note_unresolved_element(&mut state, &mut id, &[]);
record_root_profile(&mut state, is_root, &id);
let is_alt = enter_alt(&mut state, &id, part, acc);
let branch_prev = assign_alt_branch(&mut state, &id);
let branch_prev = assign_alt_branch(&mut state, &id, &attrs, reader.resolver(), &[]);
push_unknown_prefix(&mut out, &state.declared, &[], id.unknown.as_deref());
check_prefixes(&state.declared, &attrs, reader.resolver(), (&[], complete_entities.as_ref().map(|_| &entity_decls)), &mut out);
collect_ink_content_part(&id, &attrs, reader.resolver(), &mut out, acc.limits.facts);
check_dml_coordinates(&state, &id, &attrs, part, &mut out, acc);
if !was_suppressed {
collect_refs(&id, &attrs, reader.resolver(), &mut out, acc.limits.facts, &mut state.refs_capped);
collect_content_part(&id, &attrs, reader.resolver(), &mut out.content_parts, acc.limits.facts, &mut out.content_part_capped);
@@ -1161,11 +1189,18 @@ pub(crate) fn scan_part(part: &str, text: &str, role: PartRole, acc: &mut Acc) -
);
check_para_ids(&mut state, &id, &attrs, reader.resolver(), role, part, acc);
}
let frame = Frame { alt: is_alt, suppressed: was_suppressed, alt_branch_prev: branch_prev, ..frame_for(&id) };
let frame = Frame {
alt: is_alt,
suppressed: was_suppressed,
alt_branch_prev: branch_prev,
in_custom_geometry: in_custom_geometry(&state, &id),
..frame_for(&id)
};
state.frames.push(frame);
}
Ok(Event::Empty(e)) => {
if state.frames.is_empty() {
let is_root = state.frames.is_empty();
if is_root {
if root_count >= 1 {
out.malformed = Some("more than one document element".to_string());
break;
@@ -1181,11 +1216,13 @@ pub(crate) fn scan_part(part: &str, text: &str, role: PartRole, acc: &mut Acc) -
let was_suppressed = state.alt_depth > 0;
let decls = declarations(&attrs);
note_unresolved_element(&mut state, &mut id, &decls);
record_root_profile(&mut state, is_root, &id);
let is_alt = enter_alt(&mut state, &id, part, acc);
let branch_prev = assign_alt_branch(&mut state, &id);
let branch_prev = assign_alt_branch(&mut state, &id, &attrs, reader.resolver(), &decls);
push_unknown_prefix(&mut out, &state.declared, &decls, id.unknown.as_deref());
check_prefixes(&state.declared, &attrs, reader.resolver(), (&decls, complete_entities.as_ref().map(|_| &entity_decls)), &mut out);
collect_ink_content_part(&id, &attrs, reader.resolver(), &mut out, acc.limits.facts);
check_dml_coordinates(&state, &id, &attrs, part, &mut out, acc);
if !was_suppressed {
collect_refs(&id, &attrs, reader.resolver(), &mut out, acc.limits.facts, &mut state.refs_capped);
collect_content_part(&id, &attrs, reader.resolver(), &mut out.content_parts, acc.limits.facts, &mut out.content_part_capped);
@@ -1448,11 +1485,20 @@ fn enter_alt(state: &mut State, id: &ElemId, part: &str, acc: &mut Acc) -> bool
// An `AlternateContent` of unresolved namespace may be the markup-compatibility one: it is treated as that,
// so its branches are skipped exactly as the literal spelling's are (nothing in them is established).
let is_alt = id.local == "AlternateContent" && (id.ns == Some(NS_MC.as_bytes()) || id.unresolved);
let is_mc = id.ns == Some(NS_MC.as_bytes());
let is_alt = id.local == "AlternateContent" && (is_mc || id.unresolved);
if is_alt {
state.alt_depth += 1;
state.alt_seq += 1;
state.alt_stack.push(AltCtx { seq: state.alt_seq, branch: 0 });
state.alt_stack.push(AltCtx {
seq: state.alt_seq,
branch: 0,
is_mc,
choice_seen: false,
selected_seen: false,
selection_unresolved: !is_mc,
in_selected_branch: false,
});
if !state.alt_noted {
acc.note(format!("{part} contains mc:AlternateContent; its contents were skipped"));
state.alt_noted = true;
@@ -1505,6 +1551,8 @@ fn frame_for(id: &ElemId) -> Frame {
},
is_sdt_content: w && local == "sdtContent",
is_custom_xml: w && local == "customXml",
in_custom_geometry: false,
is_path_lst: id.a() && local == "pathLst",
tc_has_block: false,
tc_known_block: false,
tc_unresolved_candidate: false,
@@ -1946,6 +1994,405 @@ fn check_header_source(state: &mut State, id: &ElemId, role: PartRole, part: &st
}
}
/// Schema-defined integer bounds for DrawingML custom geometry types (`dml-main.xsd`).
/// `ST_CoordinateUnqualified` (§20.1.10.19): `i32::MIN * 12_700 ..= i32::MAX * 12_700`.
const DML_COORD_MIN: i64 = -27_273_042_329_600;
const DML_COORD_MAX: i64 = 27_273_042_316_900;
/// `ST_Angle` (§20.1.10.3): `xsd:int`.
const DML_ANGLE_MIN: i64 = i32::MIN as i64;
const DML_ANGLE_MAX: i64 = i32::MAX as i64;
/// Schema lexical domains and integer bounds used by the custom geometry types in `dml-main.xsd`.
#[derive(Clone, Copy)]
enum CoordKind {
/// `ST_PositiveCoordinate` (§20.1.10.41, path dimensions): integer only, `0..=27273042316900`.
PositiveCoordinate,
/// `ST_AdjCoordinate` (§20.1.10.2, coordinates/radii): `ST_CoordinateUnqualified`
/// (`-27273042329600..=27273042316900`), `ST_UniversalMeasure`, or `ST_GeomGuideName`.
AdjCoordinate,
/// `ST_AdjAngle` (§20.1.10.1, angles): `ST_Angle` (`xsd:int`, `-2147483648..=2147483647`)
/// or `ST_GeomGuideName`.
AdjAngle,
}
impl CoordKind {
fn allows_guide_name(self) -> bool {
matches!(self, Self::AdjCoordinate | Self::AdjAngle)
}
fn int_in_range(self, value: i64) -> bool {
match self {
Self::PositiveCoordinate => (0..=DML_COORD_MAX).contains(&value),
Self::AdjCoordinate => (DML_COORD_MIN..=DML_COORD_MAX).contains(&value),
Self::AdjAngle => (DML_ANGLE_MIN..=DML_ANGLE_MAX).contains(&value),
}
}
}
/// Classification of a custom geometry attribute value against its lexical domain.
#[derive(Clone, Copy, PartialEq, Eq)]
enum CoordLiteral {
/// Valid in-range integer, or (for adjustable attributes) a non-numeric guide name or
/// universal measure.
Valid,
/// Measured-refused decimal-fraction spelling (#8231, Word for Mac 16.114.4, 2026-12-02):
/// raw XML attribute source matching `[ ]*-?[0-9]+\.[0-9]+[ ]*` with an `i64`-representable
/// whole part.
MeasuredDecimalFraction,
/// Any other invalid numeric literal (unmeasured signs such as `+`, non-space whitespace
/// padding, entity/character-reference-encoded spellings, empty/whitespace-only, lone sign,
/// lone dot, leading/trailing dot, scientific notation, integer outside its schema type's
/// bounds or whole part outside `i64` range, or non-integer on an integer-only type).
OtherInvalid,
}
/// Return `(raw_source, normalized)` for an unprefixed attribute by exact name.
///
/// `raw_source` is the undecoded UTF-8 attribute slice from the XML source (preserving character
/// references, entity references, and literal `\t`/`\r`/`\n` before XML 1.0 attribute-value
/// normalization), while `normalized` is `Some` when XML 1.0 normalization succeeds and `None`
/// when normalization fails (for example, on a DOCTYPE-declared or unresolvable entity reference).
fn dml_attr_values<'a>(attrs: &'a [Attribute<'a>], name: &[u8]) -> Option<(&'a str, Option<String>)> {
let attr = attrs.iter().find(|a| a.key.as_ref() == name)?;
let raw_source = std::str::from_utf8(attr.value.as_ref()).ok()?;
let normalized = attr.normalized_value(quick_xml::XmlVersion::Implicit1_0).ok().map(std::borrow::Cow::into_owned);
Some((raw_source, normalized))
}
/// Whether `raw_source` (undecoded, unnormalized XML attribute value) belongs to the
/// measured-refused decimal-fraction lexical set (#8231, Word for Mac 16.114.4, 2026-12-02):
/// optional surrounding ASCII spaces (`' '`), optional leading `-`, one or more ASCII digits,
/// `.`, one or more ASCII digits, with an `i64`-representable signed whole part.
///
/// Unmeasured spellings — `+`-prefixed fractions, non-space whitespace (`\t`, `\r`, `\n`,
/// non-ASCII spaces), character-reference or entity encodings, exponent forms, leading/trailing
/// dot forms, empty/whitespace-only values, and out-of-`i64`-range whole parts — return `false`
/// and never take the `Error` / `Observed` path.
fn is_measured_decimal_fraction(raw_source: &str) -> bool {
let trimmed = raw_source.trim_matches(' ');
let Some((signed_whole, frac)) = trimmed.split_once('.') else { return false };
let whole = signed_whole.strip_prefix('-').unwrap_or(signed_whole);
!whole.is_empty()
&& !frac.is_empty()
&& whole.chars().all(|c| c.is_ascii_digit())
&& frac.chars().all(|c| c.is_ascii_digit())
&& signed_whole.parse::<i64>().is_ok()
}
/// Classify unqualified numeric literals using both the raw XML attribute source and its
/// XML 1.0 normalized value. Other tokens in adjustable attributes may be guide names
/// (including `3cd4`), or a unit-qualified `ST_UniversalMeasure` for coordinates.
/// Values whose XML 1.0 normalization failed (such as DOCTYPE-declared or unresolvable entity
/// references) classify as [`CoordLiteral::OtherInvalid`] so they reach the Warning path using
/// their raw text and never enter the `Error` / `Observed` path.
fn classify_dml_coord(raw_source: &str, normalized: Option<&str>, kind: CoordKind) -> CoordLiteral {
let Some(normalized) = normalized else {
return CoordLiteral::OtherInvalid;
};
let value = normalized.trim_matches([' ', '\t', '\r', '\n']);
if let Ok(int_value) = value.parse::<i64>() {
return if kind.int_in_range(int_value) { CoordLiteral::Valid } else { CoordLiteral::OtherInvalid };
}
if is_measured_decimal_fraction(raw_source) {
return CoordLiteral::MeasuredDecimalFraction;
}
let unsigned = value.strip_prefix(['+', '-']).unwrap_or(value);
let numeric =
unsigned.is_empty() || unsigned == "." || (unsigned.starts_with(|c: char| c.is_ascii_digit() || c == '.') && value.parse::<f64>().is_ok());
if kind.allows_guide_name() && !numeric { CoordLiteral::Valid } else { CoordLiteral::OtherInvalid }
}
/// The parser keeps each custom geometry scope even inside AlternateContent.
fn in_custom_geometry(state: &State, id: &ElemId) -> bool {
observation_contract! {
rules: "-";
collections: "field.frames*1";
scope: "custom geometry ancestry of the current XML event";
loss: "XML event/depth budget";
fallback: "use ancestry of events already scanned";
package_loss: "independent";
}
(id.a() && id.local == "custGeom") || state.frames.last().is_some_and(|frame| frame.in_custom_geometry)
}
/// Observed-Error custom geometry attributes (#8231): only measured decimal-fraction spellings in
/// `wR`/`hR` on `a:arcTo` (Transitional or Strict DrawingML namespace) have desktop consumer
/// refusal measurements (Word for Mac 16.114.4, 2026-12-02).
fn is_observed_decimal_attr(local: &str, attr: &str) -> bool {
local == "arcTo" && matches!(attr, "wR" | "hR")
}
/// Schema-typed custom geometry attributes of CT_Path2D, CT_Path2DArcTo, CT_AdjPoint2D,
/// CT_GeomRect, CT_XYAdjustHandle, CT_PolarAdjustHandle and CT_ConnectionSite in the model.
/// Entries outside [`is_observed_decimal_attr`] (and unmeasured invalid literals on any entry)
/// are unmeasured and graded Warning / MsDocumented.
fn dml_coord_spec(local: &str, is_path: bool) -> &'static [(&'static str, CoordKind)] {
use CoordKind::{AdjAngle, AdjCoordinate, PositiveCoordinate};
match local {
"arcTo" => &[("wR", AdjCoordinate), ("hR", AdjCoordinate), ("stAng", AdjAngle), ("swAng", AdjAngle)],
"pt" | "pos" => &[("x", AdjCoordinate), ("y", AdjCoordinate)],
"rect" => &[("l", AdjCoordinate), ("t", AdjCoordinate), ("r", AdjCoordinate), ("b", AdjCoordinate)],
"ahXY" => &[("minX", AdjCoordinate), ("maxX", AdjCoordinate), ("minY", AdjCoordinate), ("maxY", AdjCoordinate)],
"ahPolar" => &[("minR", AdjCoordinate), ("maxR", AdjCoordinate), ("minAng", AdjAngle), ("maxAng", AdjAngle)],
"cxn" => &[("ang", AdjAngle)],
"path" if is_path => &[("w", PositiveCoordinate), ("h", PositiveCoordinate)],
_ => &[],
}
}
/// Root namespace profile of the part currently being scanned.
#[derive(Clone, Copy, Default, PartialEq, Eq)]
enum PartProfile {
/// Root element namespace resolved to a Transitional (non-Strict) URI.
Transitional,
/// Root element namespace resolved to a Strict OOXML URI (`http://purl.oclc.org/ooxml/...`).
Strict,
/// Root element namespace could not be resolved by the scanner (for example, entity-obscured
/// `xmlns`, undeclared prefix, or no namespace binding).
#[default]
Unresolved,
}
/// Record the namespace profile of this part's root element.
fn record_root_profile(state: &mut State, is_root: bool, id: &ElemId) {
if is_root {
state.part_profile = match id.ns {
Some(ns) if !id.unresolved && is_strict_ooxml_ns(ns) => PartProfile::Strict,
Some(ns) if !id.unresolved && !ns.is_empty() => PartProfile::Transitional,
_ => PartProfile::Unresolved,
};
}
}
/// Whether a namespace URI belongs to the Strict OOXML family (`http://purl.oclc.org/ooxml/...`).
fn is_strict_ooxml_ns(ns: &[u8]) -> bool {
ns.starts_with(b"http://purl.oclc.org/ooxml/")
}
/// Whether `ns` is an exact full namespace URI proven by a Word measurement to be rejected as an
/// `mc:Choice/@Requires` capability without confounding MCE rejection.
///
/// Currently always returns `false`: no capability is populated by inference.
fn is_unsupported_word_mce_capability(ns: &[u8]) -> bool {
let _ = ns;
false
}
/// Whether `ns` is an exact full namespace URI known to be supported by Word as an
/// `mc:Choice/@Requires` capability.
///
/// The measured anchor is `http://schemas.microsoft.com/office/word/2010/wordprocessingShape`
/// (`wps`, corpus document `d60c276dc845` and Word for Mac 16.114.4 context probes).
/// The remaining entries are Word's own main WordprocessingML namespace (`w`) and the complete
/// URIs of Word's shipped MCE capability namespaces (`wordprocessingGroup`,
/// `wordprocessingCanvas`, `wordprocessingInk`, `wordprocessingDrawing`, 2010/2012
/// WordprocessingML, and 2010/2012 DrawingML extensions) that Word resolves as `Requires`
/// capabilities.
///
/// Match by exact URI equality only — closed list, never prefix or namespace-family matching.
/// Additions require a Word measurement or a Word-produced document showing the `Requires` value.
fn is_word_mce_capability(ns: &[u8]) -> bool {
matches!(
ns,
// WordprocessingML main namespace (w).
b"http://schemas.openxmlformats.org/wordprocessingml/2006/main"
// Word 2010 shapes (wps — measured anchor).
| b"http://schemas.microsoft.com/office/word/2010/wordprocessingShape"
// Word 2010 shape groups, drawing canvas, ink, and drawing extensions (wpg, wpc, wpi, wp14).
| b"http://schemas.microsoft.com/office/word/2010/wordprocessingGroup"
| b"http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas"
| b"http://schemas.microsoft.com/office/word/2010/wordprocessingInk"
| b"http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing"
// Word 2010 and 2012 WordprocessingML extensions (w14, w15).
| b"http://schemas.microsoft.com/office/word/2010/wordml"
| b"http://schemas.microsoft.com/office/word/2012/wordml"
// Office 2010 and 2012 DrawingML extensions (a14, pic14, dgm14, cdr14, a15, c15, cs).
| b"http://schemas.microsoft.com/office/drawing/2010/main"
| b"http://schemas.microsoft.com/office/drawing/2010/picture"
| b"http://schemas.microsoft.com/office/drawing/2010/diagram"
| b"http://schemas.microsoft.com/office/drawing/2010/chartDrawing"
| b"http://schemas.microsoft.com/office/drawing/2012/main"
| b"http://schemas.microsoft.com/office/drawing/2012/chart"
| b"http://schemas.microsoft.com/office/drawing/2012/chartStyle"
)
}
/// Three-state evaluation outcome of an `mc:Choice/@Requires` attribute.
#[derive(Clone, Copy, PartialEq, Eq)]
enum ChoiceState {
/// Every required prefix resolved to an exact URI in [`is_word_mce_capability`] (or `Requires`
/// was absent — measured in Word for Mac probe `r1`).
Supported,
/// At least one required prefix resolved to a URI not on the allowlist, could not be resolved
/// (undeclared, malformed, or entity-obscured), or `Requires` itself was empty or unreadable.
/// Makes the whole enclosing `mc:AlternateContent`'s selection uncertain.
Unresolved,
/// Reserved for capabilities a Word measurement proves Word rejects without confounding MCE
/// rejection. Never populated by inference; [`is_unsupported_word_mce_capability`] always
/// returns `false` today.
Unsupported,
}
/// Evaluate a single prefix token from `mc:Choice/@Requires` against [`is_word_mce_capability`].
fn prefix_requires_state(prefix: &str, res: &NamespaceResolver, declared: &[Vec<String>], own_decls: &[String]) -> ChoiceState {
observation_contract! {
rules: "-";
collections: "type.Vec*1";
scope: "namespace scope for one mc:Choice Requires prefix";
loss: "XML event/depth budget; entity-obscured xmlns declaration";
fallback: "treat unlisted, undeclared, malformed, or entity-obscured prefix bindings as unresolved rather than supported or unsupported";
package_loss: "independent";
}
if prefix.is_empty() || prefix.as_bytes().contains(&b':') {
return ChoiceState::Unresolved;
}
if nearest_binding(declared, own_decls, prefix) == Binding::Unresolved {
return ChoiceState::Unresolved;
}
let qname = format!("{prefix}:_");
match res.resolve_attribute(QName(qname.as_bytes())).0 {
ResolveResult::Bound(Namespace(ns)) if is_word_mce_capability(ns) => ChoiceState::Supported,
ResolveResult::Bound(Namespace(ns)) if is_unsupported_word_mce_capability(ns) => ChoiceState::Unsupported,
_ => ChoiceState::Unresolved,
}
}
/// Evaluate an `mc:Choice` element's `Requires` attribute into [`ChoiceState`]:
/// - Missing `Requires` is [`ChoiceState::Supported`] (measured in Word for Mac probe `r1`:
/// fractional radii inside an `mc:Choice` with no `Requires` attribute are refused).
/// - If every whitespace-delimited prefix resolves to an exact URI in [`is_word_mce_capability`],
/// returns [`ChoiceState::Supported`].
/// - If any prefix resolves to a URI in [`is_unsupported_word_mce_capability`] (currently none),
/// returns [`ChoiceState::Unsupported`].
/// - Otherwise (any unlisted URI, undeclared/malformed prefix, empty `Requires`, or
/// entity-obscured `Requires` / `xmlns`), returns [`ChoiceState::Unresolved`].
fn choice_requires_state(attrs: &[Attribute], res: &NamespaceResolver, declared: &[Vec<String>], own_decls: &[String]) -> ChoiceState {
observation_contract! {
rules: "-";
collections: "type.Vec*1";
scope: "mc:Choice Requires attribute evaluation in current namespace scope";
loss: "XML event/depth budget; entity-obscured Requires or xmlns declaration";
fallback: "withhold Error by returning Unresolved when Requires or any prefix binding is unlisted, empty, undeclared, or unreadable";
package_loss: "independent";
}
let Some(attr) = attrs.iter().find(|a| a.key.as_ref() == b"Requires") else {
return ChoiceState::Supported;
};
let Ok(value) = attr.normalized_value(quick_xml::XmlVersion::Implicit1_0) else {
return ChoiceState::Unresolved;
};
let mut saw_prefix = false;
let mut unresolved = false;
for prefix in value.split([' ', '\t', '\r', '\n']).filter(|prefix| !prefix.is_empty()) {
saw_prefix = true;
match prefix_requires_state(prefix, res, declared, own_decls) {
ChoiceState::Supported => {}
ChoiceState::Unsupported => return ChoiceState::Unsupported,
ChoiceState::Unresolved => unresolved = true,
}
}
if !saw_prefix || unresolved { ChoiceState::Unresolved } else { ChoiceState::Supported }
}
/// Enclosing `mc:AlternateContent` selection status for custom geometry checks.
#[derive(Clone, Copy, PartialEq, Eq)]
enum DmlBranchSelection {
/// Outside every `mc:AlternateContent`, or inside the Supported-selected branch of every
/// enclosing `mc:AlternateContent` (including a choice-less `mc:Fallback`).
Selected,
/// Inside a definitively unselected branch of at least one enclosing `mc:AlternateContent`.
Unselected,
/// At least one enclosing `AlternateContent` has unresolved selection (for example, an
/// unlisted `Requires` capability, a `Fallback` behind a Choice, or an entity-obscured
/// `xmlns` / `Requires`) and none is definitively unselected.
Unresolved,
}
/// Determine whether the current XML event sits in an established Supported-selected branch, a
/// definitively unselected branch, or an unresolved `AlternateContent` context.
fn dml_branch_selection(state: &State) -> DmlBranchSelection {
observation_contract! {
rules: "-";
collections: "field.alt_stack*1";
scope: "enclosing mc:AlternateContent branch selection for the current XML event";
loss: "XML event/depth budget";
fallback: "evaluate enclosing AlternateContent frames already scanned";
package_loss: "independent";
}
let mut unresolved = false;
for ctx in &state.alt_stack {
if ctx.is_mc && !ctx.selection_unresolved {
if !ctx.in_selected_branch {
return DmlBranchSelection::Unselected;
}
} else {
unresolved = true;
}
}
if unresolved { DmlBranchSelection::Unresolved } else { DmlBranchSelection::Selected }
}
/// Report invalid custom geometry literals from the XML events in every branch.
/// Measured Errors require ALL of: Transitional part profile + Supported-selected branch (bare
/// drawing, Supported `mc:Choice`, or choice-less `mc:Fallback` at every enclosing level) +
/// measured fractional geometry (`a:arcTo` `wR`/`hR`). Everything else is Warning, buffered in
/// `out` (bounded to one entry past the per-rule finding cap) and flushed after all XML parts
/// have been scanned so Warnings cannot crowd out measured Errors at the cap.
///
/// Warning grade precedence for measured fractional geometry:
/// 1. Strict part profile OR definitively unselected enclosing `mc:AlternateContent` branch
/// -> `Warning` / `Observed` (`DmlWarnEvidence::ObservedContext`).
/// 2. Unresolved part profile OR unresolved `AlternateContent` selection (only in a non-Strict
/// part with no definitively unselected enclosing branch)
/// -> `Warning` / `MsDocumented` (`DmlWarnEvidence::Unmeasured`).
fn check_dml_coordinates(state: &State, id: &ElemId, attrs: &[Attribute], part: &str, out: &mut PartScan, acc: &mut Acc) {
observation_contract! {
rules: "DML-COORDINATE";
collections: "field.dml_coordinate_warnings*2,field.frames*1";
scope: "source-local custom geometry attribute values";
loss: "source unavailable or malformed; XML event/depth budget";
fallback: "measured decimal-fraction spellings ([ ]*-?[0-9]+\\.[0-9]+[ ]* raw XML source) in a:arcTo wR/hR (Transitional or Strict DrawingML namespace) receive Error with Observed evidence only when the part profile is Transitional and every enclosing AlternateContent is Supported-selected (bare drawing, Supported Choice, or choice-less Fallback); Warning grade precedence: Strict parts and definitively unselected enclosing AlternateContent branches report Warning with Observed evidence, while unresolved part profiles and unresolved AlternateContent selections report Warning with MsDocumented evidence only in a non-Strict part with no definitively unselected enclosing branch; other invalid schema-typed custom geometry attributes and unmeasured or unresolvable lexical classes receive Warning with MsDocumented evidence; measured Errors are emitted ahead of Warnings; report invalid values in the scanned prefix";
package_loss: "independent";
}
if !id.a() || !in_custom_geometry(state, id) {
return;
}
if id.local == "custGeom" {
acc.ran_dml_coordinate();
}
let is_path = id.local == "path"
&& state.frames.iter().rev().find(|frame| !frame.alt && frame.alt_branch_prev.is_none()).is_some_and(|frame| frame.is_path_lst);
for &(attr_name, kind) in dml_coord_spec(&id.local, is_path) {
let Some((raw_source, normalized)) = dml_attr_values(attrs, attr_name.as_bytes()) else { continue };
let warning_evidence = match classify_dml_coord(raw_source, normalized.as_deref(), kind) {
CoordLiteral::Valid => continue,
CoordLiteral::MeasuredDecimalFraction if is_observed_decimal_attr(&id.local, attr_name) => {
match (state.part_profile, dml_branch_selection(state)) {
(PartProfile::Transitional, DmlBranchSelection::Selected) => {
acc.add_dml_coordinate_error(
part.to_string(),
format!("a:{} attribute {attr_name} has invalid coordinate or angle value {raw_source:?} in {part}", id.local),
);
continue;
}
(PartProfile::Strict, _) | (_, DmlBranchSelection::Unselected) => DmlWarnEvidence::ObservedContext,
(PartProfile::Transitional, DmlBranchSelection::Unresolved)
| (PartProfile::Unresolved, DmlBranchSelection::Selected | DmlBranchSelection::Unresolved) => DmlWarnEvidence::Unmeasured,
}
}
CoordLiteral::MeasuredDecimalFraction | CoordLiteral::OtherInvalid => DmlWarnEvidence::Unmeasured,
};
// Save one extra Warning past the cap to exercise the accumulator's truncation path
// while emitting measured Errors first across all XML parts.
if out.dml_coordinate_warnings.len() <= acc.limits.findings_per_rule {
out.dml_coordinate_warnings.push((
warning_evidence,
format!("a:{} attribute {attr_name} has invalid coordinate or angle value {raw_source:?} in {part}", id.local),
));
}
}
}
/// The AlternateContent ancestry of one `w14:paraId` occurrence: one
/// `(block, branch instance)` pair per enclosing `mc:AlternateContent`
/// block, outermost first. Branch instance 0 means the occurrence is
@@ -2072,6 +2519,21 @@ struct AltCtx {
/// no branch element, otherwise the instance number assigned to
/// the enclosing `mc:Choice` / `mc:Fallback` element.
branch: u32,
/// Whether the opening element resolved to the actual Markup Compatibility namespace (`NS_MC`).
is_mc: bool,
/// Whether this block has already seen any direct `Choice` child (`mc:Choice` or unresolved).
/// `mc:Fallback` is selected only when no `Choice` precedes it.
choice_seen: bool,
/// Whether this `mc:AlternateContent` block has already seen its established selected branch
/// (the first `Supported` `mc:Choice`, or `mc:Fallback` when no `Choice` is present).
selected_seen: bool,
/// Whether branch selection for this block is uncertain (the `AlternateContent` element's
/// namespace could not be resolved, an earlier direct `Choice`/`Fallback` before selection
/// was unresolved, a `Choice` before selection evaluated to [`ChoiceState::Unresolved`], or
/// `mc:Fallback` appeared behind a non-selected `Choice`).
selection_unresolved: bool,
/// Whether the scanner is currently inside this block's established selected branch.
in_selected_branch: bool,
}
/// The `w14:paraId` / `w14:textId` family (MS-DOCX §2.6.2.3 and
@@ -2155,10 +2617,10 @@ fn check_para_ids(state: &mut State, id: &ElemId, attrs: &[Attribute], res: &Nam
/// are different alternatives — and returns the block's previous
/// branch value, which the caller restores when the branch element
/// closes (its frame carries it; an empty element restores at once).
fn assign_alt_branch(state: &mut State, id: &ElemId) -> Option<u32> {
fn assign_alt_branch(state: &mut State, id: &ElemId, attrs: &[Attribute], res: &NamespaceResolver, own_decls: &[String]) -> Option<(u32, bool)> {
observation_contract! {
rules: "-";
collections: "field.alt_stack*1,field.frames*1";
collections: "field.alt_stack*1,field.declared*1,field.frames*1";
scope: "source-local bounded extraction; no implicit document owner";
loss: "source unavailable or malformed; XML event/depth budget; category allocation cap";
fallback: "retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set";
@@ -2175,15 +2637,54 @@ fn assign_alt_branch(state: &mut State, id: &ElemId) -> Option<u32> {
return None;
}
let ctx = state.alt_stack.last_mut()?;
let prev = ctx.branch;
let prev = (ctx.branch, ctx.in_selected_branch);
state.alt_branch_seq += 1;
ctx.branch = state.alt_branch_seq | if unresolved { BRANCH_UNKNOWN } else { 0 };
if id.local == "Choice" {
ctx.choice_seen = true;
}
if ctx.selection_unresolved {
ctx.in_selected_branch = false;
} else if ctx.is_mc && id.ns == Some(NS_MC.as_bytes()) {
match id.local.as_str() {
"Choice" if !ctx.selected_seen => match choice_requires_state(attrs, res, &state.declared, own_decls) {
ChoiceState::Supported => {
ctx.selected_seen = true;
ctx.in_selected_branch = true;
}
ChoiceState::Unsupported => {
ctx.in_selected_branch = false;
}
ChoiceState::Unresolved => {
ctx.selection_unresolved = true;
ctx.in_selected_branch = false;
}
},
"Fallback" if !ctx.selected_seen => {
if !ctx.choice_seen {
ctx.selected_seen = true;
ctx.in_selected_branch = true;
} else {
ctx.selection_unresolved = true;
ctx.in_selected_branch = false;
}
}
_ => {
ctx.in_selected_branch = false;
}
}
} else if unresolved {
if !ctx.selected_seen {
ctx.selection_unresolved = true;
}
ctx.in_selected_branch = false;
}
Some(prev)
}
/// Restore the innermost block's branch value saved by
/// `assign_alt_branch` when its branch element closes.
fn restore_branch(state: &mut State, prev: Option<u32>) {
fn restore_branch(state: &mut State, prev: Option<(u32, bool)>) {
observation_contract! {
rules: "-";
collections: "field.alt_stack*1";
@@ -2193,10 +2694,11 @@ fn restore_branch(state: &mut State, prev: Option<u32>) {
package_loss: "independent";
}
if let Some(prev) = prev
if let Some((prev_branch, prev_selected)) = prev
&& let Some(ctx) = state.alt_stack.last_mut()
{
ctx.branch = prev;
ctx.branch = prev_branch;
ctx.in_selected_branch = prev_selected;
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -530,6 +530,7 @@ cover this part of #3614. PDF layout, saved content and format-readiness estimat
| 2026-10-29 | trivial | PDF figure tagging reuses requested paragraph prefixes within each export (#3614); alternative text, decorative roles and drawing/page order stay unchanged; synthetic controls, readiness estimates unchanged. |
| 2026-10-28 | trivial | Built-in heading styles (`heading 1`…`heading 9`) have their outline level when `styles.xml` leaves out `w:outlineLvl`, as in Word: their headings show in the Navigation pane (#4696) |
| 2026-10-29 | trivial | DOCX: comments.xml is read before footnotes and endnotes, so a comment range inside a note keeps its comment (it was dropped) (#4548) |
| 2026-10-29 | trivial | DOCX: a run marked complex script (`w:cs`) takes bold and italic only from `w:bCs` and `w:iCs` (run, styles, defaults), no longer from `w:b` and `w:i`, so Thai that a file sets `<w:b/><w:cs/>` without `w:bCs` is drawn plain as in Word. Runs not marked `w:cs` still borrow the Latin values; the complex-script size still borrows `w:sz` (#4197). Measured in Word for Windows; `complex_script_inheritance::complex_script_runs_take_bold_and_italic_only_from_bcs_and_ics` |
| 2026-10-28 | trivial | #4658: bound Markdown reference-label rejection work, preserving literal source and ordinary link matching |
| 2026-10-17 | trivial | macOS launch arguments (`-psn_*`, `-NS*`, `-Apple*`) are no longer opened as files; a file that fails to open (command line, open event, drop) names the file and the cause on the status bar and in the log (#1103) |
| 2026-10-29 | trivial | HTML import keeps preformatted lines with CR, CRLF or LF input newlines (#4810); numeric character references retain their separate meaning; readiness estimates unchanged. |
@@ -541,7 +542,6 @@ cover this part of #3614. PDF layout, saved content and format-readiness estimat
| 2026-10-17 | trivial | Encryption rows: Standard (Word 2007, AES-ECB) encrypted packages open with a password, also when named `.doc`/`.dot`; AES headers in Word 97-2003 files are outside the public spec and refused (gap 9). The duplicate combined `.docx`/`.doc` row is removed; the `.doc` row reads 🟡 ~60% (it opens XOR/RC4/RC4 CryptoAPI); hours 2–4 → 1–2 and 4–6 → 1–2 (left: checks against Word-written files); total re-summed from the rows, 175–287 h |
| 2026-10-25 | trivial | Repeated DOCX style IDs: repeated save/reopen regression for whole-definition replacement. |
| 2026-10-25 | trivial | Arabic list labels: `arabicAlpha` and `arabicAbjad` draw the 28 Arabic letters (alphabetical and abjad order), doubling past the last letter; Hebrew, Hindi, Thai and Vietnamese still show decimal (`doc::section::tests::arabic_letters_count_in_both_orders`) |
| 2026-10-29 | trivial | DOCX: a run marked complex script (`w:cs`) takes bold and italic only from `w:bCs` and `w:iCs` (run, styles, defaults), no longer from `w:b` and `w:i`, so Thai that a file sets `<w:b/><w:cs/>` without `w:bCs` is drawn plain as in Word. Runs not marked `w:cs` still borrow the Latin values; the complex-script size still borrows `w:sz` (#4197). Measured in Word for Windows; `complex_script_inheritance::complex_script_runs_take_bold_and_italic_only_from_bcs_and_ics` |
| 2026-10-26 | trivial | DOCX: a package spelling `WORD/FONTTABLE.XML` and its fonts in another casing than the relationships still loads and saves its embedded fonts (the font table is found by its stored spelling), and a save that removes personal information escapes the attribute values of a kept glossary (`w:val='Say "hi"'` stays well-formed) (#3872 review) |
| 2026-10-23 | trivial | cu20we: preserve and render outline caps across DOCX/VML, screen and PDF; synthetic regressions; readiness estimates unchanged |
| 2026-10-23 | trivial | `.doc` reader logs what its copy budget leaves out (floating objects, link targets, alt text, Prm formatting), once a kind per document (#3692) |
+14 -2
View File
File diff suppressed because one or more lines are too long

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