Compare commits

...
Author SHA1 Message Date
FredApps f7db2c5845 Merge remote-tracking branch 'origin/main' into tc14-6913 2026-11-26 17:19:13 +07:00
skylar taylor-barrick 68c024a624 Nightly: open the Launcher's files rather than its --, and stop blocking a refused launch on macOS (#7849)
Nightly launch fix under Skylar's Exec 454: the Launcher's trailing `--` no longer reaches the file list, and a refused launch no longer blocks on macOS (the reason goes to stderr and the app exits 2). Two CodeRabbit findings folded in: documents keep command-line order across the separator, and a document named like a launch argument (`-NS…`, `-psn_`, `-Apple…`) survives because the split comes before the strip.
2026-11-26 04:04:23 -06:00
FredApps 5239535f19 Merge remote-tracking branch 'origin/main' into tc14-6913 2026-11-26 16:37:47 +07:00
Lucas Batista Vargas 104556e47d chore: bump craft-libs to 0b8bbaf4c8 and egui to b9770908e0 (#7837) 2026-11-26 08:52:55 +00:00
skylar taylor-barrick 765abcc790 Switch on supervised nightlies on the nightly-signer branch (#7839)
Supervised nightly switch-on, merged under Skylar's explicit Nightly 758 override after green CI, CodeRabbit on this head with no open threads, Sonar passing, and an independent adversarial review with no blockers.
2026-11-25 19:52:59 -06:00
Martin BallandClaude Opus 5.5 39aa564f56 #4134: joined text's later lines clear the shared line when a large word wraps
The area that keeps a continuation's later lines below the shared line now starts just below the first row at the line breaker's row estimate, which is what the breaker tests rows with. The probe's first line can be taller than the real one when a large word fits it but wraps off the narrower shared line, and starting the area below that taller line let the real second line start inside the heading's line. The test adds a 30 pt word at three places that wrap it to the second line, in the body and in a cell.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx
2026-11-26 01:18:06 +00:00
Martin BallandClaude Opus 5.5 4c9614df84 #4134: joined text's first line shares the line again with exact spacing
The area that holds a joined paragraph's later lines below a taller shared
line started just below its first line. The line breaker checks a row
against wrap areas at its own estimate, the mark's font height, which is
taller than an exact line height below it: the first row then met the area
and moved below the shared line. The area now starts below whichever is
taller, so the first line shares the line under every line spacing rule.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx
2026-11-26 01:11:28 +00:00
Martin BallandClaude Opus 5.5 0b09f41983 #4134: joined text's later lines start below a taller shared line; table frames don't join
A paragraph going on from the line of one whose mark is hidden kept only its
first line clear of that line: under a taller heading its second line started
inside the heading's line, back at the left margin. Its later lines now keep
clear of the rest of the shared line, with the room for its bottom border, in
the body and in boxes (cells, headers, text boxes).

The guard against joining a text frame resolves the paragraph with the table's
paragraph formatting, as its layout does, so a frame given by the table style
is placed apart with its list number instead of joining.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 00:59:00 +00:00
Martin BallandClaude Opus 5.5 a44dc74fc0 #7822: Spec, plan and ADR for closing document windows (#7840)
Agreed rules for every close path (window close, File › Close, quit, one-document hosts, automation), who owns the Save prompt, and the order of work: craft-libs hidden root and test kit, repin, then the WordCraft fix. Adds Document window and Save prompt to the glossary.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-26 00:19:22 +00:00
Martin Ball 349d6ee444 Merge remote-tracking branch 'origin/main' into land/4134 2026-11-25 23:09:21 +00:00
skylar taylor-barrick 77a530b179 Use the shared nightly launcher template (#7829)
Renders the plain nightly tar's launcher from craft-common-actions' shared template.

Independent check: dylanmtaylor compared all 14 app launcher PRs byte for byte with the template rendered from the registry (https://github.com/storytold/craft-common-actions/pull/367#issuecomment-7172085284); this head was re-checked against craft-common-actions main 88148a5.
2026-11-25 16:17:53 -06:00
Martin BallandClaude Opus 5.5 4e00d00779 ROADMAP: remove a stray branch-name line from the progress log (#6917)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 20:48:59 +00:00
Martin BallandClaude Opus 5.5 4d70405ab4 Layout: hidden-mark join fixes from review of #6913
- A paragraph moved off the shared line (next column or page) gets its
  own top and bottom border room again (flow.rs `Rooms` were stale).
- Hit testing cuts a line at a joined paragraph only when that paragraph
  still shares the line (`shares_line`), not when its first word wrapped below.
- A cell or header paragraph going on from a hidden mark takes the shared
  line's top as its paragraph origin, so paragraph-anchored drawings follow it.
- A text frame is placed apart: it is not joined, keeps its number.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 18:11:08 +00:00
Lucas Batista Vargas 26b1d89ad2 fix(dialogs): restore table style dialog v0.18.1 layout, preview, and alignment test (#7317) (#7645) 2026-11-25 18:04:13 +00:00
Lucas Batista Vargas a272715194 test(windows): restore #117 window title test and cover root promotion (#7702) 2026-11-25 15:38:40 +00:00
Lucas Batista Vargas ff90488655 test(credits): cover Models table refit in narrowed About dialog (#7646) 2026-11-25 15:38:34 +00:00
Lucas Batista Vargas bc629b7a4f test(control_server): adapt params.token / params.key auth test post-#7101 (#7729) (#7629) 2026-11-25 15:38:28 +00:00
Lucas Batista Vargas 954750790b Dialogs: restore modal shake/nudge animation on backdrop clicks (#7321) (#7332) 2026-11-25 15:38:22 +00:00
Lucas Batista Vargas f587bcb95a fix(keytips): record ribbon menu_button commands and restore language test (#7317) (#7612) 2026-11-25 15:38:16 +00:00
Lucas Batista Vargas b068e1a538 refactor(ui-egui): unify command_input cache loop and test keytip cache behaviour (#7764) (#7573) 2026-11-25 15:38:10 +00:00
Lucas Batista Vargas 9ab9f2f874 Accessibility: return keyboard focus to page on dialog dismissal from non-canvas controls (#7458) (#7467) 2026-11-25 15:38:04 +00:00
Lucas Batista Vargas 231a09761c test(keytips): adapt long QAT multi-digit badge test to craft Keytips (#7733) (#7626) 2026-11-25 15:37:58 +00:00
Lucas Batista Vargas dc12b22371 test(objects): adapt nothing_to_snap_to post-#7101 (#7749) (#7618) 2026-11-25 15:37:50 +00:00
Lucas Batista Vargas b77c55c028 test(dialogs): adapt escape_in_the_browser_leaves_the_dialog_under_it_open post-#7101 (#7754) (#7617) 2026-11-25 15:37:43 +00:00
Lucas Batista Vargas 09465c9fc4 test(ribbon): adapt Styles gallery RTL reading-order test post-#7101 (#7753) (#7616) 2026-11-25 15:37:37 +00:00
Lucas Batista Vargas c8ecea24cf test(file_dialogs): adapt entries_expose_names_selection_and_picking post-#7101 (#7317) (#7613) 2026-11-25 15:37:32 +00:00
Lucas Batista Vargas 2a09d78972 test(keys): restore the_ignored_paste_uses_up_its_paste_modifiers test (#7317) (#7609) 2026-11-25 15:37:26 +00:00
Lucas Batista Vargas b163c0568d test(file_browser): restore a_dialog_closing_into_the_browser_leaves_it_the_keyboard test (#7317) (#7604) 2026-11-25 15:37:20 +00:00
Lucas Batista Vargas 8ed5ddd47b test(ui-egui): restore the_tab_strip_buttons_have_names test (#7317, #1110) (#7577) 2026-11-25 15:37:13 +00:00
Lucas Batista Vargas ea8f665f20 test(ui-egui): restore focus_and_full_screen_view_ask_for_full_screen_once_per_change (#1678) (#7576) 2026-11-25 15:37:06 +00:00
Lucas Batista Vargas c30777bf2a test(ui-egui): restore command_filter_narrows_the_picker_and_add_works test (#7317) (#7574) 2026-11-25 15:36:59 +00:00
Lucas Batista Vargas 34b79b33db test(ui-egui): restore the_ribbon_boxes_name_themselves_for_a_screen_reader test (#7317, #3172) (#7569) 2026-11-25 15:36:53 +00:00
Lucas Batista Vargas f89c52c428 test(ui-egui): restore the_print_button_leads_the_settings_and_is_the_primary_action (#2958) (#7568) 2026-11-25 15:36:47 +00:00
Lucas Batista Vargas 4da5534eb8 test(ui-egui): restore the_plus_button_adds_a_row test (#7317) (#7563) 2026-11-25 15:36:41 +00:00
Lucas Batista Vargas afe332b225 test(engine): restore copy_format_web_alias_respects_user_removal_and_reassignment test (#7317) (#7562) 2026-11-25 15:36:29 +00:00
Lucas Batista Vargas 3ebf69481a test(ui-egui): restore caret_colour_is_not_worked_out_while_the_caret_is_hidden (#299) (#7561) 2026-11-25 15:36:22 +00:00
Lucas Batista Vargas ab014b8fe5 test(engine): restore f11_is_full_screen_and_alt_f1_walks_fields test (#980) (#7317) (#7559) 2026-11-25 15:36:16 +00:00
Lucas Batista Vargas 7951466b8b test(ui-egui): restore a_bordered_table_shows_no_gridlines (#5967) (#7554) 2026-11-25 15:36:08 +00:00
Lucas Batista Vargas d26c7375ff test(ui-egui): restore read_aloud_player_closes_from_title_bar (#1885) (#7553) 2026-11-25 15:35:57 +00:00
Lucas Batista Vargas e3b742f75a test(ui-egui): restore the_full_screen_button_reports_the_commands_own_enabled_state (#7317) (#7552) 2026-11-25 15:35:50 +00:00
Lucas Batista Vargas f847159a29 System clipboard: restore test for empty copy preserving clipboard state (#7317) (#7544) 2026-11-25 15:35:44 +00:00
Lucas Batista Vargas 9409b2fd79 Tests: restore title_stem_omits_nul_from_each_title_source (#7317) (#7543) 2026-11-25 15:35:38 +00:00
Lucas Batista Vargas e2f001b946 Dialogs: restore AutoCorrect filter and Compare options tests (#7317) (#7542) 2026-11-25 15:35:32 +00:00
Lucas Batista Vargas dc5d27cded Default apps: restore test for xdg-mime word types and exclusion of plain text (#7317) (#7541) 2026-11-25 15:35:25 +00:00
Lucas Batista Vargas c56825487f Dialogs insert: restore test for Document Information fields in Field dialog (#7317) (#7537) 2026-11-25 15:35:19 +00:00
Lucas Batista Vargas 4343683da8 Icons: restore test for fitOnePage painting through the SVG registry (#7317) (#7534) 2026-11-25 15:35:12 +00:00
Lucas Batista Vargas 1f65a8e588 Window geometry: restore test for clamping or dropping insane values (#7317) (#7533) 2026-11-25 15:35:06 +00:00
Lucas Batista Vargas bfc160809c Font download: restore test for short window opt-out and close buttons (#7317) (#7530) 2026-11-25 15:35:00 +00:00
Lucas Batista Vargas 3639389be3 Paste picture: restore test for refusing hostile clipboard pictures and files (#7317) (#7529) 2026-11-25 15:34:54 +00:00
Lucas Batista Vargas 37d03a1eb4 Chrome: restore test for clicking AutoSave label to toggle (#3370) (#7317) (#7528) 2026-11-25 15:34:48 +00:00
Lucas Batista Vargas 7fa77df595 DOCX settings merge trials: zoom round-trips and the mail-merge source id (#7524) 2026-11-25 15:34:42 +00:00
Dylan M. Taylor c179a31619 packaging(linux): support co-installable nightly packages (#7746)
Linux nightly packaging by @dylanmtaylor, with the per-app Nightly flavor commits stacked on his branch.

Co-authored-by: Dylan M. Taylor <[email protected]>
2026-11-24 19:00:35 -06:00
Lucas Batista Vargas 6e92d33e07 UI: cache command metadata, hints and keytip tables between idle frames (#7674) (#7719) 2026-11-24 21:51:04 +00:00
Lucas Batista Vargas 4d7100a7f8 test(fonts): adapt installed Arabic font isolation test post-#7101 (#7734) (#7627) 2026-11-24 17:03:26 +00:00
Lucas Batista Vargas 920d9342e7 test(chrome): adapt AutoSave knob RTL mirroring test to craft Switch (#7730) (#7630)
* test(chrome): adapt AutoSave knob RTL mirroring test to craft Switch (#7730)

* test(chrome): drive AutoSave RTL test via ui.language and root_env
2026-11-24 17:03:20 +00:00
Lucas Batista Vargas c11504affa Ribbon: align Table Design › Table Style Options checkboxes in two columns (#7691) (#7695)
* Ribbon: align Table Style Options checkboxes in two columns (#7691)

* Ribbon: widen Table Style Options column gutter while keeping tight rows
2026-11-24 17:03:14 +00:00
Lucas Batista Vargas 604ad56f0a fix(keytips): show legacy menu key hint under slim screen bar without ribbon (#7731) (#7628) 2026-11-24 14:26:12 +00:00
Lucas Batista Vargas 852330e928 fix(chrome): return canvas focus after picking an Undo History row (#7726) (#7632) 2026-11-24 14:25:57 +00:00
Lucas Batista Vargas b5fb29b539 test(dialogs): restore RTL Page Setup oversized margin test (#7722) (#7637)
Closes #7722. Part of #7317.
2026-11-24 14:25:41 +00:00
Lucas Batista Vargas 012d0dd875 test(control_server): adapt per-connection token auth test post-#7101 (#7720) (#7631) 2026-11-24 14:25:28 +00:00
Lucas Batista Vargas 352042d41f Canvas: size Web Layout from PageView's side gutter instead of rail width (#7687) (#7701) 2026-11-24 11:50:56 +00:00
Lucas Batista Vargas 4f6cc31af6 test(dialogs): verify Customize Keyboard empty shortcuts list shows None (#7317) (#7644) 2026-11-24 11:50:50 +00:00
Lucas Batista Vargas 58e52bc962 test(dialogs): restore the_title_bar_close_box_is_the_whole_corner test (#7317) (#7638) 2026-11-24 11:50:45 +00:00
bd3ca8d3ab Layout: a paragraph with a hidden mark is shown on one line with the next one (#3986) (#4134)
Lands #4134 rebased onto main; only docs conflicts were resolved (both sides kept).

Co-Authored-By: Menonro <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FypgCXtSjB6e5jmy9Uq7u8
2026-11-24 08:19:07 +00:00
Lucas Batista Vargas bf2be3cad8 fix(dialogs): adapt chart types tile grid to craft-libs GridZoom API (#7697) (#7698) 2026-11-24 01:50:21 +00:00
aiongg 805fb543fa Merge pull request #7670 from aiongg/repin-next-1123
deps: bump craft-libs pin to next b436ae9925 (shared FontPicker fixes)
2026-11-23 19:42:14 -05:00
Lucas Batista Vargas 73de5b5569 Ribbon: use large 3:2 thumbnails in Table Design › Table Styles gallery (#7317) (#7689)
Table Design › Table Styles (crates/ui-egui/src/ribbon/galleries.rs)
omitted .thumb(ThumbSize::Large) and .aspect(...), unlike sibling Styles
and Style Sets galleries. Gallery therefore fell back to ThumbSize::Medium
with a square aspect ratio, shrinking the 112×74 pt (3:2) table previews
into cramped strips with empty space above and below.

Configure .thumb(ThumbSize::Large).aspect(ThumbAspect::new(3, 2)) to match
table_style_image's 3:2 landscape ratio and v0.18.1's ribbon tile height,
and add a focused regression test in crates/ui-egui/src/ribbon/tests.rs.
2026-11-24 00:37:16 +00:00
Lucas Batista Vargas 5e83839736 Mini toolbar: suppress text labels on Text Highlight Color and Font Color SplitButtons (#7482) (#7511)
- Run mini toolbar members with GroupLevel::Compact and ControlPlace::Ribbon env overrides so SplitButtons suppress button face text labels while retaining tooltips and accessibility, and ComboBox controls size by content.
- Update Grow Font and Shrink Font controls to 24 pt Buttons matching Row 1 control height.
- Re-enable and update mini toolbar regression tests verifying toolbar width constraint (< 350 pt), height alignment, and hover previews.
2026-11-24 00:05:57 +00:00
Lucas Batista Vargas cf161d30a3 Dialogs: compact tile sizing for Insert › Chart type selector (#7456) (#7466)
In Insert › Chart and Change Chart Type dialogs (dialogs_chart.rs),
the chart types TileGrid configured a 3-column gallery without thumbnail
sizing, causing tiles to expand to the default card size (128 pt compact /
160 pt comfortable, resulting in ~132×104 pt cells). This caused the
3-column grid to balloon over ~420 pt in width, crowding the modal dialog.

Configure .thumb_size(ThumbSize::Large).zoom(1.6).aspect(19.0 / 15.0) on
the chart types TileGrid, producing ~76.8×60.6 pt preview pictures in
~85×87 pt cells within a ~280 pt grid, matching pre-refactor parity
(~112×92 pt cells with 76×60 pt preview pictures). Add a regression test
verifying cell and grid bounds.
2026-11-24 00:05:52 +00:00
Lucas Batista Vargas e4633540c0 Ribbon: bind table.selectTable command to Table Layout › Select menu button (#7457) (#7461)
In crates/ui-egui/src/ribbon/table.rs, the Table Layout › Table › Select menu
button previously passed None as its command binding, leaving the menu button
face permanently enabled even when the selection was outside a table.

Bind the menu button to Some("table.selectTable") (which is gated by in_table),
so that the Select button accurately disables when outside a table, matching
pre-port ribbon behavior. Add regression test assertions in ribbon/tests.rs.
2026-11-24 00:05:47 +00:00
Lucas Batista Vargas 73d3c71346 Ribbon: compact tile sizing for Text Effects › Transform menu (#7449) (#7453)
In Text Effects › Transform (wordart_menus.rs), the warp effects TileGrid
did not configure thumbnail sizing, causing tiles to expand to the default
card size (128 pt compact / 160 pt comfortable, resulting in ~132×93 pt
cells). With 4 columns, this expanded the dropdown menu to ~554 pt in width.

Set .thumb_size(ThumbSize::Small) on the TileGrid, rendering compact preview
tiles (~46×32 pt) and keeping the 4-column menu around ~200 pt wide with
crisp previews, matching pre-refactor parity. Add a regression test verifying
tile and grid dimensions.
2026-11-24 00:05:42 +00:00
aiongg c939e644aa Control keyboard test: a modeless dialog's first Escape reverts the field, the second closes it; table resize button events carry the held modifiers 2026-11-23 23:24:26 +00:00
aiongg c406211ce9 Selection bar test: button events carry the held modifiers 2026-11-23 22:28:38 +00:00
aiongg 720d6f4586 Test the CJK composition through the served face's glyphs 2026-11-23 21:59:16 +00:00
aiongg 224b65101c web host: Files::write takes the write intent 2026-11-23 21:18:18 +00:00
aiongg ada0a0247d Review fixes for the next API adaptation 2026-11-23 21:10:21 +00:00
aiongg 027dc1f197 Adapt to craft-libs next b436ae9925 API changes 2026-11-23 21:02:46 +00:00
aiongg 57a9ff0dda deps: bump craft-libs pin to next b436ae9925 (shared FontPicker fixes) 2026-11-23 20:51:58 +00:00
Lucas Batista Vargas 4700018be7 deps: bump craft-libs pin to next for the Styles gallery well and PageView spacing (#7371) (#7379)
* deps: bump craft-libs pin to next to activate merged File rail icons (#2569) and Styles gallery well (#7371)

Bump craft-libs pin to e953d47a378776dea207899b10baf969fc8cbe53 to activate
upstream fixes for File rail icons on Brand/Scrim surfaces (craft-libs#2569)
and Home › Styles gallery sunken well surface in Dark Mode (craft-libs#2986).
Update DOCX settings fixtures to provide external mail merge relationship targets
matching craft-docx source preservation (craft-libs#2349) and assert source rel ID resolution.

Tracks #7149 Item 4 and C3-7 in EPIC #7317. Closes #7371.

* deps: keep the DOCX test edits out of the pin bump

The settings merge fixture changes and the zoom trial do not belong to a
craft-libs rev move. The mail-merge fixtures already landed on main in
1094d3c3 and cc9778eb, and both craft-docx fixes are in the current pin.
The remaining coverage moves to its own DOCX test pull request.
2026-11-23 20:49:29 +00:00
Dylan M. Taylor 700ce2f861 revert: restore scheduled release.yml dry-run on main (#7666) 2026-11-23 14:45:53 -05:00
Dylan M. Taylor 6088bf6f30 ci(release): publish scheduled nightly prereleases (#7663) 2026-11-23 13:17:47 -05:00
Martin BallandClaude Opus 5.5 7fd0136bc8 Missing Fonts: one compact framed row per font (#7283) (#7578)
* Missing Fonts: one compact row per font (#7283)

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

* Missing Fonts: frame each download group (#7283)

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

* Missing Fonts: cut a long unbroken font name at the end so Download stays in its card (#7283)

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

* #7283: the long-name test holds the name and button inside the dialog, not just the window

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-23 17:06:04 +00:00
Dylan M. Taylor f94728dea0 ci(release): forward ARTCRAFT_SERVICES_DISPATCH_TOKEN secret (#7651) 2026-11-23 09:34:31 -05:00
Martin BallandClaude Opus 5.5 6837508ec9 i18n audit: ignore clock data and URLs, and never call GitHub (#7463) (#7487)
* #7463: i18n audit ignores clock data and URLs, and never calls GitHub

The audit compared the Date and Time preview with the clock at the moment of the
check, so a second ticking over between drawing and checking failed it. It now
accepts any preview from any second since the audit began, and any single-word
http(s) link. Check for Updates in the audit's apps answers from a stub, so the
GitHub rate limit's error text can't appear. A test pins that wording and
sentences with links are still reported.

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

* #7463: i18n audit asserts the update check ran through the stub

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

* #7463: wait for the update-check worker thread in the audit test

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

* #7463: wait for the stubbed update check by wall-clock time, not a frame count

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

* #7463: the audit's clock catch-up survives a backward step and is bounded after a forward jump

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-23 13:48:51 +00:00
Martin BallandClaude Opus 5.5 262d036420 Mini toolbar: anchor at the selection's start in right-to-left paragraphs (#7464) (#7488)
* #7464: Mini toolbar anchors at the right edge in right-to-left paragraphs

The bar sat at anchor.min.x + inset, the end of a selection that starts in an
RTL paragraph. Mirror it to anchor.max.x - inset when the paragraph where the
selection starts is RTL. Adds an RTL test and a multi-line LTR test.

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

* #7464: Anchor the mini toolbar at the whole line's edge in mixed-direction RTL lines

visible_anchor kept only the first emitted run of the topmost line; runs come out left to right, so an RTL line with several runs anchored at the leftmost run's right edge. Union the runs on that line.

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

* #7464: Union line runs for the mini toolbar anchor in RTL only

Vertical text stacks whole lines at one y-range, so the union moved the left-to-right anchor off the first line. Left to right keeps the first rectangle again.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-23 13:48:46 +00:00
Martin BallandClaude Opus 5.5 eb7d54c59d Window title: strip NUL from every title source (#3634) (#7545)
* Window title: strip NUL from every title source (#3634)

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

* Window title: test every OS-bound window title for NUL (#3634)

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

* #3634: collect title commands from every frame of the NUL title test, the first three too

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-23 13:48:41 +00:00
batistalucasv c369c3a20b Mini toolbar: anchor floating TaskBar to selection start rather than bounding center (#7447) (#7452) 2026-11-22 18:52:36 +00:00
batistalucasv 0ce25a8d6d Dialogs: compact tile sizing for Insert › SmartArt layouts picker (#7446) (#7451)
In Insert › SmartArt (dialogs_smart_art.rs), the layouts picker TileGrid
did not configure thumbnail sizing, causing tiles to expand to the default
card size (128 pt compact / 160 pt comfortable, resulting in ~136×154 pt
cells). This caused three rows to take ~482 pt in height, overflowing the
dialog's 304 pt viewport budget and pushing detail/footer controls out
of view.

Set .thumb_size(ThumbSize::Large).zoom(1.4) on the layouts TileGrid,
producing 67.2 pt thumbnails in 75.2×93.2 pt cells that cap at 299.6 pt
for 3 rows, matching pre-refactor parity (~96×96 pt cells within
PICKER_HEIGHT = 304 pt). Add a regression test verifying cell and grid
dimensions.
2026-11-22 18:52:26 +00:00
batistalucasv 3d2d9a3d9b Backstage: adopt portrait template cards and full frames in Home and New (#7372) (#7380)
Configure StartScreen in File › Home with the active region's portrait page
aspect (17:22 Letter or 70:99 A4), a fixed card zoom factor of 1.0 (~150 pt
card width without filling the row), and white paper behind page pictures.
Update File › New template grid to use the region's page aspect and render
cards with Cover fit and white paper. Remove thumbnails from File › Open's
RecentList to restore production plain list rows without letterbox bars.

Tracks #7149 items 2 and 3.
2026-11-22 18:52:16 +00:00
batistalucasv e34e841b8f Title bar: provide dedicated single-ink Discord icon for title-bar accent pill (#7445) (#7448)
Follow-up to #7311 and PR #7315.

In crates/ui-egui/icons/discord.svg, restore class="accent" (with #1E6FD9
fill fallback) so the Help › Community Discord ribbon button retains its
distinct brand accent coloration.

Add a dedicated single-ink discordPill.svg icon without class="accent"
(using pure currentColor fill) registered in WORDCRAFT_ICONS_TABLE as
IconId::new("discordPill"), and reference it in the title bar's compact
and full pill button variants (crates/ui-egui/src/chrome/title_bar.rs).
This ensures optimal on_strong contrast against the filled accent.strong
background in both light and dark themes.

Add an asset attribution entry in ATTRIBUTION.md and a regression test in
crates/ui-egui/src/chrome/tests.rs verifying that the title-bar Discord button
paints in text.on_strong while the Help ribbon button renders in accent.solid.
2026-11-22 18:52:06 +00:00
batistalucasv 9409bc7763 Ribbon: compact tile sizing for Decorative Text / WordArt Styles menu (#7374) (#7376)
In crates/ui-egui/src/ribbon/galleries.rs (pub(crate) fn wordart), the
Decorative Text / WordArt Styles TileGrid called .content_cells() without an
explicit thumbnail sizing constraint. Because TileGrid defaults picture_side
to tokens.size.thumb.card and .content_cells() ignores thumb_size/zoom, each
WordArt tile expanded to ~132×119 pt.

Replace .content_cells() with .thumb_size(ThumbSize::Small).zoom(2.0)
so each WordArt style tile renders at compact dimensions (~40×36.4 pt with
ThumbAspect::new(10, 9)), matching pre-refactor ribbon dropdown parity. Add
a regression test verifying compact tile bounds.
2026-11-22 18:49:44 +00:00
batistalucasvandMartin Ball d7085aabde Ribbon: bind command IDs for Table Styles, Borders, Delete, and AutoFit menus (#7324) (#7328)
* Ribbon: compact tile sizing for Home › Bullets library dropdown (#7323)

In the Home › Bullets dropdown popup (bullets_menu), the Bullet Library
grid tiles were rendered with .content_cells() without an explicit
thumbnail sizing constraint, causing each bullet tile to expand to default
card dimensions (~132×132 pt).

Replace .content_cells() with .thumb_size(ThumbSize::Small) so the
Bullet Library renders compact square bullet previews (~22×22 pt), matching
pre-refactor ribbon dropdown parity. Add a regression test verifying the
compact tile dimensions.

* Ribbon: bind command IDs for Table Styles, Borders, Delete, and AutoFit menus (#7324)

In crates/ui-egui/src/ribbon/table.rs, bind command IDs for four table
ribbon menu buttons (Styles -> table.style, Borders -> table.borders,
Delete -> table.deleteTable, AutoFit -> table.autofit) instead of None.

In crates/ui-egui/src/ribbon/common.rs, update menu_button to apply the
bound command's hint/tooltip when the command is disabled.

This ensures that menu button availability, disabled states, and disabled
tooltips accurately reflect engine command state and document protection rules.

---------

Co-authored-by: Martin Ball <[email protected]>
2026-11-22 17:40:08 +00:00
batistalucasvandMartin Ball 9cfe513477 Ribbon: compact tile sizing for Home › Bullets library dropdown (#7323) (#7327)
In the Home › Bullets dropdown popup (bullets_menu), the Bullet Library
grid tiles were rendered with .content_cells() without an explicit
thumbnail sizing constraint, causing each bullet tile to expand to default
card dimensions (~132×132 pt).

Replace .content_cells() with .thumb_size(ThumbSize::Small) so the
Bullet Library renders compact square bullet previews (~22×22 pt), matching
pre-refactor ribbon dropdown parity. Add a regression test verifying the
compact tile dimensions.

Co-authored-by: Martin Ball <[email protected]>
2026-11-22 16:49:00 +00:00
batistalucasv f1decbad01 Mini toolbar: stack formatting controls into two rows inside floating TaskBar (#7375) (#7378) 2026-11-22 15:38:58 +00:00
batistalucasv 139f3a2c7e Backstage: restore white page card and 44 pt icon for File › New personal templates (#7373) (#7377) 2026-11-22 15:38:48 +00:00
batistalucasv a5d5ee8a29 Dialogs: render Multilevel List preview with opaque paper background in Dark Mode (#7325) (#7333) 2026-11-22 15:38:40 +00:00
batistalucasv 08fe7bbb70 Dialogs: compact tile sizing for Insert › Symbol map and recently used grids (#7326) (#7330) 2026-11-22 15:38:31 +00:00
batistalucasv 9f1f2cfb4f Status bar: adjust view mode toggles spacing and zoom slider thumb proportions (#7319) (#7329)
- Group status bar controls using outer Gap::Section spacing between Focus, view mode buttons, and zoom controls.
- Group view mode buttons (Read Mode, Print Layout, Web Layout) in an inner row with Gap::Item spacing.
- Adjust Zoom slider size with ControlSize::Md to match the 14pt icon proportions of adjacent zoom icon buttons.
- Add regression test asserting view mode toggle button spacing/grouping and slider thumb size.
2026-11-22 15:38:22 +00:00
aiongg dda2b45e3c Merge pull request #7179 from aiongg/office-set
Rulers: use the productivity component set
2026-11-22 10:29:31 -05:00
batistalucasv b8627a2373 Ribbon: disable unimplemented stub commands in the command board (#7310) (#7314) 2026-11-22 14:13:55 +00:00
aiongg 993d39c723 Merge remote-tracking branch 'upstream/main' into office-set
# Conflicts:
#	crates/ui-egui/src/language_packs.rs
2026-11-22 07:00:15 +00:00
aiongg 33d874c1f5 Merge pull request #7337 from aiongg/harness-input-first
Tests: run the app window as an eframe app (fixes the intermittent Windows perf failure)
2026-11-22 01:59:47 -05:00
aiongg 85370b265f Add a language test: the reason row may sit partly below the list's visible edge 2026-11-22 05:56:03 +00:00
aiongg edd33f9db5 Add a language: the licence is the row's wrapped text, so an error notice has the row's width
ListRow::below lays its components out in one line. With the licence text
and the error notice both there, the licence took the row's width and the
notice was squeezed to a few pixels; in CI it dropped out of the tree. The
licence goes into the row's lines, and the notice (or the progress bar) is
alone below. The trial checks the reason is at least as wide as Install
and inside the list.
2026-11-22 05:25:43 +00:00
aiongg f005c58134 Perf test: scroll a range the table outruns on every platform's fonts 2026-11-22 04:58:35 +00:00
aiongg 8fb8a5b789 Tests: run the app window as an eframe app, so every pass has the app's input
The app-window harnesses built a ui closure that made the app's input inside a
pass and handed it to the runtime when the next pass began, so each pass ran
on the previous pass's input and the build pass had none. The page picture
loader fixes its job queue from the host it first sees, so in tests it took
the default thread queue instead of the app's host jobs, and the big-table
scrolling test read the resident picture count before those threads finished:
it failed intermittently on loaded runners (Windows).

The harnesses now build with kittest's `build_eframe` over a test-only
`eframe::App` for `WordApp` whose `raw_input_hook` calls `embed::before_input`,
as the desktop driver does. `driver_logic`, `HandOver` and its pending input
are gone.

The scrolling test gives the app a host with `ManualJobs`, runs the queued
renders after each scroll step and checks that the renders use the host's
jobs. Its table and scroll steps are smaller; the relations are unchanged.

Key chords fire their command in the runtime's key stage, which the app reads
before the next pass, as on the desktop: the chord rows step twice.

ui-egui declares `craft`'s `ui-testing` for its own tests, so they build
without the workspace's feature union.
2026-11-22 04:44:26 +00:00
aiongg 616b43bb74 Add a language: the licence is the row's wrapped text, so an error notice has the row's width
ListRow::below lays its components out in one line. With the licence text
and the error notice both there, the licence took the row's width and the
notice was squeezed to a few pixels; in CI it dropped out of the tree. The
licence goes into the row's lines, and the notice (or the progress bar) is
alone below. The trial checks the reason is at least as wide as Install
and inside the list.
2026-11-22 03:17:16 +00:00
aiongg fbade3d8c2 Pin craft-libs next 750a9bdd57 (craft-libs#2905: content-sized shell slots grow to their content, so ribbon groups fit above their labels) 2026-11-22 02:19:33 +00:00
aiongg ec483a4fb0 Pin craft-libs next 13353a0fd3 (craft-libs#2778: Go To, reveals in the scroll owner, the ribbon's first frame) 2026-11-21 18:49:45 +00:00
aiongg 1094d3c35e DOCX settings merge trials: the mail merge source has its relationship part
craft-docx carries a kept w:mailMerge's external source relationship and refuses a missing one (storytold/craft-libs#2349). The fixture's rId9 now has its mailMergeSource part in word/_rels/settings.xml.rels, and the trial checks that mail merge and its source survive a save.
2026-11-21 03:34:46 +00:00
aiongg cc9778ebe1 DOCX passthrough trial: settings without a dangling mail merge source
craft-docx rebinds a kept w:mailMerge's r:id to its external source relationship and refuses a missing one (storytold/craft-libs#2349). The fixture's rId9 had no relationship part; the trial checks the privacy flags, so the element goes.
2026-11-21 02:55:00 +00:00
aiongg 442d1c3f53 craft-libs next: move the pin past the ruler tab selector fix 2026-11-21 02:27:55 +00:00
aiongg 3e0b11df2f Use the productivity component set
WordApp's root environment sets ComponentSet::Productivity, so the rulers take the centred face. The craft-libs pin moves to next fd652b37, which names the set.
2026-11-21 02:21:07 +00:00
aiongg ecb3633aff craft-libs next: move the pin and fix the build
- egui fork pin follows craft-libs (6525c879).
- A value glyph is memo props: EdgeGlyph and LibraryGlyph derive MemoProps; a library glyph keys by its static icon's address, so it holds a 'static reference.
- The tests take craft::ui::testing through the facade's ui-testing feature.
2026-11-21 01:51:03 +00:00
200 changed files with 13633 additions and 1353 deletions
+16
View File
@@ -0,0 +1,16 @@
-----BEGIN PGP PUBLIC KEY BLOCK-----
mDMEaulK1xYJKwYBBAHaRw8BAQdAqHJeDCjY6Hx5FTn/hW+aqu6V394ubLk0Zj3C
bftDwFm0IkFydENyYWZ0IExpbnV4IFJlbGVhc2UgU2lnbmluZyBLZXmIkwQTFgoA
OxYhBCt2dBtBSq1s0z5jEhOgBcC518PtBQJq6UrXAhsBBQsJCAcCAiICBhUKCQgL
AgQWAgMBAh4HAheAAAoJEBOgBcC518PtGeUA/RjvULBTLlccc+2wtJkfjSnCV+cf
PUMEGmW7XkZWkk51AP9w2A/WLv+79nREWEpZzI8LGK5EjrNazP+sY0l7j5rFCLgz
BGrpStcWCSsGAQQB2kcPAQEHQPl7XkQ1gWsvSPf/T9b4m/UHcjJjBpSOtpYlWR56
er5RiO8EGBYKACAWIQQrdnQbQUqtbNM+YxIToAXAudfD7QUCaulK1wIbAgCBCRAT
oAXAudfD7XYgBBkWCgAdFiEEVo3B9o+Prsx5fzx7AG2va7DvM04FAmrpStcACgkQ
AG2va7DvM07taQEA4d2VFkKRIP0g9TrE86KpnuXPap+LKqe0tfIxpdf9YxIA/0Wo
9H/iG8nH++nxC087p3HE0S+0UovxqkhXJLSr8B4JDOoA/iLRpqTdYmk6fVXMyPJo
SkOVuwZIGS6VgBdSQP0e2P2YAP41L5OoSvwdQIG3/uNrM+ieqpYeM597/hCLFs5A
ga/qCA==
=3wGQ
-----END PGP PUBLIC KEY BLOCK-----
+107
View File
@@ -0,0 +1,107 @@
{
"schema": "craft-nightly-release-policy/v3",
"repository": "storytold/wordcraft",
"repository_id": 1408489772,
"producer_workflow_id": 429734489,
"producer_workflow_path": ".github/workflows/nightly.yml",
"producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
"signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"release_branch": "nightly-signer",
"manual_actors": [
"bflatastic",
"dylanmtaylor",
"echelon",
"FredApps",
"skylartaylor"
],
"max_age_seconds": 86400,
"candidate_policy": {
"schema": "craft-nightly-candidate-policy/v3",
"epoch": "wordcraft-nightly-20261124",
"repository": "storytold/wordcraft",
"branch": "main",
"required_workflows": [
{
"workflow_id": 380135788,
"workflow_path": ".github/workflows/ci.yml",
"jobs": [
{
"name": "gate / gate (ubuntu-24.04)",
"app_id": 15368,
"applicability": "required"
}
]
}
],
"sonar": {
"organization": "storytold",
"project": "storytold_wordcraft",
"app_id": 12526,
"check_name": "SonarCloud Code Analysis",
"details_url": "https://sonarcloud.io/dashboard?id=storytold_wordcraft&branch=main",
"issue_types": [
"VULNERABILITY"
],
"accepted_conditions": [
{
"metric": "new_security_rating",
"comparator": "GT",
"error_threshold": "1",
"maximum": "5"
}
],
"required_conditions": [
{
"metric": "new_reliability_rating",
"comparator": "GT",
"error_threshold": "1"
},
{
"metric": "new_maintainability_rating",
"comparator": "GT",
"error_threshold": "1"
},
{
"metric": "new_coverage",
"comparator": "LT",
"error_threshold": "80"
},
{
"metric": "new_duplicated_lines_density",
"comparator": "GT",
"error_threshold": "3"
},
{
"metric": "new_security_hotspots_reviewed",
"comparator": "LT",
"error_threshold": "100"
}
],
"debt": []
}
},
"max_artifact_bytes": 2147483648,
"automatic_signer_actors": [],
"platforms": {
"windows-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
"trust": {
"publisher_subject": "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"
}
},
"linux-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
"trust": {
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
}
},
"macos-aarch64": {
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
"trust": {
"apple_team_id": "DJ6XS33FX8"
}
}
}
}
+227
View File
@@ -0,0 +1,227 @@
name: Nightly build check
# Builds the unsigned WordCraft Nightly the way the producer does (packaging/linux/nightly.sh,
# packaging/windows/package.ps1 -Nightly, packaging/macos/nightly.sh) and checks each archive as the
# Launcher unpacks it. No secrets and no environment: the real Nightly is signed by the shared
# release-ref signer (craft-common-actions), which calls packaging/macos/nightly-sign.sh and the
# app's sign.ps1.
on:
# The platform runners are shared with release builds: pull requests run this only with the
# `full-ci` label, never by changed paths. `labeled` so adding it starts a run.
pull_request:
types: [opened, synchronize, reopened, labeled]
workflow_dispatch:
permissions:
contents: read
# A newer push to a labelled PR cancels its older run. Any event that will not build (no `full-ci`
# label, or another label added) gets a group of its own, so it never cancels a real build.
concurrency:
group: nightly-build-${{ github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'full-ci') && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
linux:
name: Nightly tar (x86_64, unsigned)
if: >-
github.event_name == 'workflow_dispatch' ||
(contains(github.event.pull_request.labels.*.name, 'full-ci') &&
(github.event.action != 'labeled' || github.event.label.name == 'full-ci'))
runs-on: ubuntu-latest
timeout-minutes: 120
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Install the system libraries the GUI links
run: sudo apt-get update && sudo apt-get install -y pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcursor-dev libxrandr-dev libxi-dev libgtk-3-dev libfontconfig1-dev libfreetype-dev
- name: Check out craft-fonts
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f5141455aac7b2eb4708aa259d8ffcdf10fde939
with:
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f5141455aac7b2eb4708aa259d8ffcdf10fde939
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
with:
toolchain: stable
- name: Prepare a Nightly identity for this commit
shell: bash
run: |
set -euo pipefail
base="$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"].split("-")[0])')"
sha="$(git rev-parse HEAD)"
date="$(date -u +%Y-%m-%d)"
{
echo "WORDCRAFT_BUILD_SHA=$sha"
echo "WORDCRAFT_BUILD_DATE=$date"
echo "WORDCRAFT_VERSION=$base-nightly.${date//-/}.$GITHUB_RUN_NUMBER.$GITHUB_RUN_ATTEMPT.g${sha:0:12}"
echo "WORDCRAFT_BUILD_CHANNEL=nightly-v1"
echo "CARGO_TARGET_DIR=$RUNNER_TEMP/nightly-targets"
echo "DIST=$RUNNER_TEMP/nightly-dist"
echo "CRAFT_FONTS_DIR=$GITHUB_WORKSPACE/craft-fonts"
echo "CRAFT_FONTS_REQUIRED=1"
} >>"$GITHUB_ENV"
- name: Build the unsigned Nightly tar
run: bash packaging/linux/nightly.sh --arch x86_64
- name: Check the tar as the Launcher unpacks it, and ask its version
shell: bash
run: |
set -euo pipefail
work="$RUNNER_TEMP/nightly-check"
mkdir -p "$work"
archive="$DIST/wordcraft-$WORDCRAFT_VERSION-linux-x86_64-nightly.tar.gz"
# The launcher and the GUI it starts, the icon and the notices; the embedded fonts'
# OFL-*.txt licences appear when the build has CRAFT_FONTS_DIR.
core="$(tar -tzf "$archive" | sort | grep -Ev '^OFL-[A-Za-z0-9_.-]+\.txt$' | tr '\n' ' ')"
[ "$core" = "ATTRIBUTION.md LICENSE-APACHE LICENSE-MIT NOTICE README.md wordcraft wordcraft-bin wordcraft-nightly.png " ] \
|| { echo "unexpected members: $core"; exit 1; }
tar -xzf "$archive" -C "$work"
[ -x "$work/wordcraft" ] && [ ! -L "$work/wordcraft" ]
[ "$(stat -c %a "$work/wordcraft")" = 755 ]
[ -x "$work/wordcraft-bin" ] && [ ! -L "$work/wordcraft-bin" ]
mkdir -p "$work/home" "$work/profile"
chmod 700 "$work/home" "$work/profile"
out="$(env -i HOME="$work/home" PATH=/usr/bin:/bin "$work/wordcraft" --version 2>"$work/stderr")" \
|| { cat "$work/stderr"; exit 1; }
[ ! -s "$work/stderr" ]
[ "$out" = "WordCraft $WORDCRAFT_VERSION (nightly-v1)" ]
out="$(env -i HOME="$work/home" PATH=/usr/bin:/bin "$work/wordcraft" --launch-profile nightly-v1 --profile-root "$work/profile" --version)"
[ "$out" = "WordCraft $WORDCRAFT_VERSION (nightly-v1)" ]
[ "$(head -c 2 "$work/wordcraft")" = '#!' ]
echo "==> verified (unsigned): $out"
- name: Keep the unsigned archive
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: wordcraft-nightly-linux-x86_64-unsigned
path: ${{ runner.temp }}/nightly-dist/wordcraft-${{ env.WORDCRAFT_VERSION }}-linux-x86_64-nightly.tar.gz
if-no-files-found: error
retention-days: 7
compression-level: 0
windows:
name: Nightly ZIP (x86_64, unsigned)
if: >-
github.event_name == 'workflow_dispatch' ||
(contains(github.event.pull_request.labels.*.name, 'full-ci') &&
(github.event.action != 'labeled' || github.event.label.name == 'full-ci'))
runs-on: windows-latest
timeout-minutes: 150
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
defaults:
run:
shell: pwsh
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Check out craft-fonts
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f5141455aac7b2eb4708aa259d8ffcdf10fde939
with:
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f5141455aac7b2eb4708aa259d8ffcdf10fde939
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
with:
toolchain: stable
targets: x86_64-pc-windows-msvc
- name: Prepare a Nightly identity for this commit
shell: bash
run: |
set -euo pipefail
base="$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"].split("-")[0])')"
sha="$(git rev-parse HEAD)"
date="$(date -u +%Y-%m-%d)"
{
echo "WORDCRAFT_BUILD_SHA=$sha"
echo "WORDCRAFT_BUILD_DATE=$date"
echo "WORDCRAFT_VERSION=$base-nightly.${date//-/}.$GITHUB_RUN_NUMBER.$GITHUB_RUN_ATTEMPT.g${sha:0:12}"
echo "WORDCRAFT_BUILD_CHANNEL=nightly-v1"
echo "CARGO_TARGET_DIR=$RUNNER_TEMP/nightly-targets"
echo "DIST=$RUNNER_TEMP/nightly-dist"
echo "CRAFT_FONTS_DIR=$GITHUB_WORKSPACE/craft-fonts"
echo "CRAFT_FONTS_REQUIRED=1"
} >>"$GITHUB_ENV"
- name: Build the unsigned Nightly intermediate
run: ./packaging/windows/package.ps1 -Arch x64 -Nightly -BuildOnly -Target x86_64-pc-windows-msvc -TargetDir $env:CARGO_TARGET_DIR -Dist $env:DIST
- name: Run the packaging contracts (no signing material)
run: ./packaging/windows/nightly-package-tests.ps1 -FixtureRoot $env:RUNNER_TEMP
- name: Run the signing contracts (dummy keys, no signing)
run: ./packaging/windows/nightly-signing-tests.ps1 -FixtureRoot $env:RUNNER_TEMP
- name: Keep the unsigned intermediate
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: wordcraft-nightly-windows-x86_64-unsigned
path: ${{ runner.temp }}/nightly-dist/wordcraft-${{ env.WORDCRAFT_VERSION }}-windows-x86_64-nightly.unsigned.zip
if-no-files-found: error
retention-days: 7
compression-level: 0
macos:
name: Nightly .app (aarch64, unsigned)
if: >-
github.event_name == 'workflow_dispatch' ||
(contains(github.event.pull_request.labels.*.name, 'full-ci') &&
(github.event.action != 'labeled' || github.event.label.name == 'full-ci'))
runs-on: macos-15
timeout-minutes: 120
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Check out craft-fonts
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f5141455aac7b2eb4708aa259d8ffcdf10fde939
with:
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f5141455aac7b2eb4708aa259d8ffcdf10fde939
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
with:
toolchain: stable
targets: aarch64-apple-darwin
- name: Prepare a Nightly identity for this commit
shell: bash
run: |
set -euo pipefail
base="$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"].split("-")[0])')"
sha="$(git rev-parse HEAD)"
date="$(date -u +%Y-%m-%d)"
{
echo "WORDCRAFT_BUILD_SHA=$sha"
echo "WORDCRAFT_BUILD_DATE=$date"
echo "WORDCRAFT_VERSION=$base-nightly.${date//-/}.$GITHUB_RUN_NUMBER.$GITHUB_RUN_ATTEMPT.g${sha:0:12}"
echo "WORDCRAFT_BUILD_CHANNEL=nightly-v1"
echo "CARGO_TARGET_DIR=$RUNNER_TEMP/nightly-targets"
echo "DIST=$RUNNER_TEMP/nightly-dist"
echo "CRAFT_FONTS_DIR=$GITHUB_WORKSPACE/craft-fonts"
echo "CRAFT_FONTS_REQUIRED=1"
} >>"$GITHUB_ENV"
- name: Build the unsigned Nightly bundle
run: bash packaging/macos/nightly.sh --arch aarch64
- name: Check the archive and the bundle version
run: bash packaging/macos/nightly-verify.sh --expect unsigned --input "$DIST/wordcraft-$WORDCRAFT_VERSION-macos-aarch64-nightly.zip"
- name: Keep the unsigned archive
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: wordcraft-nightly-macos-aarch64-unsigned
path: ${{ runner.temp }}/nightly-dist/wordcraft-${{ env.WORDCRAFT_VERSION }}-macos-aarch64-nightly.zip
if-no-files-found: error
retention-days: 7
compression-level: 0
+72
View File
@@ -0,0 +1,72 @@
name: Dispatch release-ref nightly
# Transport only, never authorization. No checkout, payload parsing or release environment.
on:
workflow_run:
workflows: [WordCraft unsigned nightly]
types: [completed]
branches: [main]
permissions: {}
jobs:
dispatch:
# SOURCE PREPARATION: literal off until immutable shared tooling and policy qualification.
if: >-
false && github.repository == 'storytold/wordcraft' &&
github.event_name == 'workflow_run'
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
actions: write
steps:
- name: Dispatch only the exact completed producer run and attempt
shell: python
env:
GH_TOKEN: ${{ github.token }}
run: |
import json
import os
import urllib.request
def require(value, message):
if not value:
raise RuntimeError(message)
# These filters reduce noise; the protected signer-branch validator repeats admission
# against authenticated API metadata and required attestation/quality evidence.
require(os.environ.get('GITHUB_REPOSITORY') == 'storytold/wordcraft', 'wrong repository')
require(os.environ.get('GITHUB_EVENT_NAME') == 'workflow_run', 'wrong event')
with open(os.environ['GITHUB_EVENT_PATH'], encoding='utf-8') as stream:
event = json.load(stream)
require(event.get('action') == 'completed', 'producer is not complete')
require(event.get('repository', {}).get('full_name') == 'storytold/wordcraft', 'wrong event repository')
producer = event.get('workflow_run', {})
require(producer.get('head_repository', {}).get('full_name') == 'storytold/wordcraft', 'foreign producer')
require(producer.get('path') == '.github/workflows/nightly.yml', 'wrong producer path')
require(producer.get('head_branch') == 'main', 'wrong producer branch')
require(producer.get('status') == 'completed' and producer.get('conclusion') == 'success', 'producer did not succeed')
# First scheduled attempt only; reviewed manual/re-run authority belongs to release policy.
require(producer.get('event') == 'schedule', 'not an automatic scheduled producer')
run_id, attempt = producer.get('id'), producer.get('run_attempt')
require(type(run_id) is int and run_id > 0, 'invalid producer run id')
require(type(attempt) is int and attempt == 1, 'invalid automatic producer attempt')
body = json.dumps({'ref': 'refs/heads/nightly-signer', 'inputs': {
'producer_run_id': str(run_id), 'producer_run_attempt': str(attempt)
}}).encode('utf-8')
request = urllib.request.Request(
'https://api.github.com/repos/storytold/wordcraft/actions/workflows/nightly-sign.yml/dispatches',
data=body, method='POST', headers={
'Authorization': 'Bearer ' + os.environ['GH_TOKEN'],
'Accept': 'application/vnd.github+json',
'Content-Type': 'application/json',
'X-GitHub-Api-Version': '2022-11-28',
'User-Agent': 'wordcraft-nightly-dispatch'
})
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
raise RuntimeError('dispatch redirects are forbidden')
# One bounded request, no retry: duplicate transport is not publication authority.
with urllib.request.build_opener(NoRedirect()).open(request, timeout=20) as response:
require(response.status == 204, 'dispatch was not accepted')
print('Dispatched producer run/attempt to the release-ref validator; not a signing result.')
+45
View File
@@ -0,0 +1,45 @@
name: WordCraft release-ref nightly signer
# Enabled for supervised manual dispatch on the dedicated nightly-signer branch, which only ever
# fast-forwards to reviewed main commits (never the stable release branch).
# A reusable callee does not change context; this must be a real top-level signer-branch dispatch.
on:
workflow_dispatch:
inputs:
producer_run_id:
description: Exact untrusted producer Actions run ID
required: true
type: string
producer_run_attempt:
description: Exact untrusted producer Actions run attempt
required: true
type: string
permissions: {}
concurrency:
group: wordcraft-nightly-release
cancel-in-progress: false
jobs:
release:
# Actual context guards: official repository, manual dispatch, real nightly-signer branch.
if: >-
github.repository == 'storytold/wordcraft' &&
github.event_name == 'workflow_dispatch' &&
github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch'
permissions:
contents: write
actions: read
checks: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
with:
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
app-name: wordcraft
producer_run_id: ${{ inputs.producer_run_id }}
producer_run_attempt: ${{ inputs.producer_run_attempt }}
# No secrets: inherit or raw platform values in this caller. Only the isolated native
# callee job may bind the existing release environment (which trusts release and
# nightly-signer) and export keys in its signing step.
+34
View File
@@ -0,0 +1,34 @@
name: WordCraft unsigned nightly
# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet.
# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it).
on:
workflow_dispatch:
permissions:
contents: read
jobs:
unsigned:
# Actual context guards only; no inherited/platform secrets.
if: >-
github.repository == 'storytold/wordcraft' &&
github.ref == 'refs/heads/main' && github.ref_type == 'branch' &&
(github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')
# Maximum for the reusable workflow. Its compiler narrows to contents/actions read;
# no OIDC, attestation write, release environment or platform secrets in compilation.
permissions:
contents: read
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
with:
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
app-name: wordcraft
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
# One producer run builds every listed platform for one all-or-nothing release. The pin is the
# craft-common-actions main commit that merged the exact-analysis admission (#371, after #370,
# #369 and #364).
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
+25 -2
View File
@@ -5,9 +5,9 @@ name: Packaging lint
on:
push:
branches: [main, release]
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**", ".github/nightly-signing-policy.json", ".github/nightly-linux-signing-key.asc", "sonar-project.properties"]
pull_request:
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**", ".github/nightly-signing-policy.json", ".github/nightly-linux-signing-key.asc", "sonar-project.properties"]
workflow_dispatch:
permissions:
@@ -49,3 +49,26 @@ jobs:
- name: Build and check non-executable installer fixtures
shell: pwsh
run: ./packaging/windows/test-install-policy.ps1 -OutputDirectory (Join-Path $env:RUNNER_TEMP 'craft-install-policy-tests')
nightly-source-contract:
name: Nightly source contracts (no build or signing)
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
contents: read
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Enforce nightly serialization and synthetic packaging contracts
run: python3 packaging/nightly-tests.py
- name: Check the Arch Nightly handoff launcher (no build)
run: bash packaging/linux/nightly-arch-tar-test.sh
- name: Render and run the Nightly tar launcher (no build)
run: bash packaging/linux/nightly-package-test.sh
- name: Check the flat Nightly tar's shared template launcher (no build)
run: bash packaging/linux/nightly-tar-launch-test.sh
+1
View File
@@ -60,3 +60,4 @@ jobs:
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
+4
View File
@@ -8,3 +8,7 @@ plan/
/.claude/
/target-*/
/craft-fonts/
/.nightly-tools
/.nightly-input
/craft-i18n
__pycache__/
+7
View File
@@ -26,6 +26,12 @@ The UI icons are SVG files in `crates/ui-egui/icons/`, one row each below. Gener
| `assets/app-icon/hicolor/scalable/apps/ai.storyteller.wordcraft.svg` | WordCraft contributors | original artwork drawn in SVG (`assets/app-icon/wordcraft.svg`), rendered by `packaging/icons.sh` | MIT OR Apache-2.0 | Placeholder app icon until the WordCraft mascot drawing lands |
| `assets/app-icon/hicolor/48x48/apps/ai.storyteller.wordcraft.png` | WordCraft contributors | original artwork drawn in SVG (`assets/app-icon/wordcraft.svg`), rendered by `packaging/icons.sh` | MIT OR Apache-2.0 | Placeholder app icon until the WordCraft mascot drawing lands |
| `assets/app-icon/hicolor/512x512/apps/ai.storyteller.wordcraft.png` | WordCraft contributors | original artwork drawn in SVG (`assets/app-icon/wordcraft.svg`), rendered by `packaging/icons.sh` | MIT OR Apache-2.0 | Placeholder app icon until the WordCraft mascot drawing lands |
| `assets/app-icon/wordcraft-nightly.png` | WordCraft contributors | derived from `assets/app-icon/hicolor/256x256/apps/ai.storyteller.wordcraft.png` by `packaging/nightly-icons.py` (nightly field `#232c67`); input hashes and the recipe are in `assets/app-icon/nightly-provenance.json` | MIT OR Apache-2.0 | Nightly 256 px render; the icon the Linux Nightly tar ships |
| `assets/app-icon/wordcraft-nightly-1024.png` | WordCraft contributors | derived from `assets/app-icon/wordcraft-1024.png` by `packaging/nightly-icons.py` | MIT OR Apache-2.0 | 1024 px master the Nightly `.icns` is generated from |
| `assets/app-icon/wordcraft-nightly.ico` | WordCraft contributors | derived from `assets/app-icon/wordcraft.ico` by `packaging/nightly-icons.py` | MIT OR Apache-2.0 | Windows Nightly icon (16-256 px), embedded by `apps/wordcraft/build.rs` into the Nightly executable only |
| `assets/app-icon/wordcraft-nightly.icns` | WordCraft contributors | derived from `assets/app-icon/wordcraft.icns` by `packaging/nightly-icons.py` | MIT OR Apache-2.0 | macOS Nightly bundle icon (`CFBundleIconFile wordcraft-nightly`) |
| `assets/app-icon/nightly-provenance.json` | WordCraft contributors | original work for this repository | MIT OR Apache-2.0 | The exact inputs, palette and transform that produced the Nightly icon set |
| `assets/app-icon/README.md` | WordCraft contributors | original description of this repository's own icon artwork | MIT OR Apache-2.0 | Names the master, the sizes and the regeneration steps |
| `assets/fonts/Inter-Medium.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface (Latin UI/document font, carried over from DesignCraft) |
| `assets/fonts/Inter-Regular.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface (Latin UI/document font, carried over from DesignCraft) |
| `assets/fonts/Inter-SemiBold.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface (Latin UI/document font, carried over from DesignCraft) |
@@ -135,6 +141,7 @@ The UI icons are SVG files in `crates/ui-egui/icons/`, one row each below. Gener
| `crates/ui-egui/icons/designMode.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/dictate.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/discord.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/discordPill.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/distributeCols.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/distributeRows.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/docPrefs.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
Generated
+210 -284
View File
File diff suppressed because it is too large Load Diff
+52 -52
View File
@@ -37,20 +37,20 @@ 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 = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", 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" }
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
craft = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0", default-features = false }
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
craft = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0", default-features = false }
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
# foundation
kurbo = { version = "0.13", features = ["serde"] }
@@ -81,28 +81,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 = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0", default-features = false, features = ["write"] }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0", default-features = false, features = ["write"] }
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0", features = ["doc"] }
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0", features = ["text"] }
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0", features = ["flow"] }
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0", features = ["detect"] }
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0", features = ["doc"] }
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0", features = ["text"] }
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0", features = ["flow"] }
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0", features = ["detect"] }
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", 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"
@@ -170,27 +170,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 = "243d68e12d05e89122db6d154924bf1992e10d38" }
hayro = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
emath = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
egui = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
hayro = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
+13
View File
@@ -66,3 +66,16 @@ _Avoid_: Tofu, box, notdef character
A picture the document refers to that the output cannot include: its part is absent, its data
cannot be decoded, its format is unsupported, or it is linked from outside the file.
_Avoid_: Broken image, dropped image
## Windows
**Document window**:
A top-level window showing one open document. A document can be shown in several document windows
at once (View › New Window); each window shows exactly one.
_Avoid_: Viewport (that is the framework's surface), root window, tab
**Save prompt**:
The question "Save changes?" asked when the last document window showing a document with unsaved
changes is about to close. It belongs to that window and appears there; while it is up, the other
windows wait.
_Avoid_: Close guard, save dialog, unsaved-changes dialog
-1
View File
@@ -167,7 +167,6 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
- 2026-11-17: File formats, codecs and protocols now come from the shared libraries (storytold/craft-libs#778): legacy code pages (craft-codepage, #6785), plain-text encoding detection (craft-mime, #6950), the ZIP entry-count guard (craft-zip, #6948), Read Aloud's Speech Dispatcher wire format (craft-ssip, #6951), picture probes for clipboard DIBs, JPEG memory, PNG and WebP (craft-image-codecs, #6949, #6955) and the MCP stdio server (craft-mcp-server, #6956), all with craft-libs pinned at main `93dac78c` (#6954, #6960). Opening documents and pictures behaves as before, except that large non-interleaved JPEGs are refused sooner (a 4:4:4 picture from about 60 Mpx, was 67 Mpx), invalid PNGs are refused more strictly, a lossless WebP's transparency is now seen, and MCP clients get tool errors for unknown or mistyped arguments and a 1,000-message batch cap (docs/mcp.md). The old code stays as test-only references the shared code is checked against.
- 2026-11-15: Get the Missing Fonts. A document opened from a file that is missing fonts their publisher gives away (Microsoft's Aptos family, the default in recent Word documents; Cascadia Code and Mono) brings up a box naming each font, the font drawn instead, the publisher's download page and how to install the download, with Don't show this again. `font.missing` reports the same page, so agents get it without the box. WordCraft links to the page only; it downloads and bundles nothing.
- 2026-10-30: Track Changes: a list item deleted whole, text and paragraph mark, shows its number as deleted text, in the deletion's colour and with its mark (struck through by default, or caret, #, bold, italic, underline), and hides it with No Markup or when Track Changes Options hide deletions (#4828). Readiness unchanged.
fix/6146-touchpad-scroll-speed
- 2026-11-09: Touchpad and mouse-wheel scroll speed settings (#6146): scales Wayland touchpad point input by default (4×) so two-finger scrolling matches desktop speed rather than crawling 1:1, and scales mouse wheel line distance; File › Options › Advanced › Scrolling; commands ui.scrollSpeed and ui.touchpadScrollSpeed.
- 2026-11-15: Layout: from Word 2013's layout (compatibility mode 15), balancing the columns before a continuous break keeps the last two, three or five lines of a paragraph that began on the page before together, keeps a two- or three-line paragraph that begins the last page whole, and holds a paragraph with keep lines together (or keep with next) whole in the first column when the strict rules fit. Synthetic tests also cover a footnote and a float (#6821); mode 14 splits them as before. Readiness estimates unchanged.
+13
View File
@@ -897,8 +897,21 @@ fn parity_markdown(p: &Value) -> String {
s
}
/// The Launcher's Nightly bootstrap belongs to the desktop app: a CLI must not accept it, in the
/// separate-token or `=` form, so a mis-routed launch fails loudly instead of editing stable data.
fn launcher_profile_flag(args: &[OsString]) -> bool {
args.iter().any(|arg| {
let arg = arg.to_string_lossy();
arg == "--launch-profile" || arg == "--profile-root" || arg.starts_with("--launch-profile=") || arg.starts_with("--profile-root=")
})
}
fn main() -> ExitCode {
let args: Vec<OsString> = std::env::args_os().skip(1).collect();
if launcher_profile_flag(&args) {
eprintln!("wordcraft-cli: --launch-profile and --profile-root are the desktop app's Nightly bootstrap, not a CLI option");
return ExitCode::from(2);
}
// Language packs installed in the suite's font store are used; `proof.installPack` installs
// only while the person has turned downloading on in the app.
wordcraft_engine::packs::use_font_store(false);
+17
View File
@@ -1,6 +1,23 @@
use super::*;
use std::io::Read;
/// The desktop app's Nightly bootstrap is never a CLI option, in either spelling.
#[test]
fn the_launcher_profile_bootstrap_is_refused_in_both_forms() {
for argv in [
&["--launch-profile", "nightly-v1", "--profile-root", "/nightly/profiles/wordcraft", "--version"][..],
&["--launch-profile=nightly-v1", "--profile-root=/nightly/profiles/wordcraft"][..],
&["--profile-root", "/nightly/profiles/wordcraft"][..],
] {
let argv: Vec<std::ffi::OsString> = argv.iter().map(std::ffi::OsString::from).collect();
assert!(launcher_profile_flag(&argv), "{argv:?}");
}
for argv in [&["--version"][..], &["proof.check", "--launch-profiles"][..], &["--profile-roots"][..]] {
let argv: Vec<std::ffi::OsString> = argv.iter().map(std::ffi::OsString::from).collect();
assert!(!launcher_profile_flag(&argv), "{argv:?}");
}
}
fn args(values: &[&str]) -> Vec<String> {
values.iter().map(|value| (*value).into()).collect()
}
+8 -8
View File
@@ -37,9 +37,9 @@ use std::rc::Rc;
use std::sync::Arc;
use std::sync::Mutex;
use craft::host::{FileError, Files, PickId, PickRequest, Picked};
use craft::host::{FileError, Files, PendingPick, PickId, PickRequest, Picked, WriteIntent};
use craft::platform::browser_files::BrowserFiles;
use craft::platform::open::{DropTarget, DroppedFile, IntakeSender};
use craft::platform::open::{DroppedFile, IntakeSender};
use craft::web_host::web::{FileData, Host, Message};
use wordcraft_ui_egui::{Services, WordApp};
@@ -131,7 +131,7 @@ fn deliver_open(intake: &IntakeSender, name: &str, data: &FileData) {
return;
}
let file = DroppedFile { path: None, name, bytes: Some(Arc::from(array.to_vec())) };
intake.dropped(vec![file], DropTarget::Elsewhere);
intake.dropped(vec![file]);
}
/// The files of a hosted page: reads go to the browser's files, but a save goes to the host page,
@@ -167,16 +167,16 @@ impl Files for HostedFiles {
}
}
fn pick_pending(&self) -> bool {
self.inner.pick_pending()
fn pending_pick(&self) -> Option<PendingPick> {
self.inner.pending_pick()
}
fn read(&self, path: &Path) -> Result<Vec<u8>, FileError> {
self.inner.read(path)
}
fn write(&self, path: &Path, bytes: &[u8]) -> Result<(), FileError> {
self.inner.write(path, bytes)
fn write(&self, path: &Path, bytes: &[u8], intent: WriteIntent) -> Result<bool, FileError> {
self.inner.write(path, bytes, intent)
}
fn last_folder(&self, purpose: &str) -> Option<PathBuf> {
@@ -192,7 +192,7 @@ impl Files for HostedFiles {
let answer = match sent {
// A Save As or first Save makes the page hold the document as this file: the answer
// names it, and the next Save posts the name with `save_as` false.
Ok(()) if request.save_as => Picked::Paths(vec![PathBuf::from(&name)]),
Ok(()) if request.save_as => Picked::Saved { path: PathBuf::from(&name), file_type: None },
// An overwrite of the opened file, or a copy: the document's file stays as it is.
Ok(()) => Picked::Downloaded(name),
Err(error) => Picked::Failed(error),
+3 -3
View File
@@ -10,7 +10,7 @@ use craft::host::{Files, Host, Wake};
use craft::platform::appearance::SystemReader;
use craft::platform::browser_files::BrowserFiles;
use craft::platform::clipboard::{Clipboard, ClipboardError, EventClipboard, Flavor, LateOffers, TEXT};
use craft::platform::open::{DropTarget, DroppedFile, FileIntake, IntakeSender};
use craft::platform::open::{DroppedFile, FileIntake, IntakeSender};
use craft::print::spool::Spool;
use craft::settings::SharedSettings;
use craft::ui::InstallSpec;
@@ -227,7 +227,7 @@ impl eframe::App for WebShell {
match f.bytes_async().await {
Ok(bytes) => {
let file = DroppedFile { path: None, name, bytes: Some(Arc::from(bytes)) };
sender.dropped(vec![file], DropTarget::Elsewhere);
sender.dropped(vec![file]);
}
Err(e) => log::error!("couldn't read dropped file {name}: {e}"),
}
@@ -412,7 +412,7 @@ fn guard_unload(dirty: Rc<Cell<bool>>, files: Arc<BrowserFiles>) -> Result<(), S
let window = web_sys::window().ok_or("no window")?;
let on_unload = wasm_bindgen::closure::Closure::<dyn FnMut(web_sys::BeforeUnloadEvent)>::new(move |e: web_sys::BeforeUnloadEvent| {
// A save still in the browser's picker hasn't written anything yet.
if dirty.get() || files.pick_pending() {
if dirty.get() || files.pending_pick().is_some() {
e.prevent_default();
// Older browsers ask only when `returnValue` is set.
e.set_return_value("unsaved changes");
+6
View File
@@ -25,6 +25,9 @@ eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "
egui = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
# The nightly launch profile's refusal dialog (a native message box, like the app's other OS errors).
rfd = { workspace = true }
thiserror = { workspace = true }
# The suite's shared libraries: the runtime hooks (`ui`, `ui-app`), file dialogs, the control
# channel's arguments, the GPU choice, printing, settings and window placement, the OS appearance
# reader and the system clipboard.
@@ -68,3 +71,6 @@ xkbcommon-dl = { version = "0.4.2", features = ["x11"] }
# The update helper: a copy of this program started with `--finish-update`
# (`craft::update::self_update::finish`).
craft = { workspace = true, features = ["update"] }
# The nightly Windows identity: an explicit AppUserModelID, so Nightly gets its own taskbar
# button instead of sharing the stable app's (#16335's rule for the suite).
winsafe = { version = "=0.0.29", default-features = false, features = ["user", "shell"] }
+43 -5
View File
@@ -1,25 +1,63 @@
//! Windows only: embed the app icon and version info (VERSIONINFO) into `wordcraft.exe`, so it
//! shows in Explorer, the taskbar, the Start menu and Alt-Tab.
//!
//! On every other target this does nothing. A missing resource compiler is a warning, so a
//! cross-compile from macOS or Linux still links, unless `WORDCRAFT_REQUIRE_WINRES=1` turns it
//! The build channel (`WORDCRAFT_BUILD_CHANNEL`) is decided here, before any code is compiled: a
//! nightly-v1 build gets its own cfg, its own icon and its exact feed version in VERSIONINFO.
//! On every other target this does nothing but that. A missing resource compiler is a warning, so
//! a cross-compile from macOS or Linux still links, unless `WORDCRAFT_REQUIRE_WINRES=1` turns it
//! into an error (for release builds).
#[path = "src/build_channel.rs"]
mod build_channel;
fn main() {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-env-changed=WORDCRAFT_BUILD_CHANNEL");
println!("cargo:rustc-check-cfg=cfg(wordcraft_nightly_v1)");
let nightly = match std::env::var("WORDCRAFT_BUILD_CHANNEL").as_deref() {
Ok("nightly-v1") => {
println!("cargo:rustc-cfg=wordcraft_nightly_v1");
true
}
// An empty value (an unset CI input) means the default stable build.
Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false,
_ => {
eprintln!("unsupported WORDCRAFT_BUILD_CHANNEL (expected stable or nightly-v1)");
std::process::exit(1);
}
};
println!("cargo:rerun-if-changed=../../assets/app-icon/wordcraft.ico");
println!("cargo:rerun-if-changed=../../assets/app-icon/wordcraft-nightly.ico");
println!("cargo:rerun-if-env-changed=WORDCRAFT_REQUIRE_WINRES");
println!("cargo:rerun-if-env-changed=WORDCRAFT_VERSION");
let built_version = if nightly {
match std::env::var("WORDCRAFT_VERSION") {
Ok(version) if build_channel::is_nightly_version(&version) => version,
_ => {
eprintln!("nightly-v1 requires an explicit WORDCRAFT_VERSION feed identity");
std::process::exit(1);
}
}
} else {
std::env::var("CARGO_PKG_VERSION").unwrap_or_default()
};
println!("cargo:rustc-env=WORDCRAFT_BUILT_VERSION={built_version}");
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
return;
}
let mut res = winresource::WindowsResource::new();
res.set_icon("../../assets/app-icon/wordcraft.ico")
.set("ProductName", "WordCraft")
.set("FileDescription", "WordCraft word processor")
res.set_icon(build_channel::windows_icon_path(nightly))
.set("ProductName", if nightly { "WordCraft Nightly" } else { "WordCraft" })
.set("FileDescription", if nightly { "WordCraft Nightly word processor" } else { "WordCraft word processor" })
.set("CompanyName", "Learning Machines LLC")
.set("LegalCopyright", "Copyright (c) the WordCraft authors. MIT OR Apache-2.0.")
.set("OriginalFilename", "wordcraft.exe")
.set("InternalName", "wordcraft");
if nightly {
// The Launcher verifies the PE ProductVersion against the exact feed identity, not FileVersion.
res.set("ProductVersion", &built_version);
}
if let Err(e) = res.compile() {
if std::env::var_os("WORDCRAFT_REQUIRE_WINRES").is_some() {
eprintln!("embedding Windows resources failed: {e}");
+54
View File
@@ -0,0 +1,54 @@
//! The build-time nightly identity shared by the build script and its pure regression tests.
pub fn is_nightly_version(version: &str) -> bool {
let Some((base, suffix)) = version.split_once("-nightly.") else { return false };
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
let base: Vec<_> = base.split('.').collect();
let parts: Vec<_> = suffix.split('.').collect();
base.len() == 3
&& base.iter().all(|s| digits(s))
&& parts.len() == 4
&& parts[0].len() == 8
&& digits(parts[0])
&& digits(parts[1])
&& digits(parts[2])
&& parts[3].strip_prefix('g').is_some_and(|sha| sha.len() == 12 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
}
pub fn windows_icon_path(nightly: bool) -> &'static str {
if nightly { "../../assets/app-icon/wordcraft-nightly.ico" } else { "../../assets/app-icon/wordcraft.ico" }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn windows_resource_uses_the_flavor_specific_icon_without_changing_stable() {
assert_eq!(windows_icon_path(false), "../../assets/app-icon/wordcraft.ico");
assert_eq!(windows_icon_path(true), "../../assets/app-icon/wordcraft-nightly.ico");
}
#[test]
fn explicit_feed_identity_is_required_for_a_nightly_build() {
assert!(is_nightly_version("0.18.1-nightly.20261124.17.1.gabcdef012345"));
for invalid in [
"",
"0.18.1",
"0.18.1-nightly",
"0.18.1-nightly.20261124",
"0.18.1-nightly.20261124.17.1.gABCDEF012345",
"0.18.1-nightly.20261124.17.1.gabcdef012345\n",
] {
assert!(!is_nightly_version(invalid), "{invalid:?}");
}
}
#[test]
fn version_cannot_inject_a_path_or_an_extra_build_directive() {
for invalid in [
"../0.18.1-nightly.20261124.1.1.gabcdef012345",
"0.18.1-nightly.20261124.1.1.gabcdef012345/other",
"0.18.1-nightly.20261124.1.1.gabcdef012345\ncargo:rustc-cfg=other",
] {
assert!(!is_nightly_version(invalid));
}
}
}
+72
View File
@@ -0,0 +1,72 @@
//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build.
use crate::launch_profile::Profile;
use std::ffi::OsString;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BuildFlavor {
Stable,
NightlyV1,
}
pub const COMPILED: BuildFlavor = if cfg!(wordcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> {
match (flavor, profile.is_nightly()) {
(BuildFlavor::NightlyV1, false) => Err("Open WordCraft Nightly from ArtCraft Launcher".into()),
(BuildFlavor::Stable, true) => Err("This is a stable WordCraft build; nightly-v1 requires the nightly build".into()),
_ => Ok(()),
}
}
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
desktop_session && flavor == BuildFlavor::NightlyV1
}
/// The Launcher's version line: `WordCraft <version> (nightly-v1)` for a nightly build.
pub fn version(flavor: BuildFlavor, stable: &str) -> String {
match flavor {
BuildFlavor::Stable => stable.to_owned(),
BuildFlavor::NightlyV1 => format!("WordCraft {stable} (nightly-v1)"),
}
}
/// A plain `--version` / `-V`: the only arguments, answered before any startup work.
pub fn version_query(args: &[OsString]) -> bool {
matches!(args, [arg] if arg == "--version" || arg == "-V")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
assert!(!needs_native_error(BuildFlavor::NightlyV1, false));
assert!(!needs_native_error(BuildFlavor::Stable, true));
assert!(!needs_native_error(BuildFlavor::Stable, false));
}
#[test]
fn nightly_build_without_a_profile_is_refused_before_startup() {
let started = std::cell::Cell::new(false);
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
assert!(!started.get());
}
#[test]
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
}
#[test]
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
assert_eq!(version(BuildFlavor::Stable, "0.18.1"), "0.18.1");
assert_eq!(version(BuildFlavor::NightlyV1, "0.18.1"), "WordCraft 0.18.1 (nightly-v1)");
assert!(version_query(&["--version".into()]));
assert!(version_query(&["-V".into()]));
assert!(!version_query(&["--".into(), "--version".into()]));
assert!(!version_query(&[]));
}
}
+163
View File
@@ -123,4 +123,167 @@ mod tests {
assert!(supplied.exists());
let _ = std::fs::remove_dir_all(&dir);
}
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
fn boot() -> (u16, Receiver<ControlRequest>, Control) {
let options = ControlOptions { token: Some(TOKEN.to_string()), ..ControlOptions::default() };
let (rx, control) = start(&options, 0, host(), None).unwrap();
let port = control.listening.addr.port();
(port, rx, control)
}
/// Answer the next request that reaches the UI with `ok`, and return it.
fn answer(rx: &Receiver<ControlRequest>) -> ControlRequest {
let req = rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap();
let _ = req.reply.send(serde_json::json!({"ok": true, "result": {}}));
req
}
/// One connection, several lines.
struct Conn(std::io::BufReader<std::net::TcpStream>, std::net::TcpStream);
impl Conn {
fn open(port: u16) -> Self {
let s = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap();
s.set_read_timeout(Some(std::time::Duration::from_secs(5))).unwrap();
Self(std::io::BufReader::new(s.try_clone().unwrap()), s)
}
fn send(&mut self, line: &str) {
use std::io::Write;
writeln!(self.1, "{line}").unwrap();
}
fn recv(&mut self) -> serde_json::Value {
use std::io::BufRead;
let mut r = String::new();
let n = self.0.read_line(&mut r).expect("read reply line");
assert!(n > 0, "unexpected EOF while waiting for reply");
serde_json::from_str(&r).expect("reply is valid JSON")
}
fn call(&mut self, line: &str) -> serde_json::Value {
self.send(line);
self.recv()
}
/// The server closed the connection.
fn closed(&mut self) -> bool {
use std::io::BufRead;
let mut r = String::new();
match self.0.read_line(&mut r) {
Ok(0) => true,
Err(e) => matches!(
e.kind(),
std::io::ErrorKind::ConnectionReset
| std::io::ErrorKind::ConnectionAborted
| std::io::ErrorKind::NotConnected
| std::io::ErrorKind::BrokenPipe
),
_ => false,
}
}
}
/// Post-#7101 adaptation of `the_key_on_each_request` (#124, tracked under #7317 / #7720):
/// `craft::automation::server` replaced the legacy per-request `"key"` field with one-time
/// per-connection token authentication (`docs/control-protocol.md`, Token).
#[test]
fn a_connection_authenticates_once_with_the_token_and_unauthenticated_requests_are_refused() {
let (port, rx, control) = boot();
// Authenticate once per connection with `params.token`.
let mut c = Conn::open(port);
let auth_resp = c.call(&format!(r#"{{"id":1,"method":"auth","params":{{"token":"{TOKEN}"}}}}"#));
assert_eq!(auth_resp, serde_json::json!({"id": 1, "ok": true, "result": {"authenticated": true}}));
// Subsequent requests on the authenticated connection carry no token and reach the UI.
c.send(r#"{"id":7,"method":"document.inspect","params":{"text":true}}"#);
let req = answer(&rx);
assert_eq!((req.method.as_str(), &req.params), ("document.inspect", &serde_json::json!({"text": true})));
let r = c.recv();
assert_eq!((&r["ok"], &r["id"]), (&serde_json::json!(true), &serde_json::json!(7)));
c.send(r#"{"id":8,"method":"document.inspect","params":{"text":false}}"#);
let req = answer(&rx);
assert_eq!((req.method.as_str(), &req.params), ("document.inspect", &serde_json::json!({"text": false})));
let r = c.recv();
assert_eq!((&r["ok"], &r["id"]), (&serde_json::json!(true), &serde_json::json!(8)));
drop(c);
// An unauthenticated connection is refused and closed without reaching the UI.
let mut unauth = Conn::open(port);
let r = unauth.call(r#"{"id":9,"method":"document.inspect"}"#);
assert_eq!(r, serde_json::json!({"id": 9, "ok": false, "error": "authentication required"}));
assert!(unauth.closed());
assert!(rx.try_recv().is_err(), "unauthenticated request must not reach the UI");
drop(unauth);
// Legacy pre-#7101 per-request `"key"` does not bypass `auth` and closes the connection.
let mut legacy = Conn::open(port);
let r = legacy.call(&format!(r#"{{"id":10,"key":"{TOKEN}","method":"document.inspect","params":{{"text":true}}}}"#));
assert_eq!(r, serde_json::json!({"id": 10, "ok": false, "error": "authentication required"}));
assert!(legacy.closed());
assert!(rx.try_recv().is_err(), "legacy per-request key must not reach the UI");
drop(legacy);
control.shut_down();
}
/// Post-#7101 adaptation of `params_key_is_only_a_secret_for_auth` (#124, tracked under #7317 / #7729):
/// `craft::automation::server` replaced legacy `"key"` / `params.key` secrets with one-time
/// per-connection `auth` using `params.token` (`docs/control-protocol.md`, Token).
#[test]
fn params_token_is_only_a_secret_for_auth() {
let (port, rx, control) = boot();
// Neither `params.token` on a non-`auth` method nor legacy `params.key` on
// `document.inspect` or `auth` authenticates.
for (id, line) in [
(1, format!(r#"{{"id":1,"method":"document.inspect","params":{{"token":"{TOKEN}"}}}}"#)),
(2, format!(r#"{{"id":2,"method":"document.inspect","params":{{"key":"{TOKEN}"}}}}"#)),
(3, format!(r#"{{"id":3,"method":"auth","params":{{"key":"{TOKEN}"}}}}"#)),
] {
let mut c = Conn::open(port);
assert_eq!(c.call(&line), serde_json::json!({"id": id, "ok": false, "error": "authentication required"}));
assert!(c.closed());
}
assert!(rx.try_recv().is_err(), "refused requests must not reach the UI");
// Authenticate once with `params.token`; `params.key` and `params.token` on subsequent
// non-`auth` methods are forwarded untouched as ordinary parameters.
let mut c = Conn::open(port);
let auth_resp = c.call(&format!(r#"{{"id":1,"method":"auth","params":{{"token":"{TOKEN}"}}}}"#));
assert_eq!(auth_resp, serde_json::json!({"id": 1, "ok": true, "result": {"authenticated": true}}));
c.send(r#"{"id":2,"method":"ui.key","params":{"key":"Enter"}}"#);
let req = answer(&rx);
assert_eq!((req.method.as_str(), &req.params), ("ui.key", &serde_json::json!({"key": "Enter"})));
let r = c.recv();
assert_eq!((&r["ok"], &r["id"]), (&serde_json::json!(true), &serde_json::json!(2)));
c.send(r#"{"id":3,"method":"document.inspect","params":{"token":"ordinary"}}"#);
let req = answer(&rx);
assert_eq!((req.method.as_str(), &req.params), ("document.inspect", &serde_json::json!({"token": "ordinary"})));
let r = c.recv();
assert_eq!((&r["ok"], &r["id"]), (&serde_json::json!(true), &serde_json::json!(3)));
drop(c);
control.shut_down();
}
/// Post-#7101 adaptation of `a_wrong_key_is_refused_and_closed` (#124, tracked under #7317):
/// wrong, short, and long `params.token` values are refused and close the connection without
/// reaching the UI.
#[test]
fn a_wrong_token_is_refused_and_closed() {
let (port, rx, control) = boot();
let wrong = TOKEN.replace('0', "1");
let long = format!("{TOKEN}0");
for token in ["nope", wrong.as_str(), &TOKEN[..63], long.as_str()] {
let mut c = Conn::open(port);
let resp = c.call(&format!(r#"{{"id":1,"method":"auth","params":{{"token":"{token}"}}}}"#));
assert_eq!(resp, serde_json::json!({"id": 1, "ok": false, "error": "authentication required"}), "{token}");
assert!(c.closed(), "{token}");
}
assert!(rx.try_recv().is_err(), "refused auth attempts must not reach the UI");
control.shut_down();
}
}
+17
View File
@@ -54,6 +54,23 @@ pub fn identity() -> AppIdentity {
mod tests {
use super::*;
/// Every type the button claims is included in identity, and plain text/Markdown are never claimed.
#[test]
fn xdg_mime_sets_every_word_type_in_one_call() {
let id = identity();
assert_eq!(id.desktop_id, "ai.storyteller.wordcraft.desktop");
assert_eq!(id.registered_name, "WordCraft");
for t in [
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/msword",
"application/rtf",
"application/vnd.oasis.opendocument.text",
] {
assert!(id.mime_types.iter().any(|a| a == t), "{t}");
}
assert!(!id.mime_types.iter().any(|a| a == "text/plain" || a == "text/markdown"), "plain text and Markdown are never claimed");
}
/// Every type the button claims is one the desktop entry declares, or desktops ignore it.
#[test]
fn the_desktop_entry_declares_every_claimed_type() {
+229
View File
@@ -0,0 +1,229 @@
//! Launcher-owned nightly-v1 bootstrap. Selected before logging, preferences, fonts or saved state.
//! Stable launches retain their original arguments and directory policy. No environment mutation.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use std::sync::OnceLock;
pub const VERSION: &str = "nightly-v1";
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Profile {
Stable,
NightlyV1(PathBuf),
}
impl Profile {
pub fn is_nightly(&self) -> bool {
matches!(self, Self::NightlyV1(_))
}
pub fn root(&self) -> Option<&Path> {
match self {
Self::Stable => None,
Self::NightlyV1(root) => Some(root),
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct Launch {
pub profile: Profile,
pub args: Vec<OsString>,
}
static PROFILE: OnceLock<Profile> = OnceLock::new();
pub fn current() -> &'static Profile {
PROFILE.get().unwrap_or(&Profile::Stable)
}
pub fn install(profile: Profile) -> Result<(), String> {
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into())
}
/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is
/// a file, even when it looks like a profile flag. No filesystem or startup hook runs here.
pub fn parse(args: Vec<OsString>) -> Result<Launch, String> {
let mut selector = None;
let mut root = None;
let mut other = Vec::new();
let mut files = Vec::new();
let mut iter = args.iter();
let mut delimiter = false;
while let Some(arg) = iter.next() {
if arg == "--" {
delimiter = true;
files.extend(iter.cloned());
break;
}
if arg == "--launch-profile" || arg == "--profile-root" {
let slot = if arg == "--launch-profile" { &mut selector } else { &mut root };
if slot.is_some() {
return Err("the profile selector and root must each occur exactly once".into());
}
let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?;
if value.to_string_lossy().starts_with("--") {
return Err("the profile selector/root needs a value".into());
}
*slot = Some(value.clone());
} else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") {
return Err("the nightly protocol requires separate literal selector/root argument tokens".into());
} else {
other.push(arg.clone());
}
}
match (selector, root) {
(None, None) => Ok(Launch { profile: Profile::Stable, args }),
(Some(version), Some(root)) if version == VERSION => {
if !delimiter || !other.is_empty() {
return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into());
}
let root = PathBuf::from(root);
if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) {
return Err("the nightly profile root must be absolute and contain no parent traversal".into());
}
Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() })
}
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()),
_ => Err("--launch-profile and --profile-root must be supplied together".into()),
}
}
/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`),
/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never
/// validated or touched, and `-- --version` stays a file name.
pub fn version_query(args: &[OsString]) -> bool {
let Some((last, pair)) = args.split_last() else { return false };
if last != "--version" && last != "-V" {
return false;
}
let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect();
matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1)
}
/// Validation finishes before the caller's first startup effect. Stable never calls the nightly
/// root validator, so its old settings-folder resolution stays unchanged.
pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result<PathBuf, String>) -> Result<Launch, String> {
if let Profile::NightlyV1(root) = &launch.profile {
launch.profile = Profile::NightlyV1(validate(root)?);
}
Ok(launch)
}
/// The root the Launcher hands a nightly on this platform, in that platform's own spelling: `C:\NightlyData\profiles\wordcraft`
/// on Windows, `/nightly-data/profiles/wordcraft` elsewhere. A test that fixtures the hand-off uses this rather than a
/// literal, because a root literal in the other platform's spelling is not absolute here and `parse` refuses it (#7849).
#[cfg(test)]
pub(crate) fn launcher_root() -> &'static str {
if cfg!(windows) { r"C:\NightlyData\profiles\wordcraft" } else { "/nightly-data/profiles/wordcraft" }
}
/// Resolve the selected private root before the caller's first startup effect.
pub fn validate_root(root: &Path) -> Result<PathBuf, String> {
crate::profile_root::validate(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref(), crate::profile_root::probe_writable)
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
fn args(values: &[&str]) -> Vec<OsString> {
values.iter().map(OsString::from).collect()
}
fn absolute() -> &'static str {
super::launcher_root()
}
fn nightly() -> Vec<OsString> {
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
}
#[test]
fn stable_arguments_and_directory_policy_are_unchanged() {
for argv in [args(&[]), args(&["--control", "7981", "a.docx"]), args(&["--", "--launch-profile", "file.docx"])] {
let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap();
assert_eq!(launch, Launch { profile: Profile::Stable, args: argv });
}
}
#[test]
fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() {
let mut argv = nightly();
argv.extend(args(&["--profile-root", "letter with spaces.docx"]));
let launch = parse(argv).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
assert_eq!(launch.args, args(&["--", "--profile-root", "letter with spaces.docx"]));
}
#[test]
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
for argv in [
args(&["--launch-profile", VERSION]),
args(&["--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--sample", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
] {
assert!(parse(argv).is_err());
}
}
/// #7849: `/nightly-data/...` carries no drive prefix and so is not absolute on Windows, and `C:\...`
/// is one relative name on Unix. A launch that carries the other platform's root spelling is refused
/// instead of run against a directory this platform never meant.
#[test]
fn a_root_absolute_only_in_the_other_platforms_spelling_is_refused() {
let foreign = if cfg!(windows) { "/nightly-data/profiles/wordcraft" } else { r"C:\NightlyData\profiles\wordcraft" };
let argv = args(&["--launch-profile", VERSION, "--profile-root", foreign, "--"]);
assert!(parse(argv).is_err(), "the other platform's root spelling must not stand in: {foreign}");
}
#[test]
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION];
for flag in ["--version", "-V"] {
for form in [pair, reversed] {
let mut argv = args(form);
argv.push(flag.into());
assert!(version_query(&argv), "{argv:?}");
}
}
for argv in [
args(&["--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--sample", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]),
args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]),
args(&["--launch-profile", VERSION, "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]),
] {
assert!(!version_query(&argv), "{argv:?}");
}
// Outside the query the strict protocol still refuses the version flag.
assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err());
}
#[test]
fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() {
let reached = Cell::new(false);
let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true));
assert!(result.is_err());
assert!(!reached.get());
}
#[test]
fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() {
let checked = PathBuf::from(absolute()).join("checked");
let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap();
assert_eq!(launch.profile.root(), Some(checked.as_path()));
assert!(launch.profile.is_nightly());
}
}
+307 -28
View File
@@ -14,9 +14,16 @@
#[cfg(target_os = "linux")]
mod appimage_env;
#[cfg(test)]
mod build_channel;
mod build_flavor;
mod control_server;
mod default_apps;
mod launch_profile;
mod nightly_session;
mod prefs;
mod process_identity;
mod profile_root;
mod region;
use std::path::PathBuf;
@@ -31,7 +38,7 @@ 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::{DropTarget, DroppedFile, FileIntake, IntakeSender};
use craft::platform::open::{DroppedFile, FileIntake, IntakeSender};
use craft::print::spool::Spool;
use craft::settings::SharedSettings;
use craft::ui::InstallSpec;
@@ -58,6 +65,9 @@ struct App {
spool: Spool,
/// The control server, when `--control` started one; it removes the token file it made.
control: Option<control_server::Control>,
/// The app binary's last step as the app leaves, run once at the end of `finish` (a Nightly
/// quit ends the process inside AppKit's terminate, after eframe's `on_exit`).
exit: Option<Box<dyn FnOnce()>>,
}
impl App {
@@ -95,7 +105,12 @@ impl App {
if let Some(control) = self.control.take() {
control.shut_down();
}
self.app.start_pending_update();
if !launch_profile::current().is_nightly() {
self.app.start_pending_update();
}
if let Some(exit) = self.exit.take() {
exit();
}
}
}
@@ -106,7 +121,7 @@ impl eframe::App for App {
// 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, DropTarget::Elsewhere);
self.drops.dropped(files);
}
embed::before_input(ctx, |out| self.app.frame_input(out));
}
@@ -202,10 +217,12 @@ type MakeDefault = Box<dyn Fn() -> Result<DefaultApp, DefaultAppError>>;
/// What the app takes from its host beyond the runtime: File › Print through the system spooler,
/// personal templates (#2852, made on first save in `Templates` in the settings folder), and making
/// WordCraft the default app for Word documents (#295; macOS has no way to, so no button there).
fn services(spool: Spool, intake: FileIntake) -> Services {
fn services(spool: Spool, intake: FileIntake, nightly: bool) -> Services {
// Nightly never claims the stable app's file associations: the button would rewrite the same
// OS registration the stable WordCraft owns.
#[cfg(any(unix, windows))]
let make_default_app =
(!cfg!(target_os = "macos")).then(|| -> MakeDefault { Box::new(|| craft::platform::default_app::make_default(&default_apps::identity())) });
let make_default_app = (!cfg!(target_os = "macos") && !nightly)
.then(|| -> MakeDefault { Box::new(|| craft::platform::default_app::make_default(&default_apps::identity())) });
#[cfg(not(any(unix, windows)))]
let make_default_app: Option<MakeDefault> = None;
Services {
@@ -256,11 +273,35 @@ fn build_sha() -> &'static str {
option_env!("WORDCRAFT_BUILD_SHA").map(|s| s.get(..8).unwrap_or(s)).unwrap_or("dev")
}
/// Split the command line at its first `--`: the options before it, the documents after it. The
/// Launcher's nightly hand-off arrives as `--` followed by the file names (`launch_profile::parse`
/// puts that separator first), so it is dropped here rather than opened as a document.
fn split_at_delimiter(args: Vec<String>) -> (Vec<String>, Vec<String>) {
match args.iter().position(|a| a == "--") {
Some(i) => {
let mut options = args;
let files = options.split_off(i + 1);
options.pop();
(options, files)
}
None => (args, Vec::new()),
}
}
/// The documents to open, in the order the command line gave them: the words before `--` that the flag
/// loop kept, then the ones after it. The separator moves no document, and the Launcher, which sends
/// none before it, opens just its own file names in order.
fn documents_to_open(before: Vec<String>, after: Vec<String>) -> Vec<String> {
let mut documents = before;
documents.extend(after);
documents
}
/// The arguments as text, and apart the files whose names aren't valid Unicode, such as a Latin-1
/// one (#1440). A `--control` port, a token or a token file that isn't is an error.
fn text_args() -> (Vec<String>, Vec<std::path::PathBuf>) {
fn text_args(arguments: Vec<std::ffi::OsString>) -> (Vec<String>, Vec<std::path::PathBuf>) {
let (mut args, mut files) = (Vec::new(), Vec::new());
for (i, a) in std::env::args_os().skip(1).enumerate() {
for (i, a) in arguments.into_iter().enumerate() {
match a.into_string() {
Ok(a) => args.push(a),
Err(a) if args.last().is_some_and(|p| matches!(p.as_str(), "--control" | "--control-token" | "--control-token-file")) => {
@@ -318,18 +359,106 @@ fn complain(message: std::fmt::Arguments<'_>) {
let _ = std::io::Write::write_fmt(&mut std::io::stderr(), format_args!("wordcraft: {message}\n"));
}
fn initialize_nightly_process_identity() -> Result<(), process_identity::IdentityError> {
process_identity::initialize(
build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1,
wordcraft_ui_egui::os_window::id_for(wordcraft_ui_egui::os_window::LaunchIdentity::NightlyV1),
)
}
/// Whether a refusal may also open a native message box. Standard error always carries the reason;
/// this only adds a box where one renders without the app's event loop. Never on macOS: rfd's alert
/// there needs the AppKit run loop this start has not reached, so a refused nightly launch hung in
/// an invisible modal instead of exiting (GridCraft Mac smoke, 2026-11-26).
fn refusal_dialog(flavor: build_flavor::BuildFlavor, desktop_session: bool, macos: bool) -> bool {
build_flavor::needs_native_error(flavor, desktop_session) && !macos
}
/// Tell the person why a Launcher launch was refused: on standard error always, and with a native
/// message box on a desktop session whose modal renders without the app's run loop (Windows,
/// X11/Wayland) — a Launcher start has no terminal to read standard error from, and on macOS a modal
/// before the event loop never appears.
fn report_launch_profile_error(error: &str) {
complain(format_args!("launch profile: {error}"));
let desktop_session = cfg!(windows)
|| cfg!(target_os = "macos")
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
if refusal_dialog(build_flavor::COMPILED, desktop_session, cfg!(target_os = "macos")) {
if let Err(identity) = initialize_nightly_process_identity() {
complain(format_args!("launch profile: {identity}"));
return;
}
let _ = rfd::MessageDialog::new()
.set_title("WordCraft Nightly")
.set_description(error)
.set_level(rfd::MessageLevel::Error)
.set_buttons(rfd::MessageButtons::Ok)
.show();
}
}
/// Select the immutable launch profile before any startup service or side effect.
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
// The trusted Launcher protocol is decided before logging, crash handling, the update helper,
// fonts, preferences or the settings folder.
let argv: Vec<_> = std::env::args_os().skip(1).collect();
// Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
// --version`: answered before root validation, process identity, IPC or any window.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv))
{
let line = build_flavor::version(build_flavor::COMPILED, env!("WORDCRAFT_BUILT_VERSION"));
let _ = std::io::Write::write_all(&mut std::io::stdout(), format!("{line}\n").as_bytes());
return None;
}
let early = launch_profile::parse(argv)
.and_then(|launch| {
build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?;
initialize_nightly_process_identity().map_err(|error| error.to_string())?;
Ok(launch)
})
.and_then(|launch| launch_profile::prepare(launch, launch_profile::validate_root))
.unwrap_or_else(|error| {
report_launch_profile_error(&error);
std::process::exit(2)
});
let identity = if early.profile.is_nightly() {
wordcraft_ui_egui::os_window::LaunchIdentity::NightlyV1
} else {
wordcraft_ui_egui::os_window::LaunchIdentity::Stable
};
if let Err(error) = launch_profile::install(early.profile).and_then(|()| wordcraft_ui_egui::os_window::select_identity(identity)) {
report_launch_profile_error(&error);
std::process::exit(2);
}
// One data root for everything the app keeps: preferences, window place, logs, recovery,
// fonts, templates, dictionaries and control token files all come from it.
if let Some(root) = launch_profile::current().root()
&& let Err(error) = wordcraft_control_key::use_settings_dir(root.to_path_buf())
{
report_launch_profile_error(&error);
std::process::exit(2);
}
Some(early.args)
}
/// Parses the command line, installs logging and the panic hook, restores preferences and window
/// geometry, opens requested documents or the Start screen, starts the control server when
/// asked, and runs the eframe event loop.
fn main() -> eframe::Result {
// Windows: the print helper is a copy of this program that runs one job in its own process.
// It reads only its own job folder, so it runs before the launch profile is parsed: a Nightly
// wants a profile on every start, and the helper must print without one.
#[cfg(windows)]
if let Some(code) = craft::print::spool::isolated::helper_main() {
std::process::exit(code);
}
let Some(arguments) = prepare_launch() else { return Ok(()) };
// Windows: the update helper is a copy of this program started with `--finish-update`.
// A Nightly never updates itself: the Launcher owns its updates.
#[cfg(windows)]
if let Some(result) = craft::update::self_update::finish(&wordcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
if !launch_profile::current().is_nightly()
&& let Some(result) = craft::update::self_update::finish(&wordcraft_ui_egui::UPDATE_APP, &arguments)
{
std::process::exit(i32::from(result.is_err()));
}
// Linux: before anything reads another program's AppImage variables, or a thread starts (#5653).
@@ -350,11 +479,16 @@ fn main() -> eframe::Result {
log::error!("couldn't start again without another program's AppImage variables, so the self-update is off in this window: {e}");
}
let mut flags = ControlOptions::default();
let mut files = Vec::new();
let mut sample = false;
let (args, other_files) = text_args();
// Only macOS (Finder / LaunchServices) adds these; elsewhere `-NS…` could be a real file name.
let (args, other_files) = text_args(arguments);
// The Launcher's own hand-off: `--` ends the options, so nothing after it is read as one and
// the separator itself never becomes a document.
let (args, after_separator) = split_at_delimiter(args);
// Only macOS (Finder / LaunchServices) adds these, and only to the options: a Finder launch carries
// no separator for them to sit after, and the Launcher starts the app itself, so a document whose
// name merely looks like one of these (`-NSNotes.docx`) is still opened (#7849 review).
let args = if cfg!(target_os = "macos") { without_launch_args(args) } else { args };
let mut documents: Vec<String> = Vec::new();
let mut bad_control: Option<Option<String>> = None;
let mut missing_value: Option<&'static str> = None;
let mut args = args.into_iter().peekable();
@@ -388,6 +522,7 @@ fn main() -> eframe::Result {
},
"--sample" => sample = true,
"--version" => {
// A nightly build reported its channel line before this parser ran.
println!("wordcraft {} ({})", env!("CARGO_PKG_VERSION"), build_sha());
return Ok(());
}
@@ -396,9 +531,12 @@ fn main() -> eframe::Result {
let _ = std::io::Write::write_all(&mut std::io::stdout(), USAGE.as_bytes());
return Ok(());
}
_ => files.push(a),
_ => documents.push(a),
}
}
// After the loop, so a document before `--` opens before the ones after it (a stable launch's
// `a.docx -- b.docx` used to be reversed when the Launcher's list was the one collected first).
let files = documents_to_open(documents, after_separator);
// After the loop, so `--version` later on the line still wins.
if let Some(port) = bad_control {
let got = port.map(|p| format!(", got {p:?}")).unwrap_or_default();
@@ -422,6 +560,13 @@ fn main() -> eframe::Result {
complain(format_args!("--control needs a port number from 1 to 65535, got \"0\""));
std::process::exit(2);
}
// Nightly runs the Launcher's documents only: no control server, token file or automation
// switch, and none inherited from a stable launch's environment.
if launch_profile::current().is_nightly() && (control.port.is_some() || control.token.is_some() || control.token_file.is_some()) {
complain(format_args!("a WordCraft Nightly window does not start a control server; open documents through ArtCraft Launcher"));
std::process::exit(2);
}
let nightly = launch_profile::current().is_nightly();
let settings_dir = wordcraft_control_key::settings_dir();
// The log file lives in the settings directory, next to the preferences; opened after the
// arguments, so `--version` leaves no file behind. Records logged until now are written to it
@@ -440,10 +585,16 @@ fn main() -> eframe::Result {
None => logger.stderr_only(),
}
}
// A Nightly window always carries its own id; a stable one keeps the Flatpak sandbox's id
// when it runs inside one (so docks match the flatpak's desktop file).
let app_id = match launch_profile::current().root() {
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")
.with_app_id("ai.storyteller.wordcraft")
.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)
@@ -504,9 +655,33 @@ fn main() -> eframe::Result {
let _apple_events = craft::platform::open::apple_events::install(sender);
#[cfg(not(target_os = "macos"))]
drop(sender);
// Nightly's own health record: one owner per profile, cleared only by a controlled return.
let (nightly_record, health_unavailable) = match nightly_session::Session::begin_with_health(
launch_profile::current().root(),
env!("WORDCRAFT_BUILT_VERSION"),
option_env!("WORDCRAFT_BUILD_SHA"),
) {
Ok(pair) => pair,
Err(error) => {
log::warn!("Nightly session health is unavailable: {error}");
(None, launch_profile::current().is_nightly())
}
};
let session_health_warning: Option<String> = health_unavailable.then(|| {
"WordCraft Nightly could not record session health in its private profile. You can still edit, but abnormal-exit detection is unavailable."
.to_string()
});
let previous_nightly_unclean = nightly_record.as_ref().is_some_and(nightly_session::Session::previous_unclean);
let nightly_watch: nightly_session::Shared = Arc::new(Mutex::new(nightly_record));
let unclean_notice_shown = Arc::new(std::sync::atomic::AtomicBool::new(false));
// The window body and its exit hook each take a clone of the flag; the return path keeps the
// other, so a start that created no window can still finish the record.
let session_for_exit = nightly_watch.clone();
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",
wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity()),
options,
Box::new(move |cc| {
let ctx = cc.egui_ctx.clone();
@@ -528,7 +703,7 @@ fn main() -> eframe::Result {
);
let shell = ShellInfo::current().backend(if x11 { Backend::X11 } else { Backend::from_env() });
let spec = InstallSpec::new(shell, Arc::new(SystemWindows))
.app_id("ai.storyteller.wordcraft")
.app_id(wordcraft_ui_egui::os_window::app_id())
.system(SystemReader::start(wake))
.clipboard(Clipboard::new(SystemClipboard::new().decoder(decode_png)))
.placement(placement);
@@ -547,19 +722,31 @@ fn main() -> eframe::Result {
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)).with_host(host).with_settings(settings.clone());
let mut app = WordApp::new(session, services(spool.clone(), intake, nightly)).with_host(host).with_settings(settings.clone());
// PLAN: writer note 9 puts `with_settings` after `with_control`; it comes first here because
// the region check below reads the saved region the settings apply.
if std::env::var("WORDCRAFT_FILE_DIALOG").is_ok_and(|v| v.trim().eq_ignore_ascii_case("builtin")) {
app = app.with_fallback_chooser(true);
}
app.set_startup_update_check(true);
// After the preferences, so the reason it gives is in the interface language.
if updates_unsafe {
app.disable_self_update();
if nightly {
// The Launcher installs Nightly; Help › Check for Updates says so instead.
app.use_launcher_updates();
} else {
app.set_startup_update_check(true);
// After the preferences, so the reason it gives is in the interface language.
if updates_unsafe {
app.disable_self_update();
}
}
// Language packs from the suite's font store; an Install click is the person's own.
wordcraft_engine::packs::use_font_store(true);
// Nightly keeps its own store in the profile, so a pack installed there is not a
// change to the stable apps' shared fonts.
match launch_profile::current().root() {
Some(root) => wordcraft_engine::packs::use_font_store_in(root.join("FontStore"), true),
None => {
wordcraft_engine::packs::use_font_store(true);
}
}
// A region chosen in File › Options replaces the system's for the first blank
// document too (#838).
if !sample && app.session.prefs.region.is_some() {
@@ -576,7 +763,8 @@ fn main() -> eframe::Result {
}
}
let mut control_server = None;
if let Some(port) = control.port
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())
{
@@ -598,9 +786,32 @@ fn main() -> eframe::Result {
for f in other_files {
open_non_unicode(&mut app, &f);
}
Ok(Box::new(App { app, panels, drops, settings, spool, control: control_server }))
// 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 {
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));
})),
}))
}),
);
// 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.
if let Err(e) = exit_settings.lock().flush() {
log::warn!("preferences: {e}");
@@ -802,8 +1013,8 @@ mod smoke {
let (intake, sender) = FileIntake::new(Wake::new(|| {}));
let drops = intake.sender();
let session = Session::new(wordcraft_doc::Document::new());
let app = WordApp::new(session, services(spool.clone(), intake)).with_host(host).with_settings(settings.clone());
Run { app: App { app, panels, drops, settings, spool, control: None }, frames, ctx, sender }
let app = WordApp::new(session, services(spool.clone(), intake, false)).with_host(host).with_settings(settings.clone());
Run { app: App { app, panels, drops, settings, spool, control: None, exit: None }, frames, ctx, sender }
}
/// One frame as eframe runs it: the input hook once, the logic once, the UI per pass.
@@ -867,7 +1078,7 @@ mod smoke {
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("dropped.txt");
std::fs::write(&path, "Dropped words").unwrap();
run.sender.dropped(vec![DroppedFile { path: Some(path), name: "dropped.txt".into(), bytes: None }], DropTarget::Elsewhere);
run.sender.dropped(vec![DroppedFile { path: Some(path), name: "dropped.txt".into(), bytes: None }]);
run.settle();
assert!(run.app.app.session.doc.plain_text(wordcraft_doc::StoryRef::Body).contains("Dropped words"), "the dropped file opened");
let _ = std::fs::remove_dir_all(dir);
@@ -908,3 +1119,71 @@ mod smoke {
}
}
}
#[cfg(test)]
mod command_line_tests {
use super::{documents_to_open, split_at_delimiter};
/// The argv the Launcher starts a nightly with, as `prepare_launch` hands it on. The root is the one this
/// platform would pass: `/nightly-data/...` has no drive prefix, so on Windows `parse` rightly refuses it.
fn launcher_argv(tail: &[&str]) -> Vec<String> {
let mut argv: Vec<std::ffi::OsString> = ["--launch-profile", "nightly-v1", "--profile-root", super::launch_profile::launcher_root(), "--"]
.iter()
.map(std::ffi::OsString::from)
.collect();
argv.extend(tail.iter().map(std::ffi::OsString::from));
super::launch_profile::parse(argv).unwrap().args.iter().map(|a| a.to_string_lossy().into_owned()).collect()
}
#[test]
fn the_launchers_separator_is_never_a_document() {
let (options, files) = split_at_delimiter(launcher_argv(&[]));
assert!(options.is_empty(), "{options:?}");
assert!(files.is_empty(), "the separator must not reach the documents: {files:?}");
}
#[test]
fn documents_after_the_separator_are_kept_in_order() {
let (options, files) = split_at_delimiter(launcher_argv(&["a.file"]));
assert!(options.is_empty(), "{options:?}");
assert_eq!(files, ["a.file"]);
let (_, files) = split_at_delimiter(launcher_argv(&["a.file", "--version", "--sample"]));
assert_eq!(files, ["a.file", "--version", "--sample"], "after -- every word is a document");
// A real document path, as Windows hands one on: kept whole, in order, backslashes and spaces intact.
let (_, files) = split_at_delimiter(launcher_argv(&[r"C:\Users\user\Holiday letter.docx", "a.file"]));
assert_eq!(files, [r"C:\Users\user\Holiday letter.docx", "a.file"], "a real path after -- stays a document, in order");
}
/// A document whose name looks like a LaunchServices option is one only after the separator: the strip
/// for macOS runs on the options, after the split, so `-- -NSNotes.docx report.docx` opens both.
#[test]
fn a_document_named_like_a_launch_argument_survives_the_separator() {
let (options, after) = split_at_delimiter(["-psn_0_12345", "--", "-NSNotes.docx", "report.docx"].map(String::from).to_vec());
assert!(super::without_launch_args(options).is_empty(), "the option before the separator goes");
let hazard: Vec<String> = ["-NSNotes.docx", "report.docx"].map(String::from).to_vec();
assert!(super::without_launch_args(hazard).is_empty(), "before the split the strip takes the document and the one after it");
assert_eq!(documents_to_open(Vec::new(), after), ["-NSNotes.docx", "report.docx"], "what follows the separator is opened, in order");
}
/// A stable line that carries its own separator: `a.file` before `--` opens before `b.file` after it.
/// The flag loop keeps `a.file` (its `_` arm, one push) and `documents_to_open` puts the two lists
/// back in command-line order; the reverse, appending the loop's list to the separator's, opened them
/// backwards (found in review of #7849).
#[test]
fn documents_before_the_separator_keep_their_place_before_the_ones_after_it() {
let (options, after) = split_at_delimiter(["--sample", "a.file", "--", "b.file"].map(String::from).to_vec());
assert_eq!(options, ["--sample", "a.file"], "--sample is a switch and a.file is left for the loop");
assert_eq!(documents_to_open(vec!["a.file".into()], after), ["a.file", "b.file"]);
let (_, after) = split_at_delimiter(launcher_argv(&["b.file"]));
assert_eq!(documents_to_open(Vec::new(), after), ["b.file"], "the Launcher sends nothing before the separator");
}
#[test]
fn a_refusal_never_blocks_on_a_modal_before_the_event_loop_on_macos() {
use crate::build_flavor::BuildFlavor;
assert!(super::refusal_dialog(BuildFlavor::NightlyV1, true, false), "a desktop refusal still shows the box where one renders");
assert!(!super::refusal_dialog(BuildFlavor::NightlyV1, true, true), "macOS has no run loop yet: the modal would hang");
assert!(!super::refusal_dialog(BuildFlavor::NightlyV1, false, false), "a headless session has no box");
assert!(!super::refusal_dialog(BuildFlavor::Stable, true, false), "only a nightly refusal explains itself in a box");
}
}
+266
View File
@@ -0,0 +1,266 @@
//! App-private Nightly session health, not telemetry or a Launcher protocol.
//! A live owner holds a separate persistent lease; secondary launches never rewrite its record.
//! Dropping the guard does not clear the marker. Only the app's controlled return path does.
use std::fs::{File, OpenOptions};
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError};
const RECORD: &str = "nightly-session.json";
const LEASE: &str = "nightly-session.lock";
const MAX_METADATA_BYTES: usize = 256;
pub struct Session {
_lease: File,
path: PathBuf,
own_record: Vec<u8>,
previous_unclean: bool,
}
fn regular_or_missing(path: &Path) -> io::Result<bool> {
match std::fs::symlink_metadata(path) {
Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true),
Ok(_) => Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory")),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
Err(error) => Err(error),
}
}
/// Write `bytes` to `path` through a fresh temporary file in the same folder and a rename: the
/// destination entry is replaced, never followed, so a link planted at `path` is not written
/// through. The file is synced and the folder is synced after the rename.
fn write_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> {
static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
let directory = path.parent().ok_or_else(|| io::Error::other("the session record has no folder"))?;
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let temporary = directory.join(format!(".{name}.{}-{}", std::process::id(), NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)));
let mut file = OpenOptions::new().write(true).create_new(true).open(&temporary)?;
let written = std::io::Write::write_all(&mut file, bytes).and_then(|()| file.sync_all());
drop(file);
if let Err(error) = written {
let _ = std::fs::remove_file(&temporary);
return Err(error);
}
if let Err(error) = std::fs::rename(&temporary, path) {
let _ = std::fs::remove_file(&temporary);
return Err(error);
}
if let Ok(directory) = File::open(directory) {
let _ = directory.sync_all();
}
Ok(())
}
/// The owner's session, shared by the app's exit hook (macOS: a quit ends the process inside
/// AppKit's terminate) and the code after the event loop.
pub type Shared = Arc<Mutex<Option<Session>>>;
/// The controlled return ([`Session::finish`]) by whichever path comes first; later calls do nothing.
pub fn finish_once(shared: &Shared, unclean_notice_shown: bool) {
let watch = shared.lock().unwrap_or_else(PoisonError::into_inner).take();
if let Some(watch) = watch
&& let Err(error) = watch.finish(unclean_notice_shown)
{
log::warn!("Nightly session state was left intact: {error}");
}
}
impl Session {
/// The warning belongs to this window: a busy secondary has no health-record coverage,
/// while Stable and a lease-owning Nightly window preserve their existing result.
pub fn begin_with_health(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<(Option<Self>, bool)> {
let watch = Self::begin(root, version, commit)?;
let unavailable = root.is_some() && watch.is_none();
Ok((watch, unavailable))
}
/// `None` is stable or another owner of this profile. Neither case touches the record.
/// The supplied root must already be the validated private Nightly profile.
pub fn begin(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<Option<Self>> {
let Some(root) = root else { return Ok(None) };
if version.is_empty() || version.len() > MAX_METADATA_BYTES || commit.is_some_and(|value| value.len() > MAX_METADATA_BYTES) {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large"));
}
let lease_path = root.join(LEASE);
regular_or_missing(&lease_path)?;
let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?;
match lease.try_lock() {
Ok(()) => {}
Err(std::fs::TryLockError::WouldBlock) => return Ok(None),
Err(std::fs::TryLockError::Error(error)) => return Err(error),
}
let path = root.join(RECORD);
let previous_unclean = regular_or_missing(&path)?;
let own_record = serde_json::to_vec(&serde_json::json!({
"schema_version": 1,
"channel": "nightly-v1",
"version": version,
"commit": commit.filter(|value| !value.is_empty()),
}))?;
write_no_follow(&path, &own_record)?;
Ok(Some(Self { _lease: lease, path, own_record, previous_unclean }))
}
pub fn previous_unclean(&self) -> bool {
self.previous_unclean
}
/// Controlled return. If an earlier session's interruption was detected but no window showed
/// it yet, the record is left for the next owner to report; otherwise this is [`Self::complete`].
pub fn finish(self, unclean_notice_shown: bool) -> io::Result<()> {
if self.previous_unclean && !unclean_notice_shown {
return Ok(());
}
self.complete()
}
/// Controlled event-loop completion includes a handled startup error, not only exit 0.
/// An unwind, abort, forced exit or killed process never calls this method.
pub fn complete(self) -> io::Result<()> {
if !regular_or_missing(&self.path)? {
return Ok(());
}
let mut current = Vec::new();
File::open(&self.path)?.take(self.own_record.len() as u64 + 1).read_to_end(&mut current)?;
if current != self.own_record {
return Err(io::Error::other("Nightly session state changed; leaving it intact"));
}
std::fs::remove_file(&self.path)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicU64, Ordering};
struct Fixture(PathBuf);
impl Fixture {
fn new() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
loop {
let path =
std::env::temp_dir().join(format!("wordcraft-nightly-session-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
match std::fs::create_dir(&path) {
Ok(()) => return Self(path),
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create owned fixture: {error}"),
}
}
}
}
impl Drop for Fixture {
fn drop(&mut self) {
std::fs::remove_dir_all(&self.0).unwrap();
}
}
#[test]
fn busy_secondary_reports_unavailable_without_replacing_the_owner_record() {
let fixture = Fixture::new();
let (stable, warning) = Session::begin_with_health(None, "stable", None).unwrap();
assert!(stable.is_none() && !warning);
let (first, warning) = Session::begin_with_health(Some(&fixture.0), "nightly", Some("owned-commit")).unwrap();
assert!(!warning);
let first = first.unwrap();
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
let (secondary, warning) = Session::begin_with_health(Some(&fixture.0), "secondary", None).unwrap();
assert!(secondary.is_none() && warning, "a secondary window cannot claim recorded exit/crash coverage");
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record);
first.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn controlled_completion_is_clean_but_an_unfinished_owner_is_reported_next_time() {
let fixture = Fixture::new();
let first = Session::begin(Some(&fixture.0), "first", Some("recorded-commit")).unwrap().unwrap();
assert!(!first.previous_unclean());
let own = std::fs::read(fixture.0.join(RECORD)).unwrap();
assert!(Session::begin(Some(&fixture.0), "secondary", None).unwrap().is_none());
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), own, "a busy secondary must not replace the owner's record");
first.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
let unimportant = Session::begin(Some(&fixture.0), "second", None).unwrap().unwrap();
assert!(!unimportant.previous_unclean());
drop(unimportant); // Unwind/abnormal-path ownership release, not a controlled completion.
let next = Session::begin(Some(&fixture.0), "third", None).unwrap().unwrap();
assert!(next.previous_unclean());
next.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn an_interruption_no_window_showed_survives_a_handled_startup_failure() {
let fixture = Fixture::new();
drop(Session::begin(Some(&fixture.0), "crashed", None).unwrap().unwrap());
// The window never started: no notice was shown.
let failed = Session::begin(Some(&fixture.0), "startup-failed", None).unwrap().unwrap();
assert!(failed.previous_unclean());
failed.finish(false).unwrap();
// The next start still sees the interruption and shows it.
let next = Session::begin(Some(&fixture.0), "next", None).unwrap().unwrap();
assert!(next.previous_unclean());
next.finish(true).unwrap();
assert!(!fixture.0.join(RECORD).exists(), "a session that showed the notice clears its record");
let clean = Session::begin(Some(&fixture.0), "clean", None).unwrap().unwrap();
assert!(!clean.previous_unclean());
clean.finish(false).unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn the_exit_hook_and_the_return_path_finish_the_session_once() {
let fixture = Fixture::new();
let shared: Shared = Arc::new(Mutex::new(Session::begin(Some(&fixture.0), "quitting", None).unwrap()));
// The exit hook (macOS quit: the only path that runs there).
finish_once(&shared, false);
assert!(!fixture.0.join(RECORD).exists(), "a quit that ran the exit hook is a clean exit");
// Elsewhere the return path runs too, by then possibly after a successor took the profile.
let successor = Session::begin(Some(&fixture.0), "successor", None).unwrap().unwrap();
assert!(!successor.previous_unclean());
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
finish_once(&shared, false);
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record, "the second finish must not touch a successor's record");
successor.complete().unwrap();
}
#[test]
fn cleanup_never_removes_an_unknown_changed_record() {
let fixture = Fixture::new();
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
std::fs::write(fixture.0.join(RECORD), b"replacement owned by someone else").unwrap();
assert!(watch.complete().is_err());
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"replacement owned by someone else");
}
#[test]
fn provenance_is_bounded_and_never_collects_documents_paths_or_diagnostics() {
let fixture = Fixture::new();
assert!(Session::begin(Some(&fixture.0), &"x".repeat(MAX_METADATA_BYTES + 1), None).is_err());
assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 0);
assert!(Session::begin(None, "", None).unwrap().is_none(), "stable has no session-health side effects");
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
let data: serde_json::Value = serde_json::from_slice(&std::fs::read(fixture.0.join(RECORD)).unwrap()).unwrap();
let fields = data.as_object().unwrap().keys().map(String::as_str).collect::<std::collections::BTreeSet<_>>();
assert_eq!(fields, ["schema_version", "channel", "version", "commit"].into_iter().collect());
assert!(data["commit"].is_null(), "missing provenance must not be invented");
watch.complete().unwrap();
}
#[test]
#[cfg(unix)]
fn reserved_state_aliases_do_not_modify_external_files() {
let fixture = Fixture::new();
let external = fixture.0.join("stable-document");
std::fs::write(&external, b"stable bytes").unwrap();
for name in [LEASE, RECORD] {
let alias = fixture.0.join(name);
std::os::unix::fs::symlink(&external, &alias).unwrap();
assert!(Session::begin(Some(&fixture.0), "nightly", None).is_err());
assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes");
std::fs::remove_file(alias).unwrap();
}
}
}
+4 -2
View File
@@ -15,9 +15,11 @@ use wordcraft_ui_egui::prefs::{Prefs, import_legacy_window, legacy_ui_json};
/// The most of an old `ui.json` read for its window entry; the file is a few kilobytes.
const LEGACY_LIMIT: u64 = 8 << 20;
/// Whether this run reads and writes preferences. `WORDCRAFT_NO_PREFS` turns them off.
/// Whether this run reads and writes preferences. `WORDCRAFT_NO_PREFS` turns them off; a Nightly
/// profile always keeps its own, so an inherited developer switch cannot leave the app with no
/// preferences folder at all.
pub fn enabled() -> bool {
std::env::var_os("WORDCRAFT_NO_PREFS").is_none()
crate::launch_profile::current().is_nightly() || std::env::var_os("WORDCRAFT_NO_PREFS").is_none()
}
/// `custom-dictionary.txt` in the settings folder: the words Add to Dictionary kept (#40).
+70
View File
@@ -0,0 +1,70 @@
//! Set the immutable nightly Windows identity before any native window or COM service.
//! Stable deliberately leaves its implicit shortcut/path identity unchanged.
use std::sync::OnceLock;
#[derive(Clone, Debug, thiserror::Error)]
pub enum IdentityError {
#[error("{0}")]
Configuration(String),
}
pub fn initialize(nightly: bool, app_id: &str) -> Result<(), IdentityError> {
configure(nightly && cfg!(windows), app_id, |id| {
static RESULT: OnceLock<Result<(), String>> = OnceLock::new();
RESULT
.get_or_init(|| {
#[cfg(windows)]
{
winsafe::SetCurrentProcessExplicitAppUserModelID(id)
.map_err(|error| format!("cannot set the nightly Windows identity: {error}"))?;
let actual = winsafe::GetCurrentProcessExplicitAppUserModelID()
.map_err(|error| format!("cannot read back the nightly Windows identity: {error}"))?;
if actual != id {
return Err("the native Windows identity did not match the selected nightly channel".into());
}
Ok(())
}
#[cfg(not(windows))]
{
let _ = id;
Ok(())
}
})
.clone()
})
.map_err(IdentityError::Configuration)
}
fn configure(explicit_nightly: bool, app_id: &str, set: impl FnOnce(&str) -> Result<(), String>) -> Result<(), String> {
if explicit_nightly { set(app_id) } else { Ok(()) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn stable_does_not_call_the_explicit_identity_api() {
configure(false, "nightly-id", |_| panic!("stable identity must remain implicit")).unwrap();
}
#[test]
fn nightly_applies_the_supplied_identity_once() {
let calls = std::cell::Cell::new(0);
configure(true, "nightly-id", |id| {
assert_eq!(id, "nightly-id");
calls.set(calls.get() + 1);
Ok(())
})
.unwrap();
assert_eq!(calls.get(), 1);
}
#[test]
fn native_identity_failure_is_returned_instead_of_starting_a_window() {
let started = std::cell::Cell::new(false);
let result = configure(true, "nightly-id", |_| Err("native identity refused".into())).map(|()| started.set(true));
assert_eq!(result.unwrap_err(), "native identity refused");
assert!(!started.get());
}
}
+535
View File
@@ -0,0 +1,535 @@
//! App-owned nightly profile fences; no stable fallback, migration or process environment changes.
//!
//! WordCraft keeps all of its user state in one settings folder (`wordcraft_control_key::settings_dir`):
//! `config.toml`, `window.json`, `logs/`, `recovery/`, `fonts/`, `Templates/`,
//! `custom-dictionary.txt` and the control token files. The suite's shared font store
//! (`Craft Fonts` / `craft-fonts`, which also holds installed Language packs) is the one other
//! per-user folder the app writes, and Nightly points it at the profile too
//! (`wordcraft_engine::packs::use_font_store_in`). Every stable location of either is fenced here.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
/// The app id of the nightly Flatpak this build ships in (`packaging/linux/flatpak-bundle.sh`).
pub const NIGHTLY_FLATPAK_ID: &str = "ai.storyteller.wordcraft.nightly";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Platform {
Windows,
Linux,
Mac,
}
impl Platform {
fn current() -> Result<Self, String> {
match std::env::consts::OS {
"windows" => Ok(Self::Windows),
"linux" => Ok(Self::Linux),
"macos" => Ok(Self::Mac),
_ => Err("nightly-v1 is not defined for this operating system".into()),
}
}
fn ignores_case(self) -> bool {
self != Self::Linux
}
}
fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
return Err(format!("{label} must be absolute and contain no parent traversal"));
}
Ok(path)
}
fn required_base(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Result<PathBuf, String> {
let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?;
absolute(PathBuf::from(value), key)
}
fn xdg_base(env: &impl Fn(&str) -> Option<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
match env(key).filter(|v| !v.is_empty()) {
Some(value) => absolute(PathBuf::from(value), key),
None => Ok(required_base(env, "HOME")?.join(fallback)),
}
}
/// Resolve existing ancestors before creating anything. A dangling link or inaccessible ancestor
/// is not a missing directory that may be replaced or followed later.
fn canonical_future(path: &Path) -> Result<PathBuf, String> {
let mut parent = path;
let mut missing = Vec::new();
loop {
match std::fs::symlink_metadata(parent) {
Ok(_) => break,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string());
parent = parent.parent().ok_or("the profile root has no existing ancestor")?;
}
Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")),
}
}
let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?;
for part in missing.into_iter().rev() {
resolved.push(part);
}
Ok(resolved)
}
fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool {
let parts = |p: &Path| {
p.components()
.map(|c| {
let value = c.as_os_str().to_string_lossy().into_owned();
if platform.ignores_case() { value.to_lowercase() } else { value }
})
.collect::<Vec<_>>()
};
let (a, b) = (parts(a), parts(b));
a.starts_with(&b) || b.starts_with(&a)
}
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
let parent = exe.parent().ok_or("cannot establish the installation boundary")?;
if platform == Platform::Mac {
// A profile in Resources is still inside the versioned install, not beside MacOS.
if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) {
return Ok(bundle.to_path_buf());
}
}
Ok(parent.to_path_buf())
}
fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>, exe: &Path) -> Result<Vec<PathBuf>, String> {
let mut roots = match platform {
Platform::Windows => {
let mut roots = ["APPDATA", "LOCALAPPDATA"]
.into_iter()
.map(|key| required_base(env, key).map(|p| p.join("WordCraft")))
.collect::<Result<Vec<_>, _>>()?;
// The suite's shared font store and the MSI's default per-user and per-machine folders.
roots.push(required_base(env, "LOCALAPPDATA")?.join("Craft Fonts"));
roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("WordCraft"));
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
if let Some(base) = env(key).filter(|v| !v.is_empty()) {
roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("WordCraft"));
}
}
roots
}
Platform::Linux => {
let mut roots =
[("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")]
.into_iter()
.map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("wordcraft")))
.collect::<Result<Vec<_>, _>>()?;
// The shared font store (fonts and Language packs) and the native packages' locations.
roots.push(xdg_base(env, "XDG_DATA_HOME", ".local/share")?.join("craft-fonts"));
roots.extend(["/usr/bin/wordcraft", "/usr/local/bin/wordcraft", "/opt/wordcraft"].map(PathBuf::from));
// The stable Flatpak keeps its data in its own per-app folder.
roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.wordcraft"));
roots
}
Platform::Mac => {
let home = required_base(env, "HOME")?;
let library = home.join("Library");
vec![
library.join("Application Support/WordCraft"),
library.join("Caches/WordCraft"),
library.join("Caches/ai.storyteller.wordcraft"),
library.join("Preferences/WordCraft"),
library.join("Preferences/ai.storyteller.wordcraft.plist"),
library.join("Saved Application State/ai.storyteller.wordcraft.savedState"),
library.join("Application Support/Craft Fonts"),
home.join("Applications/WordCraft.app"),
PathBuf::from("/Applications/WordCraft.app"),
]
}
};
roots.push(installation_boundary(platform, exe)?);
roots.into_iter().map(|p| canonical_future(&p)).collect()
}
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
let child = canonical_future(&chosen.join(name))?;
if child == chosen || !child.starts_with(&chosen) {
return Err(format!("the nightly {label} must stay inside its selected profile"));
}
Ok(child)
}
/// Every existing entry directly in the profile (`config.toml`, `logs`, `recovery`, `fonts`,
/// `Templates`, `window.json` and so on) must resolve inside it, so a link there cannot point
/// Nightly's writes at another app's data.
fn entries_stay_inside(root: &Path) -> Result<(), String> {
let entries = match std::fs::read_dir(root) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")),
};
for entry in entries {
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
private_subdirectory(root, entry.file_name(), "profile entry")?;
}
Ok(())
}
/// The app's exclusive create probe: a file only this process can have made, created and removed.
pub fn probe_writable(dir: &Path) -> std::io::Result<()> {
static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
let probe = dir.join(format!(".nightly-writable-{}-{}", std::process::id(), NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)));
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
drop(file);
std::fs::remove_file(probe)
}
/// The writable hook is injected so filesystem boundary tests exercise the real policy without
/// starting the app or creating the profile of the person running them.
pub fn validate(
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
validate_for(Platform::current()?, root, env, exe, writable)
}
fn validate_for(
platform: Platform,
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
absolute(root.to_path_buf(), "the nightly profile root")?;
// The developer switch that points a run at any folder: Nightly's folder comes from the Launcher.
if env("WORDCRAFT_PROFILE_DIR").is_some_and(|v| !v.is_empty()) {
return Err("nightly-v1 cannot be combined with WORDCRAFT_PROFILE_DIR".into());
}
// These rows are native tar/app-bundle launches, not a Flatpak package. Inheriting a Flatpak
// runtime could point another profile at the stable app's token files; the nightly Flatpak
// itself (`packaging/linux/flatpak-bundle.sh`) is the one sandbox this build ships in.
if platform != Platform::Windows
&& let Some(id) = env("FLATPAK_ID").filter(|v| !v.is_empty())
&& id != NIGHTLY_FLATPAK_ID
{
return Err("nightly-v1 native packages cannot inherit a Flatpak instance; launch through the native Launcher".into());
}
let chosen = canonical_future(root)?;
let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?;
let forbidden = forbidden_roots(platform, &env, &exe)?;
if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) {
return Err("the nightly root must not overlap stable data or an installation".into());
}
// Existing aliases under the profile must not redirect its own subfolders elsewhere.
entries_stay_inside(&chosen)?;
// Recovery can read, adopt and sweep entries; a link there must never leave the profile.
private_subdirectory(&chosen, "recovery", "recovery folder")?;
let mut create = std::fs::DirBuilder::new();
create.recursive(true);
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt as _;
create.mode(0o700);
}
create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?;
let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?;
if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) {
return Err("the nightly profile changed while it was being validated".into());
}
private_subdirectory(&confirmed, "recovery", "recovery folder")?;
entries_stay_inside(&confirmed)?;
writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?;
Ok(confirmed)
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicU64, Ordering};
struct Fixture {
root: PathBuf,
env: BTreeMap<String, OsString>,
exe: PathBuf,
}
impl Fixture {
fn new() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
let root = loop {
let candidate =
std::env::temp_dir().join(format!("wordcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
match std::fs::create_dir(&candidate) {
Ok(()) => break std::fs::canonicalize(candidate).unwrap(),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create owned fixture: {error}"),
}
};
let home = root.join("home");
let exe = root.join("install/wordcraft");
std::fs::create_dir_all(&home).unwrap();
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
std::fs::write(&exe, b"fixture executable, never run").unwrap();
let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))]
.into_iter()
.map(|(key, value)| (key.into(), value.into_os_string()))
.collect();
Self { root, env, exe }
}
fn get(&self, key: &str) -> Option<OsString> {
self.env.get(key).cloned()
}
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
validate_for(
platform,
root,
|key| self.get(key),
Some(&self.exe),
|dir| {
let probe = dir.join("exclusive-test-probe");
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
drop(file);
std::fs::remove_file(probe)
},
)
}
fn home(&self) -> PathBuf {
PathBuf::from(self.get("HOME").unwrap())
}
}
impl Drop for Fixture {
fn drop(&mut self) {
// Only the directory successfully created by this fixture is owned for removal.
std::fs::remove_dir_all(&self.root).unwrap();
}
}
#[test]
fn linux_fences_the_settings_folders_font_store_and_packages_but_allows_the_launcher_sibling() {
let mut fixture = Fixture::new();
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
fixture.env.insert(key.into(), fixture.root.join(key).into_os_string());
}
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
let stable = PathBuf::from(fixture.get(key).unwrap()).join("wordcraft");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap();
for candidate in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
}
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
}
let fonts = PathBuf::from(fixture.get("XDG_DATA_HOME").unwrap()).join("craft-fonts");
std::fs::create_dir_all(fonts.join("language-packs")).unwrap();
for candidate in [fonts.clone(), fonts.join("nightly")] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
}
for package in ["/usr/bin/wordcraft", "/usr/local/bin/wordcraft", "/opt/wordcraft"] {
assert!(fixture.check(Platform::Linux, &PathBuf::from(package)).is_err());
}
let data = PathBuf::from(fixture.get("XDG_DATA_HOME").unwrap());
let nightly = data.join("ArtCraftLauncher/nightly/profiles/wordcraft");
assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly);
assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0);
}
#[test]
fn linux_fences_the_stable_flatpak_data_folder() {
let fixture = Fixture::new();
let flatpak = fixture.home().join(".var/app/ai.storyteller.wordcraft");
for candidate in [flatpak.clone(), flatpak.join("data/nightly")] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
}
assert!(!flatpak.exists());
assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.launcher/nightly")).is_ok());
// Inside the Nightly Flatpak, XDG_DATA_HOME is this app's own persistent data folder, so
// the launcher's profile lands there rather than on the discarded sandbox home.
let nightly = fixture.home().join(".var/app/ai.storyteller.wordcraft.nightly/data/wordcraft-nightly");
assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly);
}
#[test]
fn mac_fences_the_app_library_subtrees_the_shared_font_store_and_the_whole_bundle() {
let mut fixture = Fixture::new();
fixture.exe = fixture.root.join("install/WordCraft Nightly.app/Contents/MacOS/WordCraft");
std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap();
std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap();
let library = fixture.home().join("Library");
for suffix in [
"Application Support/WordCraft",
"Caches/WordCraft",
"Caches/ai.storyteller.wordcraft",
"Preferences/WordCraft",
"Saved Application State/ai.storyteller.wordcraft.savedState",
"Application Support/Craft Fonts",
] {
let stable = library.join(suffix);
assert!(fixture.check(Platform::Mac, &stable.join("nightly")).unwrap_err().contains("overlap"));
assert!(!stable.exists());
}
let inside_resources = fixture.exe.parent().unwrap().parent().unwrap().join("Resources/profile");
assert!(fixture.check(Platform::Mac, &inside_resources).unwrap_err().contains("overlap"));
assert!(!inside_resources.exists());
let valid = library.join("Application Support/ArtCraftLauncher/nightly/profiles/wordcraft");
assert_eq!(fixture.check(Platform::Mac, &valid).unwrap(), valid);
}
#[test]
fn windows_roaming_local_font_store_and_install_fences_remain_active() {
let fixture = Fixture::new();
let mut fixture = fixture;
for key in ["APPDATA", "LOCALAPPDATA"] {
let stable = PathBuf::from(fixture.get(key).unwrap()).join("WordCraft");
assert!(fixture.check(Platform::Windows, &stable.join("nightly")).unwrap_err().contains("overlap"));
assert!(!stable.exists());
}
let fonts = PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join("Craft Fonts");
assert!(fixture.check(Platform::Windows, &fonts.join("nightly")).unwrap_err().contains("overlap"));
assert!(fixture.check(Platform::Windows, &fixture.exe.parent().unwrap().join("profile")).is_err());
let local = PathBuf::from(fixture.get("LOCALAPPDATA").unwrap());
let per_user = local.join("Programs").join("ArtCraft").join("WordCraft");
assert!(fixture.check(Platform::Windows, &per_user.join("nightly")).unwrap_err().contains("overlap"));
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
let base = fixture.root.join(format!("machine {key}"));
fixture.env.insert(key.into(), base.clone().into_os_string());
let machine = base.join("ArtCraft").join("WordCraft");
assert!(fixture.check(Platform::Windows, &machine.join("nightly")).unwrap_err().contains("overlap"));
assert!(!machine.exists());
}
let sibling = local.join("Programs").join("ArtCraft").join("ArtCraftLauncher").join("nightly").join("wordcraft");
assert!(fixture.check(Platform::Windows, &sibling).is_ok(), "the Launcher's own Programs sibling is not WordCraft's install");
}
#[test]
fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() {
let fixture = Fixture::new();
let root = fixture.home().join("nightly/profiles/wordcraft");
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
assert!(overlaps(&root, &root.join("recovery"), platform));
assert!(overlaps(&root.join("recovery"), &root, platform));
assert!(!overlaps(&root, &root.with_file_name("wordcraft-other"), platform));
}
}
#[cfg(unix)]
#[test]
fn recovery_and_entry_aliases_cannot_leave_the_profile_and_stable_bytes_stay_untouched() {
let fixture = Fixture::new();
let stable = fixture.home().join(".config/wordcraft/recovery");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-autosave"), b"stable recovery bytes").unwrap();
for (index, target) in [stable.clone(), fixture.root.join("missing recovery target")].into_iter().enumerate() {
let private = fixture.root.join(format!("nightly-{index}"));
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&target, private.join("recovery")).unwrap();
let probed = std::cell::Cell::new(false);
let result = validate_for(
Platform::Linux,
&private,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
probed.set(true);
Ok(())
},
);
assert!(result.is_err(), "recovery must not escape the private profile or follow a dangling alias");
assert!(!probed.get());
}
for name in ["logs", "fonts", "config.toml"] {
let private = fixture.root.join(format!("nightly-entry-{name}"));
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&stable, private.join(name)).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_err(), "{name} must not lead outside the profile");
}
assert_eq!(std::fs::read(stable.join("stable-autosave")).unwrap(), b"stable recovery bytes");
assert_eq!(std::fs::read_dir(stable).unwrap().count(), 1);
}
#[cfg(unix)]
#[test]
fn a_recovery_alias_inside_the_profile_keeps_it_usable() {
let fixture = Fixture::new();
let private = fixture.root.join("nightly-private");
let recovery = private.join("private-recovery");
std::fs::create_dir_all(&recovery).unwrap();
std::os::unix::fs::symlink(&recovery, private.join("recovery")).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_ok());
assert_eq!(std::fs::canonicalize(private.join("recovery")).unwrap(), recovery);
}
#[test]
fn ambiguous_environment_and_non_native_sandbox_are_refused_before_creation() {
let mut fixture = Fixture::new();
let candidate = fixture.home().join("nightly/profiles/wordcraft");
fixture.env.insert("XDG_CACHE_HOME".into(), "relative/cache".into());
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("absolute"));
fixture.env.remove("XDG_CACHE_HOME");
fixture.env.insert("WORDCRAFT_PROFILE_DIR".into(), fixture.home().join("custom-stable").into_os_string());
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("WORDCRAFT_PROFILE_DIR"));
fixture.env.remove("WORDCRAFT_PROFILE_DIR");
fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.wordcraft".into());
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak"));
fixture.env.remove("FLATPAK_ID");
// The nightly Flatpak is the one sandbox this build ships in, so its own id is accepted.
let flatpak_profile = fixture.home().join("nightly/flatpak-profile");
fixture.env.insert("FLATPAK_ID".into(), NIGHTLY_FLATPAK_ID.into());
assert_eq!(fixture.check(Platform::Linux, &flatpak_profile).unwrap(), flatpak_profile);
fixture.env.remove("FLATPAK_ID");
fixture.env.remove("HOME");
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("HOME"));
assert!(!candidate.exists());
}
#[test]
fn non_directory_and_failed_write_probe_never_fall_back_to_stable() {
let fixture = Fixture::new();
let file = fixture.home().join("not-a-directory");
std::fs::write(&file, b"do not replace me").unwrap();
assert!(fixture.check(Platform::Linux, &file).is_err());
assert_eq!(std::fs::read(file).unwrap(), b"do not replace me");
let candidate = fixture.home().join("nightly");
let calls = std::cell::Cell::new(0);
let result = validate_for(
Platform::Linux,
&candidate,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
calls.set(calls.get() + 1);
Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "injected write refusal"))
},
);
assert!(result.unwrap_err().contains("not writable"));
assert_eq!(calls.get(), 1);
assert!(!fixture.home().join(".config/wordcraft").exists());
}
#[cfg(unix)]
#[test]
fn symlink_and_dangling_aliases_cannot_create_or_modify_stable_data() {
use std::os::unix::fs::symlink;
let fixture = Fixture::new();
let stable = fixture.home().join(".config/wordcraft");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("sentinel"), b"untouched").unwrap();
let alias = fixture.home().join("alias");
symlink(&stable, &alias).unwrap();
assert!(fixture.check(Platform::Linux, &alias.join("nightly")).unwrap_err().contains("overlap"));
let missing = fixture.home().join("missing-target");
let dangling = fixture.home().join("dangling");
symlink(&missing, &dangling).unwrap();
assert!(fixture.check(Platform::Linux, &dangling.join("nightly")).is_err());
assert!(!missing.exists());
assert!(!stable.join("nightly").exists());
assert_eq!(std::fs::read(stable.join("sentinel")).unwrap(), b"untouched");
}
}
+39
View File
@@ -0,0 +1,39 @@
# WordCraft app icon
A **page and pen**: a sheet of paper with a folded corner and ruled lines, with a fountain pen
lying across its lower right, on the app's blue field. It is drawn in the canvas palette the app's
own artwork uses (`#3b5bdb` field, `#efe9dc` paper, `#0b0b0c` ink).
`wordcraft.svg` is the canonical master: a full-bleed 512-unit tile with a rounded square
(`rx=112`) and no border. Windows and Linux use the tile as it is; the macOS renders sit on
Apple's grid, an 824/1024 body with a transparent margin.
## Files
- `wordcraft.svg`: canonical master (also the hicolor scalable icon).
- `wordcraft-1024.png`: 1024 px full-bleed render.
- `wordcraft-macos-512.png`: the padded macOS render (Dock, window icon; embedded by the app).
- `wordcraft.icns`: macOS bundle icon (`CFBundleIconFile`), padded frames.
- `wordcraft.ico`: Windows icon, 16–256 px, embedded in `wordcraft.exe` by
`apps/wordcraft/build.rs`.
- `hicolor/<size>/apps/ai.storyteller.wordcraft.png` (16–512) and `hicolor/scalable/...svg`:
Linux icon theme.
## Regenerate
Replace `wordcraft.svg`, then run `packaging/icons.sh`. It needs `resvg`, plus `iconutil` on macOS;
`cargo run -p xtask -- ico` packs the Windows icon.
## Nightly channel
The Nightly icons keep the drawing, its alpha and the macOS padding exactly as the stable renders
have them. Only the background contribution changes: from the app blue to the deeper Nightly
background `#232c67`. There is no letter badge, crescent or other mark; the app and the Launcher
name the channel in text.
`packaging/nightly-icons.py` derives the four files from the committed stable renders (the `.ico`
frames, the `.icns` slots, the 256 px hicolor render and the padded 512 px macOS master) and
records their hashes in [`nightly-provenance.json`](nightly-provenance.json). `--check` re-derives
them and compares. The three smallest macOS slots (16, 32 and 64 px) are box-filtered from the
padded master; every other frame is the same size as the stable frame it comes from, so nothing is
upscaled. The stable files are not modified.
+72
View File
@@ -0,0 +1,72 @@
{
"title": "WordCraft nightly deep-background icons",
"author": "@skylartaylor",
"license": "MIT OR Apache-2.0",
"source_commit": null,
"inputs": [
{
"path": "assets/app-icon/hicolor/256x256/apps/ai.storyteller.wordcraft.png",
"sha256": "7c1791408282d01e8c5d0cb1f4080971eaa412c60518694a1cec1e60b23c7406",
"purpose": "Windows/Linux native256 master"
},
{
"path": "assets/app-icon/wordcraft.ico",
"sha256": "53a23dcf66260f44d87d4d143d633395f3e967f391eda47e6e9cc3a52f820225",
"purpose": "nine full-bleed frames, 16-256 px"
},
{
"path": "assets/app-icon/wordcraft.icns",
"sha256": "02ac9dcb7ee06858416c7ef70ca2b359cad38dbef4a0b526bb1f28953d90170f",
"purpose": "padded macOS frames, 32-1024 px"
},
{
"path": "assets/app-icon/wordcraft-macos-512.png",
"sha256": "5a8a4476c1fb67123f803a8ab7a7a0dbd9912675ae54d695c17e74454913ceae",
"purpose": "padded macOS master (box-filtered down to the 16/32/64 px slots, never upscaled)"
}
],
"method": {
"kind": "derived from the project-owned stable renders by a committed, reproducible script",
"original_palette": {
"ink": "#0b0b0c",
"paper": "#efe9dc",
"background": "#3b5bdb"
},
"nightly_background": "#232c67",
"transform": "Decompose every pixel in the stable three-colour palette (ink, paper, background) and rebuild it with the Nightly background, keeping the ink and paper weights, alpha and padding. Clamped and renormalised where an antialiased pixel falls outside the triangle. No crescent, letter or badge.",
"generator": "packaging/nightly-icons.py",
"generator_sha256": "7a31bc6d3a00d991cf4fd6b1f2ce06b3bdc9201525d207ba84a935a877ee8e4a",
"reproduce": "python3 packaging/nightly-icons.py --check"
},
"outputs": {
"assets/app-icon/wordcraft-nightly.png": "43a002255f6db703599de99224cd47274905b8742d92f91d0f7c41c8cb5656e2",
"assets/app-icon/wordcraft-nightly.ico": "f4bb314bb6c8c131c7250e441407be5e22e645579881f0a80fe7bd963adda54a",
"assets/app-icon/wordcraft-nightly-1024.png": "36e21d31b852ac222c787ee27af45667882353eb9b1c3bfb62a9038c17843b25",
"assets/app-icon/wordcraft-nightly.icns": "0b359aa7f07fda079298a97215da207486ca092bbe9c6b277a5de3d3fbc4f9ef"
},
"ico_frame_sizes": [
16,
20,
24,
32,
40,
48,
64,
128,
256
],
"icns_png_slots": {
"icp4": 16,
"icp5": 32,
"icp6": 64,
"ic07": 128,
"ic08": 256,
"ic13": 256,
"ic09": 512,
"ic14": 512,
"ic10": 1024,
"ic11": 32,
"ic12": 64
},
"validation": "Every output is re-derived from the committed inputs by the committed script (--check) and compared by SHA-256; the frames' pixel dimensions and the containers' members are checked while deriving; the foreground and padding were compared visually against the stable renders. Native Explorer/Finder qualification is unrun."
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

+33 -1
View File
@@ -4,14 +4,34 @@
use std::path::{Path, PathBuf};
/// The folder the desktop app chose before any of its state was read: a Launcher-selected
/// Nightly profile (`launch_profile`). Set once, at startup, before the first [`settings_dir`]
/// call; tests and the CLI leave it unset.
static CHOSEN: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();
/// Point [`settings_dir`] at `dir` for this process. Fails when a folder was already chosen.
pub fn use_settings_dir(dir: PathBuf) -> Result<(), String> {
CHOSEN.set(dir).map_err(|_| "the settings folder was already selected".into())
}
/// The app's settings folder (preferences, logs, token files): macOS
/// `~/Library/Application Support/WordCraft`, Windows `%APPDATA%\WordCraft`, otherwise
/// `$XDG_CONFIG_HOME/wordcraft` or `~/.config/wordcraft`.
/// `WORDCRAFT_PROFILE_DIR` overrides the entire folder for isolated runs.
/// A folder chosen by the app through [`use_settings_dir`] wins: it is a launch decision, not
/// an environment variable a child or a wrapper might have inherited. `WORDCRAFT_PROFILE_DIR`
/// overrides the entire folder for isolated runs otherwise.
pub fn settings_dir() -> Option<PathBuf> {
if let Some(path) = CHOSEN.get() {
return Some(path.clone());
}
if let Some(path) = std::env::var_os("WORDCRAFT_PROFILE_DIR").filter(|p| !p.is_empty()) {
return Some(PathBuf::from(path));
}
platform_settings_dir()
}
/// The platform's own folder, when nothing chose one (see [`settings_dir`]).
fn platform_settings_dir() -> Option<PathBuf> {
if cfg!(target_os = "macos") {
std::env::var_os("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/WordCraft"))
} else if cfg!(windows) {
@@ -67,6 +87,18 @@ mod tests {
assert_eq!(parse_instance_id("app=ai.storyteller.wordcraft\n"), None);
}
#[test]
fn a_chosen_folder_wins_over_the_environment() {
// The chosen folder is process-wide and set once, so this test only reads the rule when
// nothing chose one (the crate's own tests and the CLI never do).
if CHOSEN.get().is_none() {
assert_eq!(settings_dir(), super::platform_settings_dir());
assert!(use_settings_dir(PathBuf::from("/chosen/profile")).is_ok());
assert_eq!(settings_dir().as_deref(), Some(std::path::Path::new("/chosen/profile")));
assert!(use_settings_dir(PathBuf::from("/other")).is_err(), "the folder is selected once");
}
}
#[test]
fn key_file_per_instance() {
let dir = Path::new("/settings/wordcraft");
+1 -1
View File
@@ -64,7 +64,7 @@ fn save(doc: &wordcraft_doc::Document) -> BTreeMap<String, Vec<u8>> {
}
const SETTINGS: &str = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml" mc:Ignorable="w14 w15"><w:zoom w:percent="120"/><w:removePersonalInformation/><w:removeDateAndTime/><w:proofState w:spelling="clean" w:grammar="clean"/><w:mailMerge><w:mainDocumentType w:val="formLetters"/><w:dataSource r:id="rId9"/></w:mailMerge><w:trackRevisions/><w:defaultTabStop w:val="708"/><w:hyphenationZone w:val="425"/><w:characterSpacingControl w:val="doNotCompress"/><w:compat><w:compatSetting w:name="compatibilityMode" w:uri="http://schemas.microsoft.com/office/word" w:val="15"/><w:compatSetting w:name="overrideTableStyleFontSizeAndJustification" w:uri="http://schemas.microsoft.com/office/word" w:val="1"/><w:compatSetting w:name="enableOpenTypeFeatures" w:uri="http://schemas.microsoft.com/office/word" w:val="1"/></w:compat><w:docVars><w:docVar w:name="ClauseSet" w:val="B"/></w:docVars><w:rsids><w:rsidRoot w:val="00A1B2C3"/><w:rsid w:val="00A1B2C3"/></w:rsids><m:mathPr><m:mathFont m:val="Cambria Math"/><m:smallFrac m:val="0"/></m:mathPr><w:themeFontLang w:val="pl-PL"/><w:decimalSymbol w:val=","/><w:listSeparator w:val=";"/><w14:docId w14:val="1A2B3C4D"/></w:settings>"#;
<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml" mc:Ignorable="w14 w15"><w:zoom w:percent="120"/><w:removePersonalInformation/><w:removeDateAndTime/><w:proofState w:spelling="clean" w:grammar="clean"/><w:trackRevisions/><w:defaultTabStop w:val="708"/><w:hyphenationZone w:val="425"/><w:characterSpacingControl w:val="doNotCompress"/><w:compat><w:compatSetting w:name="compatibilityMode" w:uri="http://schemas.microsoft.com/office/word" w:val="15"/><w:compatSetting w:name="overrideTableStyleFontSizeAndJustification" w:uri="http://schemas.microsoft.com/office/word" w:val="1"/><w:compatSetting w:name="enableOpenTypeFeatures" w:uri="http://schemas.microsoft.com/office/word" w:val="1"/></w:compat><w:docVars><w:docVar w:name="ClauseSet" w:val="B"/></w:docVars><w:rsids><w:rsidRoot w:val="00A1B2C3"/><w:rsid w:val="00A1B2C3"/></w:rsids><m:mathPr><m:mathFont m:val="Cambria Math"/><m:smallFrac m:val="0"/></m:mathPr><w:themeFontLang w:val="pl-PL"/><w:decimalSymbol w:val=","/><w:listSeparator w:val=";"/><w14:docId w14:val="1A2B3C4D"/></w:settings>"#;
fn pos(s: &str, needle: &str) -> usize {
s.find(needle).unwrap_or_else(|| panic!("{needle} missing from {s}"))
+54 -4
View File
@@ -66,7 +66,15 @@ const SETTINGS: &str = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?
<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml" mc:Ignorable="w14 w15"><w:zoom w:percent="120"/><w:removePersonalInformation/><w:removeDateAndTime/><w:proofState w:spelling="clean" w:grammar="clean"/><w:mailMerge><w:mainDocumentType w:val="formLetters"/><w:dataSource r:id="rId9"/></w:mailMerge><w:trackRevisions/><w:defaultTabStop w:val="708"/><w:hyphenationZone w:val="425"/><w:characterSpacingControl w:val="doNotCompress"/><w:compat><w:compatSetting w:name="compatibilityMode" w:uri="http://schemas.microsoft.com/office/word" w:val="15"/><w:compatSetting w:name="overrideTableStyleFontSizeAndJustification" w:uri="http://schemas.microsoft.com/office/word" w:val="1"/><w:compatSetting w:name="enableOpenTypeFeatures" w:uri="http://schemas.microsoft.com/office/word" w:val="1"/></w:compat><w:docVars><w:docVar w:name="ClauseSet" w:val="B"/></w:docVars><w:rsids><w:rsidRoot w:val="00A1B2C3"/><w:rsid w:val="00A1B2C3"/></w:rsids><m:mathPr><m:mathFont m:val="Cambria Math"/><m:smallFrac m:val="0"/></m:mathPr><w:themeFontLang w:val="pl-PL"/><w:decimalSymbol w:val=","/><w:listSeparator w:val=";"/><w14:docId w14:val="1A2B3C4D"/></w:settings>"#;
fn with_settings(settings: &str) -> Vec<u8> {
package("<w:p><w:r><w:t>Text</w:t></w:r></w:p>", &[("rId1", &format!("{REL}/settings"), "settings.xml")], &[], &[("word/settings.xml", settings)])
let sources = format!(
r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId9" Type="{REL}/mailMergeSource" Target="file:///__wordcraft_missing_source__/letters.xlsx" TargetMode="External"/></Relationships>"#
);
package(
"<w:p><w:r><w:t>Text</w:t></w:r></w:p>",
&[("rId1", &format!("{REL}/settings"), "settings.xml")],
&[],
&[("word/settings.xml", settings), ("word/_rels/settings.xml.rels", &sources)],
)
}
fn pos(s: &str, needle: &str) -> usize {
@@ -97,11 +105,22 @@ fn unmodelled_settings_survive_a_save_and_owned_ones_follow_the_model() {
] {
assert!(s.contains(kept), "{kept} lost: {s}");
}
// Owned: Track Changes was turned off; one compatibility mode; the mail merge source (a
// relationship that isn't carried) is dropped rather than left dangling.
// Owned: Track Changes was turned off; one compatibility mode. Mail merge keeps its external
// source relationship.
assert!(!s.contains("trackRevisions"), "{s}");
assert_eq!(s.matches("compatibilityMode").count(), 1, "{s}");
assert!(!s.contains("mailMerge") && !s.contains("rId9"), "{s}");
assert!(s.contains("mailMerge"), "{s}");
let rel_id = s
.split("<w:dataSource")
.nth(1)
.and_then(|after| after.split("r:id=\"").nth(1))
.and_then(|after| after.split('"').next())
.expect("dataSource r:id");
let rels = text(&files, "word/_rels/settings.xml.rels");
let expected_rel = format!(
r#"<Relationship Id="{rel_id}" Type="{REL}/mailMergeSource" Target="file:///__wordcraft_missing_source__/letters.xlsx" TargetMode="External"/>"#
);
assert!(rels.contains(&expected_rel), "missing matching relationship for {rel_id}: {rels}");
// The privacy options are the model's (#1062): written once each, and gone when turned off.
assert_eq!(s.matches("removePersonalInformation").count(), 1, "{s}");
assert_eq!(s.matches("removeDateAndTime").count(), 1, "{s}");
@@ -123,6 +142,37 @@ fn unmodelled_settings_survive_a_save_and_owned_ones_follow_the_model() {
assert_eq!(text(&save(&again), "word/settings.xml"), s);
}
#[test]
fn changed_zoom_survives_merged_settings_and_reads_back_as_page_width() {
let old_zoom = r#"<w:zoom w:percent="120"/>"#;
let updated_zoom = r#"<w:zoom w:val="bestFit" w:percent="145"/>"#;
for original in [SETTINGS.to_string(), SETTINGS.replace(old_zoom, "")] {
let mut doc = wordcraft_docx::read(&with_settings(&original)).unwrap();
assert!(doc.passthrough.contains_key("wordcraft:settings.orig"));
doc.settings.zoom = Some(wordcraft_doc::Zoom { percent: 145, fit: Some(wordcraft_doc::ZoomFit::PageWidth) });
let bytes = wordcraft_docx::write(&doc).unwrap();
let settings = text(&unzip(&bytes), "word/settings.xml");
assert_eq!(settings.matches("<w:zoom ").count(), 1, "{settings}");
assert!(settings.contains(updated_zoom), "{settings}");
// The retained root and unrelated child bytes still belong to the original file.
let root_end = original.find("><w:").unwrap() + 1;
assert!(settings.starts_with(&original[..root_end]), "{settings}");
for kept in [
r#"<w:proofState w:spelling="clean" w:grammar="clean"/>"#,
r#"<w:docVars><w:docVar w:name="ClauseSet" w:val="B"/></w:docVars>"#,
r#"<w:rsids><w:rsidRoot w:val="00A1B2C3"/><w:rsid w:val="00A1B2C3"/></w:rsids>"#,
] {
assert!(settings.contains(kept), "{kept} lost: {settings}");
}
assert!(pos(&settings, "<w:zoom ") < pos(&settings, "<w:proofState"));
let again = wordcraft_docx::read(&bytes).unwrap();
let zoom = again.settings.zoom.unwrap();
assert_eq!(zoom.percent, 145);
assert!(matches!(zoom.fit, Some(wordcraft_doc::ZoomFit::PageWidth)));
assert_eq!(text(&save(&again), "word/settings.xml"), settings);
}
}
#[test]
fn settings_written_by_wordcraft_keep_no_original() {
let doc = wordcraft_doc::Document::new();
+28
View File
@@ -927,4 +927,32 @@ mod shortcut_tests {
}
}
}
#[test]
fn copy_format_web_alias_respects_user_removal_and_reassignment() {
use craft_keymap::{Binding, Chord, CommandRef, Overrides, Policy};
let mut commands = super::super::registry().all().to_vec();
commands.iter_mut().find(|c| c.id == "edit.copyFormat").unwrap().shortcut = copy_format_shortcut(true);
let registry = Registry::new(commands);
let mut keymap = crate::keymap::registry_keymap(&registry, &Overrides::default());
let copy_cmd = CommandRef::new("edit.copyFormat");
let bold_cmd = CommandRef::new("format.bold");
let chord = Chord::parse("Mod+Alt+Shift+C").unwrap();
let binding = Binding::parse("Mod+Alt+Shift+C").unwrap();
assert!(keymap.bindings(&copy_cmd).iter().any(|b| b.trigger.chord == chord));
assert!(keymap.remove(&copy_cmd, &binding));
assert_eq!(keymap.holder(&chord), None);
keymap.assign(&bold_cmd, binding, Policy::Steal).unwrap();
assert_eq!(keymap.holder(&chord).as_ref().map(|c| c.id.as_str()), Some("format.bold"));
assert_eq!(keymap.holder(&Chord::parse("Mod+Shift+C").unwrap()).as_ref().map(|c| c.id.as_str()), Some("edit.copyFormat"));
let overrides = keymap.overrides().clone();
let restored = crate::keymap::registry_keymap(&registry, &overrides);
assert_eq!(restored.holder(&chord).as_ref().map(|c| c.id.as_str()), Some("format.bold"));
assert_eq!(restored.holder(&Chord::parse("Mod+Shift+C").unwrap()).as_ref().map(|c| c.id.as_str()), Some("edit.copyFormat"));
}
}
+22
View File
@@ -398,6 +398,28 @@ mod tests {
assert!(!page_text(&mut s).contains("{ AUTHOR }"));
}
/// #980: F11 is full screen, as people expect of a desktop app; the field walk keeps Word's
/// other keys, Alt+F1 and Alt+Shift+F1 (and Shift+F11).
#[test]
fn f11_is_full_screen_and_alt_f1_walks_fields() {
let s = Session::new(wordcraft_doc::Document::new());
let keymap = crate::keymap::registry_keymap(&s.registry, s.keymap());
let chord = |c: &str| craft_keymap::Chord::parse(c).unwrap();
let key = |k: &str| keymap.holder(&chord(k)).map(|c| c.id);
assert_eq!(key("F11").as_deref(), Some("view.fullScreen"));
assert_eq!(key("Alt+F1").as_deref(), Some("fields.next"));
assert_eq!(key("Alt+Shift+F1").as_deref(), Some("fields.previous"));
assert_eq!(key("Shift+F11").as_deref(), Some("fields.previous"));
assert_eq!(key("Mod+F11").as_deref(), Some("fields.lock"));
let shortcut = s.registry.get("view.fullScreen").map(|c| c.shortcut);
if cfg!(target_os = "macos") {
assert_eq!(shortcut, Some("Mod+Ctrl+F / F11"));
assert_eq!(key("Mod+Ctrl+F").as_deref(), Some("view.fullScreen"));
} else {
assert_eq!(shortcut, Some("F11"));
}
}
/// Editing a code changes the instruction and the result; lock keeps a result through updates;
/// unlink turns the field into its text in one undo step; Alt+F1/Shift+F11 walk the fields.
#[test]
+2 -1
View File
@@ -16,7 +16,8 @@ mod objects;
pub(crate) use header_footer::saved_copy;
use header_footer::{create_hf, edit_hf, header_footer, new_empty_headers, strip_headers};
pub use items::{
DropCapState, default_date_picture, drop_cap_state, format_date, format_date_at, format_date_in, format_date_parts, format_date_parts_in,
DropCapState, default_date_picture, drop_cap_state, format_date, format_date_at, format_date_at_in, format_date_in, format_date_parts,
format_date_parts_in,
};
use items::{cover_page, date_time, drop_cap, drop_cap_off, field, page_number, symbol};
use links::{bookmark, delete_bookmark, link, link_targets};
+189 -8
View File
@@ -1,7 +1,8 @@
use super::ctx::{Ctx, page_anchored};
use super::ctx::{Ctx, Joining, page_anchored};
use super::floats::{
ObjFrame, ObjectPlacement, WrapArea, align_in, float_rect, floating, left_out_objects, place_objects, rel_exclusions, wrap_area,
};
use super::flow::again;
use super::page::PageFrame;
use super::placed::Placed;
use super::table_flow::below;
@@ -262,12 +263,19 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
let frames = !matches!(story, StoryRef::Part(id) if ctx.doc.parts.get(&id).is_some_and(|p| p.kind == wordcraft_doc::PartKind::TextBox));
// The bottom of the last paragraph's lines.
let mut prev_end = 0.0f32;
// Where the last paragraph, whose mark is hidden, ended: the next one goes on from there.
let mut joint: Option<Joint> = None;
let outer_joined = ctx.joined;
for (i, b) in blocks.iter().enumerate() {
last_top = y;
let mut path = prefix.to_vec();
path.push(i as u32);
match &**b {
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 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());
@@ -306,8 +314,10 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
});
// Paragraph-relative floats start above the effective space before, as in the
// body path. Keep text and wrap exclusions relative to the text's actual top.
let para_top = y;
// 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) };
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.
let mut floats = HashMap::new();
@@ -354,10 +364,11 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
if !rel.is_empty() {
pl = ctx.para_labelled(p, width, table, &rel, label);
}
TakenUp::clear(taken.as_ref(), &mut excl);
// Bordered paragraphs: room for their borders, those of a group joined in one box.
let cell = table.map(|t| &t.para);
let (above, below) = (joined(ctx.doc, blocks, i, i.checked_sub(1), cell), joined(ctx.doc, blocks, i, Some(i + 1), cell));
let mut edges = Edges::own(&pl, 0, pl.lines.len());
let mut edges = Edges::own(&pl, 0, pl.lines.len()).sharing(&pl);
if above {
edges.top = 0.0;
}
@@ -370,6 +381,7 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
edges.up = (y + lead - prev_end).max(0.0);
}
prev_end = push_para(&mut items, (story, &path), &pl, (0, pl.lines.len()), (0.0, y + lead), width, edges);
joint = Joint::after(&pl, (0, pl.lines.len()), i, (0.0, y + lead), edges.bottom).filter(|_| mark_hidden && !shows_nothing).or(joint);
// Pictures, shapes and text boxes: drawn, their areas and text boxes' text.
if !p.objects.is_empty() {
let at = ObjFrame {
@@ -412,7 +424,9 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
let last = i + 1 == blocks.len();
let normal = || pl.rp.style == "Normal" || ctx.doc.styles.get(&pl.rp.style).is_none();
let after = if last && (pl.rp.after_auto || (in_cell && ctxl && normal())) { 0.0 } else { pl.rp.space_after };
y += edges.top + pl.height + edges.bottom + after;
y += edges.top + pl.height + edges.bottom;
// One going on from the line of the paragraph before ends below that line (#3986).
y = TakenUp::end(taken.as_ref(), ctx, (y, after), outer_joined);
prev_after = after;
prev_after_auto = pl.rp.after_auto;
prev_listed = listed;
@@ -445,6 +459,7 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
y = y.max(legacy_header_reach(y, &legacy_reach));
let floats_bottom = float_tables.iter().map(|r| r.bottom()).fold(float_objects_bottom, f32::max);
ctx.hide_deleted = outer_hide;
ctx.joined = outer_joined;
BoxLayout { items, height: y.max(0.0), floats_bottom, last_top: last_top.max(0.0), table_areas, page_table_wraps }
}
@@ -700,6 +715,162 @@ impl Edges {
joined: [false; 2],
}
}
/// A paragraph going on from the line of the one before, whose mark is hidden (#3986), takes
/// no room for its borders on that line, nor below it when that line is all it has: the
/// shared line shows the first paragraph's shading and borders (Word).
pub(crate) fn sharing(mut self, pl: &ParaLayout) -> Edges {
if pl.shares_line() {
self.top = 0.0;
if pl.lines.len() <= 1 {
self.bottom = 0.0;
}
}
self
}
}
/// Where a paragraph whose mark is hidden ends (#3986). Word shows it on one line with the next
/// paragraph: that one's text goes on from where this one's ends, beside it on its last line.
/// Paragraphs that show nothing (an empty one with a hidden mark, say) pass the place on.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Joint {
/// The block that goes on from here.
pub(crate) next: usize,
/// The page (the count of pages) and column of the last line (body text only).
pub(crate) page: usize,
pub(crate) col: usize,
/// The last line's top, height and baseline (from its top), the left edge of its column and
/// the x its text ends at.
pub(crate) top: f32,
pub(crate) height: f32,
baseline: f32,
left: f32,
end: f32,
/// The room under the line for the paragraph's bottom border: what follows the shared line
/// starts below it.
room: f32,
}
impl Joint {
/// After lines `l0..l1` of paragraph layout `pl`, block `block`, the first of them at `y` in
/// a column whose left edge is at `x`, with `room` under them for its bottom border.
pub(crate) fn after(pl: &ParaLayout, (l0, l1): (usize, usize), block: usize, (x, y): (f32, f32), room: f32) -> Option<Joint> {
let li = l1.checked_sub(1)?;
let (first, last) = (pl.lines.get(l0)?, pl.lines.get(li)?);
// Right-to-left text runs the other way: its lines aren't joined.
if pl.rp.bidi || !last.vis.is_empty() {
return None;
}
let end = pl.x_of(li, pl.text_len)?;
let (top, height, baseline) = (y + last.top - first.top, last.height, last.baseline - last.top);
Some(Joint { next: block + 1, page: 0, col: 0, top, height, baseline, left: x, end: x + end, room })
}
/// Paragraph `p`, block `i`, arriving at `joint`: whether its mark is hidden, whether it shows
/// nothing, and how it goes on from the place the one before left (if that one's mark was hidden).
fn arrive(
ctx: &mut Ctx,
joint: &mut Option<Joint>,
(i, p): (usize, &Paragraph),
(width, frames): (f32, bool),
table: Option<&para::CellText>,
) -> (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));
(mark_hidden, shows_nothing, taken)
}
/// The bottom of the shared line, with the room for the first paragraph's bottom border.
pub(crate) fn bottom(&self) -> f32 {
self.top + self.height + self.room
}
/// How the next paragraph `q`, laid out `width` wide, goes on from here: how far below the
/// shared line's top it starts (its first line's text sits on this paragraph's baseline, not
/// above it), and the areas it keeps clear of: its first line, this paragraph's text, down to
/// the bottom of that line only; its later lines, the rest of the shared line (a heading's,
/// 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 (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)];
// Just below the first row as the line breaker tests it: the breaker tests every row at
// its estimate (`row_est`), not at the line's height, so the first row never meets this
// area and every later row, starting lower, does and moves below it. The probe's own first
// line can be taller than the real one (a large word that wraps off the narrower shared
// line), so its height can't be used here.
let below = self.top + gap + probe.row_est + 0.01;
if self.bottom() > below {
areas.push((Rect::new(self.left, below, width.max(0.01), self.bottom() - below), true, None, WrapText::BothSides, false));
}
(gap, areas)
}
/// The areas [`Joint::fit`] gave taken out of `excl` again, the paragraph laid out.
pub(crate) fn unfit(areas: &[WrapArea], excl: &mut Vec<WrapArea>) {
for area in areas {
if let Some(k) = excl.iter().position(|a| a.0 == area.0 && a.1 == area.1 && a.2.is_none() && a.3 == area.3) {
excl.remove(k);
}
}
}
/// 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> {
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()) {
return None;
}
let mut para = p.clone();
para.props.space_before = Some(0.0);
para.props.space_before_auto = Some(false);
ctx.joined = Some(Joining::new(para.rev, 0.0));
let (gap, areas) = self.fit(ctx, &para, width, table);
Some(TakenUp { joint: self, para, gap, areas })
}
}
/// A paragraph of a box going on from a [`Joint`]: the paragraph without its space before, how
/// far below the shared line's top it starts and the areas its lines keep clear of.
struct TakenUp {
joint: Joint,
para: Paragraph,
gap: f32,
areas: Vec<WrapArea>,
}
impl TakenUp {
/// Where it starts: `y` below the shared line's top, its lines keeping clear of that line.
fn start(taken: Option<&TakenUp>, y: &mut f32, excl: &mut Vec<WrapArea>) {
let Some(t) = taken else { return };
*y = t.joint.top + t.gap;
excl.extend(t.areas.iter().cloned());
}
/// Its lines laid out: the areas they kept clear of come out of `excl`.
fn clear(taken: Option<&TakenUp>, excl: &mut Vec<WrapArea>) {
if let Some(t) = taken {
Joint::unfit(&t.areas, excl);
}
}
/// Where what follows a paragraph ending at `y`, with `after` its space after, starts: below
/// the shared line at least, with the first paragraph's bottom border. With the copy laid
/// out, the paragraph's own layouts are its own again (`outer`).
fn end(taken: Option<&TakenUp>, ctx: &mut Ctx, (y, after): (f32, f32), outer: Option<Joining>) -> f32 {
let Some(t) = taken else { return y + after };
ctx.joined = outer;
y.max(t.joint.bottom()) + after
}
}
/// Paragraph lines plus their shading and borders; returns the bottom of the lines. The
@@ -717,12 +888,21 @@ pub(crate) fn push_para(
return y;
};
let h = last.top + last.height - first.top;
let lines = Placed::Lines { story, path: Path(path.to_vec()), para: pl.clone(), l0, l1, x, y, turn: TextDirection::Horizontal };
// The line a paragraph shares with the one before, whose mark is hidden, shows that one's
// shading and borders: this one's start on its own next line, without a top border (Word, #3986).
let shared = l0 == 0 && pl.shares_line();
let Some(own) = pl.lines.get(if shared { 1 } else { l0 }).filter(|_| !shared || l1 > 1) else {
items.push(lines);
return y + h;
};
let (y_own, e) = if shared { (y + own.top - first.top, Edges { top: 0.0, up: 0.0, ..e }) } else { (y, e) };
// Indents are logical: a right-to-left paragraph's start indent (and hanging indent) is on the right.
let start = pl.rp.indent_left.min(pl.rp.indent_left + pl.rp.indent_first);
let (li, ri) = if pl.rp.bidi { (pl.rp.indent_right, start) } else { (start, pl.rp.indent_right) };
let left = x + li;
let right = x + width - ri;
let (top, bottom) = (y - e.top - e.up, y + h + e.bottom);
let (top, bottom) = (y_own - e.top - e.up, y + h + e.bottom);
// The outer edges of the side borders.
let sides = pl.rp.borders.unwrap_or_default();
let (lx, rx) = (left - border_room(sides.left), right + border_room(sides.right));
@@ -731,7 +911,7 @@ pub(crate) fn push_para(
let (sl, sr) = (lx.min(left - pad), rx.max(right + pad));
items.push(Placed::Fill { rect: Rect::new(sl, top, sr - sl, bottom - top), color: c });
}
items.push(Placed::Lines { story, path: Path(path.to_vec()), para: pl.clone(), l0, l1, x, y, turn: TextDirection::Horizontal });
items.push(lines);
if let Some(b) = &pl.rp.borders {
// All four lines lie beyond their distance from the text (`lx`, `rx`: the side lines'
// outer edges); `box_rules` runs the top and bottom over the side lines to those edges.
@@ -739,9 +919,10 @@ pub(crate) fn push_para(
let (cl, cr) = (lx + half(b.left), rx - half(b.right));
let tb = b.top.filter(|t| e.top > 0.0 && t.is_visible());
let bb = b.bottom.filter(|t| e.bottom > 0.0 && t.is_visible());
let ty = tb.map_or(top, |t| y - t.space - t.width / 2.0);
let ty = tb.map_or(top, |t| y_own - t.space - t.width / 2.0);
let by = bb.map_or(bottom, |t| y + h + t.space + t.width / 2.0);
box_rules(items, (cl, ty, cr, by), [tb, bb, b.left, b.right], e.joined);
// Open at the top where it goes on over the shared line.
box_rules(items, (cl, ty, cr, by), [tb, bb, b.left, b.right], [e.joined[0] || shared, e.joined[1]]);
}
y + h
}
+3
View File
@@ -27,6 +27,9 @@ pub(crate) struct Key {
pub(crate) sref: u64,
/// The word being typed in this paragraph, left without a spelling squiggle.
pub(crate) typing: Option<(usize, usize)>,
/// A copy of the paragraph going on from the line of the one before (`ctx::Joining`): its
/// space before and whether it shares that line ([`ParaEnv::joined`](crate::para::ParaEnv)).
pub(crate) joined: Option<(u32, bool)>,
}
/// Memoised paragraph layouts.
+82 -4
View File
@@ -51,6 +51,9 @@ pub(crate) struct Ctx<'a> {
/// Empty body paragraphs with hidden marks or continuous section breaks, in order:
/// they take no room (see [`place_para`]).
pub(crate) quiet_marks: Vec<usize>,
/// The paragraph being laid out as going on from the line of the one before, whose mark is
/// hidden: its list number is counted but not drawn (#3986).
pub(crate) joined: Option<Joining>,
/// Empty paragraphs closing a continuous section right after another section's mark, in
/// order: each takes its line while it fits, then stays at the page's bottom (#3907).
pub(crate) stacked_marks: Vec<usize>,
@@ -79,6 +82,31 @@ pub(crate) struct Ctx<'a> {
pub(crate) header_repeats: usize,
}
/// A paragraph going on from the line of the one before, whose mark is hidden (#3986): a copy of
/// the document's, which keeps its revision, given the space before that puts its text on that
/// line's baseline.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Joining {
/// The paragraph's revision.
pub(crate) rev: u64,
/// The space before the copy is given.
before: f32,
/// Whether it still shares that line: not once its first line has moved on to the next
/// column or page, where it is laid out as on its own (the copy's space before kept).
pub(crate) shares: bool,
}
impl Joining {
pub(crate) fn new(rev: u64, before: f32) -> Self {
Joining { rev, before, shares: true }
}
/// What tells the copy's layouts apart from each other and from the paragraph's own.
fn key(self) -> (u32, bool) {
(self.before.to_bits(), self.shares)
}
}
struct ParaEnvInput<'a> {
width: f32,
label: Option<(String, Level)>,
@@ -87,6 +115,7 @@ struct ParaEnvInput<'a> {
eq_number: u32,
typing_word: Option<(usize, usize)>,
fitted: &'a [(usize, f32)],
joined: bool,
}
/// A header or footer (`story`) laid out for page `number` of a section (`sect`, `mirror`): its
@@ -227,12 +256,31 @@ impl Ctx<'_> {
grid: para::Grid::default(),
fit_objects: false,
fitted: &[],
joined: false,
};
let pl = Arc::new(para::layout_para(&p, &env));
self.numbers.insert(n, pl.clone());
pl
}
/// Whether `p` is laid out going on from the line of the paragraph before, sharing it (#3986).
fn shares_line(&self, p: &Paragraph) -> bool {
self.joined.is_some_and(|j| j.rev == p.rev && j.shares)
}
/// Whether `p`'s paragraph mark is hidden, with hidden text not shown: Word then shows the
/// paragraph on one line with the next one (#3986). A section's closing mark never joins.
pub(crate) fn mark_hidden(&self, p: &Paragraph, table_chr: Option<&CharProps>) -> bool {
!self.opts.show_hidden && p.section.is_none() && self.doc.styles.resolve_char_in(p.props.style.as_deref(), table_chr, &p.mark).hidden
}
/// Whether `p` shows none of its text (it has none, or all of it is hidden and not shown).
pub(crate) fn text_hidden(&self, p: &Paragraph, table_chr: Option<&CharProps>) -> bool {
p.text.is_empty()
|| (!self.opts.show_hidden
&& p.runs.iter().all(|r| r.len == 0 || self.doc.styles.resolve_char_in(p.props.style.as_deref(), table_chr, &r.props).hidden))
}
/// The list label of `p`, advancing the list counters: call it once per paragraph, in
/// document order (only for paragraphs that will show).
/// Whether `p` gets a list label ([`Ctx::next_label`] is `Some`), without counting it.
@@ -269,7 +317,16 @@ impl Ctx<'_> {
let typing = key.typing;
let pl = Arc::new(para::layout_para(
p,
&self.para_env(ParaEnvInput { width, label, table, exclusions, eq_number, typing_word: typing, fitted: &fitted }),
&self.para_env(ParaEnvInput {
width,
label,
table,
exclusions,
eq_number,
typing_word: typing,
fitted: &fitted,
joined: self.shares_line(p),
}),
));
self.cache.paras.insert(key, pl.clone());
pl
@@ -302,7 +359,16 @@ impl Ctx<'_> {
self.cache.misses += 1;
let pl = Arc::new(para::layout_para(
p,
&self.para_env(ParaEnvInput { width, label, table: None, exclusions: &[], eq_number, typing_word: None, fitted: &[] }),
&self.para_env(ParaEnvInput {
width,
label,
table: None,
exclusions: &[],
eq_number,
typing_word: None,
fitted: &[],
joined: self.shares_line(p),
}),
));
self.cache.paras.insert(key, pl.clone());
Some(pl)
@@ -330,7 +396,16 @@ impl Ctx<'_> {
let typing = key.typing;
let m = measure(&para::layout_para(
p,
&self.para_env(ParaEnvInput { width, label, table, exclusions: &[], eq_number, typing_word: typing, fitted: &fitted }),
&self.para_env(ParaEnvInput {
width,
label,
table,
exclusions: &[],
eq_number,
typing_word: typing,
fitted: &fitted,
joined: self.shares_line(p),
}),
));
self.cache.measures.insert(key, m);
m
@@ -415,6 +490,7 @@ impl Ctx<'_> {
hide_deleted: self.hide_deleted,
sref: if self.fields.styleref.is_some() && styleref::has_styleref(p) { self.fields.styleref_key(p) } else { 0 },
typing: self.opts.typing_word.filter(|t| t.rev == p.rev).map(|t| (t.start, t.end)),
joined: self.joined.filter(|j| j.rev == p.rev).map(Joining::key),
};
(key, eq_number)
}
@@ -435,7 +511,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 } = input;
let ParaEnvInput { width, label, table, exclusions, eq_number, typing_word, fitted, joined } = input;
para::ParaEnv {
doc: self.doc,
width,
@@ -454,6 +530,7 @@ impl Ctx<'_> {
grid: self.grid,
fit_objects: self.boxes.inside(),
fitted,
joined,
}
}
}
@@ -525,6 +602,7 @@ mod tests {
track_totals: false,
pct_base: None,
quiet_marks: Vec::new(),
joined: None,
stacked_marks: Vec::new(),
mirror: false,
table_keys: Vec::new(),
+96 -5
View File
@@ -1,6 +1,6 @@
use super::boxes::{BoxInput, BoxLayout, Edges, joined, layout_box, push_para};
use super::boxes::{BoxInput, BoxLayout, Edges, Joint, joined, layout_box, push_para};
use super::cache::has_page_number_fields;
use super::ctx::Ctx;
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,
@@ -15,9 +15,89 @@ use super::{
#[cfg(test)]
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) {
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.
if mark_hidden && ctx.text_hidden(p, None) {
place_para_alone(ctx, pb, p, block, body_top);
pb.joint = joint.map(|mut j| {
j.next = block + 1;
j
});
return;
}
let goes_on = joint.filter(|_| {
p.section.is_none()
&& ctx.quiet_marks.binary_search(&block).is_err()
&& ctx.stacked_marks.binary_search(&block).is_err()
&& !ctx.doc.styles.resolve_para(&p.props).page_break_before
&& !ctx.doc.styles.resolve_para(&p.props).bidi
});
match goes_on {
Some(j) => place_para_joined(ctx, pb, p, (block, body_top), j),
None => place_para_alone(ctx, pb, p, block, body_top),
}
if mark_hidden {
let path = Path::top(block);
pb.joint = pb.page().and_then(|page| {
page.items.iter().rev().find_map(|it| match it {
Placed::Lines { story: StoryRef::Body, path: at, para, l0, l1, x, y, turn: TextDirection::Horizontal, .. } if *at == path => {
let room = if *l1 >= para.lines.len() { Rooms::of(ctx, block, para).bottom } else { 0.0 };
Joint::after(para, (*l0, *l1), block, (*x, *y), room)
}
_ => None,
})
});
if let Some(j) = pb.joint.as_mut() {
(j.page, j.col) = (pb.pages.len(), pb.col);
}
}
}
/// `p` going on from the last line of the paragraph before (`j`): its first line starts at that
/// line's top, beside that paragraph's text, with no space before and its list number counted
/// but not drawn; its space after and line spacing are its own (Word, #3986).
fn place_para_joined(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, (block, body_top): (usize, f32), j: Joint) {
// The copy keeps the paragraph's revision, so the word being typed in it is found and its
// layouts are reused from one pass to the next: the cache tells them apart by `Joining`.
let mut q = p.clone();
q.props.space_before = Some(0.0);
q.props.space_before_auto = Some(false);
let outer = ctx.joined.replace(Joining::new(q.rev, 0.0));
let (gap, areas) = j.fit(ctx, &q, pb.col_w(), None);
if gap > 0.0 {
q.props.space_before = Some(gap);
ctx.joined = Some(Joining::new(q.rev, gap));
}
pb.y = j.top;
pb.prev = None;
pb.unmark_block();
pb.excl.extend(areas.iter().cloned());
place_para_alone(ctx, pb, &q, block, body_top);
ctx.joined = outer;
Joint::unfit(&areas, &mut pb.excl);
// The shared line is at least as tall as the first paragraph's, with its bottom border: what
// follows starts below it.
if (pb.pages.len(), pb.col) == (j.page, j.col) {
pb.y = pb.y.max(j.bottom() + ctx.doc.styles.resolve_para(&q.props).space_after);
}
}
/// A paragraph going on from the line of the one before (#3986) whose first line moves on to the
/// next column or page no longer shares that line: it is laid out as it is on its own there, its
/// list number drawn and its first-line indent and alignment its own.
fn unjoin(ctx: &mut Ctx, p: &Paragraph) {
if let Some(j) = ctx.joined.as_mut().filter(|j| j.rev == p.rev) {
j.shares = false;
}
}
/// A closing mark before a continuous section takes no room after content. An otherwise empty
/// section starting a new page retains its paragraph line.
pub(crate) fn place_para(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block: usize, body_top: f32) {
fn place_para_alone(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block: usize, body_top: f32) {
if !pb.web && ctx.quiet_marks.binary_search(&block).is_ok() {
let follows_section = block.checked_sub(1).and_then(|i| ctx.doc.body.get(i)).and_then(|b| b.as_para()).is_some_and(|p| p.section.is_some());
let section = pb.sect_idx;
@@ -127,7 +207,7 @@ impl Rooms {
fn of(ctx: &Ctx, block: usize, pl: &ParaLayout) -> Self {
let above = joined(ctx.doc, &ctx.doc.body, block, block.checked_sub(1), None);
let below = joined(ctx.doc, &ctx.doc.body, block, Some(block + 1), None);
let own = Edges::own(pl, 0, pl.lines.len());
let own = Edges::own(pl, 0, pl.lines.len()).sharing(pl);
Rooms { above, below, top: if above { 0.0 } else { own.top }, bottom: if below { 0.0 } else { own.bottom } }
}
}
@@ -360,6 +440,7 @@ impl<'a> Flow<'a> {
// 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) {
pb.advance(self.block, self.body_top);
unjoin(ctx, self.p);
pb.y += rp.space_before.min(0.0);
return rp.space_before.min(0.0);
}
@@ -557,6 +638,7 @@ impl<'a> Flow<'a> {
fn move_on(&mut self, ctx: &mut Ctx, pb: &mut PageBuilder) {
pb.advance(self.block, self.body_top);
if self.l0 == 0 {
unjoin(ctx, self.p);
let y0 = pb.y;
self.reanchor(ctx, pb, (y0, 0.0), &[]);
self.anchor_y = y0;
@@ -846,6 +928,11 @@ fn line_numbers(ctx: &mut Ctx, pb: &mut PageBuilder, pl: &ParaLayout, (l0, l1):
{
for li in l0..l1 {
let Some(line) = pl.lines.get(li).filter(|l| !l.beside) else { continue };
// The first line of a paragraph going on from the line of the one before (#3986)
// shares that line, numbered already, unless its first word went on the next one.
if li == 0 && pl.shares_line() {
continue;
}
pb.line_no = pb.line_no.saturating_add(1);
let n = pb.line_no.saturating_add(ln.start.saturating_sub(1));
if ln.count_by > 1 && !n.is_multiple_of(ln.count_by) {
@@ -895,7 +982,7 @@ fn place_para_in_flow(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block:
}
let before = f.gap_before(ctx, pb, broke_before);
pb.y += before;
let rooms = Rooms::of(ctx, block, &f.pl);
let mut rooms = Rooms::of(ctx, block, &f.pl);
let applied_before = f.keep_together(ctx, pb, rooms, before);
// A different top only matters when there is something to wrap around.
if spot(pb) != placed_at || ((pb.y - f.guess).abs() > 0.01 && !pb.excl.is_empty()) {
@@ -904,7 +991,10 @@ fn place_para_in_flow(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block:
f.anchor_y = y0 - applied_before;
}
while f.l0 < f.n() {
// A paragraph moved on from the shared line (`unjoin`) is laid out again with borders of its own.
rooms = Rooms::of(ctx, block, &f.pl);
f.keep_again(ctx, pb, rooms);
rooms = Rooms::of(ctx, block, &f.pl);
f.place_due_late(ctx, pb);
f.relay_wrap(ctx, pb);
f.relay_pages(ctx, pb);
@@ -1098,6 +1188,7 @@ fn next_first_line(ctx: &mut Ctx, block: usize, width: f32, depth: usize, new_pa
grid: ctx.grid,
fit_objects: false,
fitted: &[],
joined: false,
};
Arc::new(para::layout_para(p, &env))
}
+8
View File
@@ -319,6 +319,14 @@ pub fn page_lines(page: &Page, story: StoryRef) -> Vec<LineHit<'_>> {
}
}
}
// A paragraph going on from the last line of one whose mark is hidden shares that line
// (#3986): the first one's part of it ends where the second one's text starts.
let joins: Vec<(f32, f32, f32)> = v.iter().filter(|l| l.para.shares_line() && l.li == 0).map(|l| (l.top, l.bottom, l.left)).collect();
for (top, bottom, left) in joins {
for l in v.iter_mut().filter(|l| l.top < bottom && top < l.bottom && l.left < left && left < l.right) {
l.right = left;
}
}
v
}
+13 -1
View File
@@ -1,4 +1,4 @@
use super::boxes::{BoxInput, box_rules, layout_box};
use super::boxes::{BoxInput, Joint, box_rules, layout_box};
use super::ctx::{Ctx, with_pin};
use super::floats::{EarlyFloats, WrapArea};
use super::notes::{NOTE_SEP, NOTE_SEP_W, NoteBox, NoteSeps, v_span};
@@ -35,6 +35,8 @@ pub(crate) struct PageBuilder<'a> {
/// The previous paragraph ended with a page break (its mark stayed with the break): the next
/// paragraph, first on the new page, gets no space before (Word).
pub(crate) after_break_mark: bool,
/// Where the last paragraph, whose mark is hidden, ended: the next one goes on from there.
pub(crate) joint: Option<Joint>,
/// The next section starts on a new page: this section's closing mark, when empty, needs no
/// room (Word leaves it on a full page rather than starting a page for it).
pub(crate) next_starts_page: bool,
@@ -228,6 +230,16 @@ impl PageBuilder<'_> {
self.block_marks.push(pg.items.len().saturating_sub(behind));
}
}
/// Takes back the mark of a block that has placed nothing yet: it goes on from the line of
/// the block before (#3986), and justified vertical alignment keeps the two together.
pub(crate) fn unmark_block(&mut self) {
if let Some(pg) = self.pages.last() {
let behind = self.behind.last().copied().unwrap_or(0);
if self.block_marks.last() == Some(&pg.items.len().saturating_sub(behind)) {
self.block_marks.pop();
}
}
}
/// Justified vertical alignment: share the room left below the page's text out equally
/// between the gaps of its blocks, so the last line sits on the bottom margin (above the
/// footnotes). A page with one block, or several columns, stays at the top.
+12
View File
@@ -101,9 +101,20 @@ pub struct ParaLayout {
/// Room after a cluster between Asian text and Latin text or digits ([`auto_space`]), by
/// cluster index, sorted. It is part of the cluster's advance, but takes no room at a line's end.
pub auto_space: Vec<(usize, f32)>,
/// It goes on from the last line of the paragraph before, whose mark is hidden, and shares
/// that line ([`ParaEnv::joined`]).
pub joined: bool,
/// How tall the line breaker takes a row to be when it checks it against wrap areas.
pub(crate) row_est: f32,
}
impl ParaLayout {
/// Whether its first line is the one it shares with the paragraph before, whose mark is
/// hidden (#3986), rather than a line of its own below it (its first word didn't fit there).
pub(crate) fn shares_line(&self) -> bool {
self.joined && self.lines.first().is_some_and(|l| l.top <= 0.01)
}
/// The room a horizontal rule at cluster `k` is placed in, from its left edge to the end of
/// what the line has left. A first-line indent moves that end along (Word, measured with
/// 50 % and fixed-width rules beside floats on either side and with first-line and hanging
@@ -359,6 +370,7 @@ mod label_spacing_tests {
read_line_spacing: None,
fit_objects: false,
fitted: &[],
joined: false,
};
let mut p = Paragraph::with_text(if wrap { "Alpha probe synthetic business text repeated" } else { "Alpha probe" }, Default::default());
p.props.line_spacing = Some(spacing);
+22 -6
View File
@@ -63,6 +63,9 @@ struct Breaker<'e> {
row_first: usize,
/// Spans skipped in a row because the next word didn't fit (see `Scan::skip`).
skipped: usize,
/// The paragraph goes on from the line of the one before (#3986): its first line starts right
/// after that one's text, and takes its place there whatever its own alignment.
joined: bool,
/// A left tab past the right indent that wrapped to start the next line.
wrapped_tab: Option<usize>,
}
@@ -188,7 +191,9 @@ impl<'e> Breaker<'e> {
n: pl.clusters.len(),
width,
base_right: (width - rp.indent_right).max(1.0),
first_left: rp.indent_left + rp.indent_first,
// On the line it shares with the paragraph before (#3986), kept clear of that one's
// text by an exclusion, a joined paragraph's own indents don't hold its text back.
first_left: if env.joined { (rp.indent_left + rp.indent_first).min(0.0) } else { rp.indent_left + rp.indent_first },
default_tab: settings.default_tab,
hanging_at: if rp.indent_first < 0.0 { Some(rp.indent_left) } else { None },
tab_origin: if settings.odf.is_some_and(|o| o.tabs_from_indent) { rp.indent_left } else { 0.0 },
@@ -222,13 +227,20 @@ impl<'e> Breaker<'e> {
row_rest: VecDeque::new(),
row_first: 0,
skipped: 0,
joined: env.joined,
wrapped_tab: None,
}
}
/// The first line's start: a joined paragraph's first line pushed below the shared line (its
/// first word didn't fit there) starts at the paragraph's left indent, as its other lines do.
fn first_indent(&self) -> f32 {
if self.joined && self.top > 0.0 { self.rp.indent_left } else { self.first_left }
}
/// The left edge of the row's first span: the indent, behind a drop cap on its lines.
fn row_left(&self, pl: &ParaLayout) -> f32 {
let lo = if self.first { self.first_left } else { self.rp.indent_left };
let lo = if self.first { self.first_indent() } else { self.rp.indent_left };
match pl.drop_cap {
Some((_, dl, dw)) if dw > 0.0 && self.lines.len() < dl as usize => self.first_left.max(self.rp.indent_left) + dw,
_ => lo,
@@ -271,7 +283,7 @@ impl<'e> Breaker<'e> {
/// The start of a line: its span, and the list label if it is the first.
fn begin_line(&mut self, pl: &mut ParaLayout) -> Scan {
let beside = !self.row_rest.is_empty() && self.lines.len() > self.row_first;
let row_lo = if self.first { self.first_left } else { self.rp.indent_left };
let row_lo = if self.first { self.first_indent() } else { self.rp.indent_left };
let (left, right_edge, narrowed) = self.next_span(pl);
let x = if self.first { self.place_label(pl, left) } else { left };
Scan {
@@ -563,7 +575,10 @@ impl<'e> Breaker<'e> {
let last_tab = (c0..c1).rev().find(|k| pl.clusters.get(*k).is_some_and(|c| c.kind == ClKind::Tab));
let align_from = last_tab.map(|k| k + 1).unwrap_or(c0);
let display = pl.displays.iter().find(|(ci, _)| *ci >= c0 && *ci < c1).map(|d| d.1);
let shift = match (display, rp.align) {
// The line a paragraph shares with the one before, whose mark is hidden, starts in that
// one, and takes its place right after that one's text (Word, #3986).
let align = if self.joined && self.lines.is_empty() { Align::Left } else { rp.align };
let shift = match (display, align) {
(Some(MathJc::Left), _) => 0.0,
(Some(MathJc::Right), _) => slack,
(Some(_), _) => slack / 2.0,
@@ -587,13 +602,13 @@ impl<'e> Breaker<'e> {
}
// A line ending in a manual line break is stretched too, unless `doNotExpandShiftReturn` says not to.
let stretch_end = sc.end == LineEnd::Wrap || (sc.end == LineEnd::LineBreak && self.expand_break);
let justify = display.is_none() && ((rp.align == Align::Justify && stretch_end) || rp.align == Align::Distribute);
let justify = display.is_none() && ((align == Align::Justify && stretch_end) || align == Align::Distribute);
// A line that only fits with shrunk spaces is shrunk, the last line of the paragraph too.
let shrink = display.is_none() && self.shrink_spaces && slack < 0.0 && last_tab.is_none();
if shrink {
shrink_line_spaces(pl, &mut sc.xs, c0, c1, content_end, slack);
} else if justify && slack > 0.0 {
justify_line(pl, &mut sc.xs, (c0, c1, align_from), (content_end, slack), rp.align == Align::Distribute);
justify_line(pl, &mut sc.xs, (c0, c1, align_from), (content_end, slack), align == Align::Distribute);
}
}
@@ -692,6 +707,7 @@ impl<'e> Breaker<'e> {
fn finish(mut self, pl: &mut ParaLayout) {
self.hang_drop_cap(pl);
pl.height = self.top;
pl.row_est = self.est_h;
pl.lines = std::mem::take(&mut self.lines);
let label_shift = self.label_shifts.get(pl.label_line()).copied().unwrap_or(0.0);
if let Some(lab) = pl.label.as_mut() {
+3
View File
@@ -401,4 +401,7 @@ pub struct ParaEnv<'a> {
/// Heights of the paragraph's inline text boxes that resize to fit their text, by object
/// index: they take these instead of their saved heights.
pub fitted: &'a [(usize, f32)],
/// The paragraph goes on from the line of the one before, whose mark is hidden (#3986): its
/// list number is counted and sets its indents, but isn't drawn.
pub joined: bool,
}
+6 -3
View File
@@ -533,13 +533,14 @@ fn mark_break_opportunities(clusters: &mut [Cluster], bt: &BreakText, rp: &Resol
}
}
/// The list label, shaped; none on a paragraph containing only a page break: Word hides it there.
/// The list counter has already advanced, so the following item keeps its number.
/// The list label, shaped; none on a paragraph containing only a page break, nor on one that goes
/// on from the line of the paragraph before (#3986): Word hides it there. The list counter has
/// already advanced, so the following item keeps its number.
fn list_label(cx: &Cx, b: &mut Builder, mark_style: u32) -> Option<Label> {
let (p, rp) = (cx.p, cx.rp);
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)?;
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));
// 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
@@ -713,6 +714,8 @@ pub fn layout_para(p: &Paragraph, env: &ParaEnv) -> ParaLayout {
left_out: Vec::new(),
enclosures,
auto_space,
joined: env.joined,
row_est: 0.0,
};
let auto = env.doc.settings.auto_hyphenation && !pl.rp.suppress_hyphens;
pl.hyph_after = hyphenation_points(&bt.text, |i| bt.to_para(i), &pl, auto, env.doc.settings.hyphenate_caps, &runs);
+2
View File
@@ -110,6 +110,7 @@ fn new_ctx<'a>(
track_totals: true,
pct_base: None,
quiet_marks: Vec::new(),
joined: None,
stacked_marks: Vec::new(),
mirror: false,
table_keys: Vec::new(),
@@ -211,6 +212,7 @@ fn new_page_builder<'p>(
orig_bottom: 0.0,
prev: None,
after_break_mark: false,
joint: None,
next_starts_page: false,
restart_at: None,
excl: Vec::new(),
+1
View File
@@ -233,6 +233,7 @@ pub fn measure_table_columns(doc: &wordcraft_doc::Document, t: &Table) -> Vec<(f
grid: crate::para::Grid::default(),
fit_objects: false,
fitted: &[],
joined: false,
};
let (mut min, mut max) = (EMPTY_TEXT, EMPTY_TEXT);
if cell.props.vmerge != VMerge::Continue && !cell.props.text_direction.is_turned() {
+405
View File
@@ -13,6 +13,7 @@ mod complex;
mod float_top;
mod grid;
mod header_legacy_float;
mod joined;
mod keep_next_section;
mod ligature;
pub(crate) mod linear;
@@ -2252,6 +2253,410 @@ fn empty_list_paragraph_with_a_hidden_mark_counts_but_shows_nothing() {
}
}
#[test]
fn a_paragraph_with_a_hidden_mark_goes_on_into_the_next_one() {
// Word (#3986): a paragraph whose mark is hidden is shown on one line with the next one. The
// next one's text goes on from where the first one's ends; its number is counted but not
// drawn ("1. AlphaOmega", then "3. Beta") and it takes no line of its own. A paragraph that
// shows nothing in between passes the joint on. In a table cell as in the body.
let doc = |paras: &[(&str, bool)], in_cell: bool| {
let text: Vec<&str> = paras.iter().map(|(t, _)| *t).collect();
let mut d = Document::from_text(&text.join("\n"));
let id = Arc::make_mut(&mut d.numbering).add_list(wordcraft_doc::ListKind::Numbered);
let last = d.body.len() - 1;
let end = paras.last().map_or(0, |(t, _)| t.len());
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(last, end), &|p| {
p.numbering = Some(wordcraft_doc::props::NumRef { num: id, level: 0 });
})
.unwrap();
for (i, (_, hidden)) in paras.iter().enumerate() {
if *hidden {
d.para_mut(StoryRef::Body, &Path::top(i)).unwrap().mark.hidden = Some(true);
}
}
if in_cell {
let mut table = Table::new(1, 1, 400.0);
table.rows[0].cells[0].blocks = std::mem::take(&mut d.body);
d.body = vec![std::sync::Arc::new(Block::Table(table))];
}
d
};
// Each paragraph's number, the top of its first line, and the x its text starts and ends at.
let laid = |d: &Document, show_hidden: bool| {
let l = layout(d, &mut LayoutCache::new(), &LayoutOptions { show_hidden, ..Default::default() });
let lines: Vec<(Option<String>, f32, f32, f32)> = l
.pages
.iter()
.flat_map(|p| &p.items)
.filter_map(|it| match it {
Placed::Lines { para, l0, l1, x, y, .. } => {
let last = l1.checked_sub(1)?;
Some((para.label.as_ref().map(|label| label.text.clone()), *y, x + para.x_of(*l0, 0)?, x + para.x_of(last, para.text_len)?))
}
_ => None,
})
.collect();
lines
};
for in_cell in [false, true] {
let plain = laid(&doc(&[("Alpha", false), ("Beta", false)], in_cell), false);
let beta_y = plain[1].1;
// Text: "Omega" on Alpha's line, after Alpha's text.
let joined = laid(&doc(&[("Alpha", true), ("Omega", false), ("Beta", false)], in_cell), false);
let labels: Vec<_> = joined.iter().map(|l| l.0.as_deref()).collect();
assert_eq!(labels, vec![Some("1."), None, Some("3.")], "in_cell={in_cell}");
assert!((joined[1].1 - joined[0].1).abs() < 0.01, "in_cell={in_cell}: Omega at {} not on Alpha's line {}", joined[1].1, joined[0].1);
assert!((joined[1].2 - joined[0].3).abs() < 0.5, "in_cell={in_cell}: Omega starts at {}, Alpha ends at {}", joined[1].2, joined[0].3);
assert!((joined[2].1 - beta_y).abs() < 0.01, "in_cell={in_cell}: Beta at {} instead of {beta_y}", joined[2].1);
// An empty paragraph: no line of its own, no number.
let empty = laid(&doc(&[("Alpha", true), ("", false), ("Beta", false)], in_cell), false);
let labels: Vec<_> = empty.iter().map(|l| l.0.as_deref()).collect();
assert_eq!(labels, vec![Some("1."), None, Some("3.")], "in_cell={in_cell}");
assert!((empty[2].1 - beta_y).abs() < 0.01, "in_cell={in_cell}: Beta at {} instead of {beta_y}", empty[2].1);
// Through an empty paragraph with a hidden mark (which shows nothing).
let chain = laid(&doc(&[("Alpha", true), ("", true), ("Omega", false), ("Beta", false)], in_cell), false);
let labels: Vec<_> = chain.iter().map(|l| l.0.as_deref()).collect();
assert_eq!(labels, vec![Some("1."), None, None, Some("4.")], "in_cell={in_cell}");
assert!((chain[2].1 - chain[0].1).abs() < 0.01, "in_cell={in_cell}: Omega not on Alpha's line");
// Hidden text shown: each paragraph on its own line, with its number.
let shown = laid(&doc(&[("Alpha", true), ("Omega", false), ("Beta", false)], in_cell), true);
let labels: Vec<_> = shown.iter().map(|l| l.0.as_deref()).collect();
assert_eq!(labels, vec![Some("1."), Some("2."), Some("3.")], "in_cell={in_cell}");
assert!(shown[1].1 > shown[0].1 + 5.0, "in_cell={in_cell}: shown hidden text keeps the paragraphs apart");
}
// A click on the joined text lands in the paragraph it belongs to.
let d = doc(&[("Alpha", true), ("Omega", false), ("Beta", false)], false);
let l = lay(&d);
let omega = l.caret(&Pos::body(1, 2)).unwrap();
let hit = l.hit(omega.page, omega.x + 0.5, omega.top + omega.height / 2.0, StoryRef::Body).unwrap();
assert_eq!(hit.path, Path::top(1));
}
#[test]
fn text_going_on_from_a_larger_heading_sits_on_its_baseline() {
// A heading with a hidden mark followed by body text (a style separator in Word, #3986): the
// body text's first line goes on beside the heading, on the heading's baseline; its next lines
// start at the margin, below both.
let body = "Body text that is long enough to wrap onto a second line in this column. ".repeat(3);
let mut d = Document::from_text(&format!("Heading\n{body}"));
d.format_range(&Pos::body(0, 0), &Pos::body(0, 7), &|c| c.size = Some(18.0)).unwrap();
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().mark.hidden = Some(true);
let l = lay(&d);
let lines: Vec<(Path, f32, f32, f32)> = l.pages[0]
.items
.iter()
.filter_map(|it| match it {
Placed::Lines { path, para, l0, l1, x, y, .. } => {
let first = para.lines.get(*l0)?;
let (x, y) = (*x, *y);
Some((*l0..*l1).filter_map(move |li| {
let line = para.lines.get(li)?;
Some((path.clone(), y + line.baseline - first.top, x + para.x_of(li, line.start)?, y + line.top - first.top))
}))
}
_ => None,
})
.flatten()
.collect();
let heading = lines.iter().find(|l| l.0 == Path::top(0)).unwrap();
let body: Vec<_> = lines.iter().filter(|l| l.0 == Path::top(1)).collect();
assert!(body.len() >= 2, "{lines:?}");
assert!((body[0].1 - heading.1).abs() < 0.01, "body baseline {} vs heading {}", body[0].1, heading.1);
assert!(body[0].2 > 100.0, "the body text starts after the heading's, at {}", body[0].2);
assert!((body[1].2 - 72.0).abs() < 0.5, "the next line starts at the margin, not at {}", body[1].2);
assert!(body[1].3 > heading.1, "the next line is below the shared one");
}
#[test]
fn a_text_box_anchored_in_a_paragraph_with_a_hidden_mark_is_not_joined() {
// A text box anchored in the first paragraph lays its own story out, whose first line has
// the same path as that paragraph (#3986). The next paragraph goes on from the paragraph's
// text, not from the box's, which is drawn after it.
let mut d = Document::from_text("Alpha\nOmega");
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().mark.hidden = Some(true);
let float = wordcraft_doc::para::Float {
wrap: wordcraft_doc::para::Wrap::InFrontOfText,
h_rel: wordcraft_doc::para::Anchor::Column,
v_rel: wordcraft_doc::para::Anchor::Paragraph,
x: 200.0,
y: 100.0,
dist: 0.0,
..Default::default()
};
text_box(&mut d, 0, "Box", 100.0, 40.0, float);
let l = lay(&d);
// The top of a story's line at a block, and the x its text starts and ends at.
let line = |story: StoryRef, block: usize| {
l.pages[0].items.iter().find_map(|it| match it {
Placed::Lines { story: s, path, para, l0, l1, x, y, .. } if *s == story && *path == Path::top(block) => {
Some((*y, x + para.x_of(*l0, 0)?, x + para.x_of(l1.checked_sub(1)?, para.text_len)?))
}
_ => None,
})
};
let (alpha, omega) = (line(StoryRef::Body, 0).unwrap(), line(StoryRef::Body, 1).unwrap());
assert!((omega.0 - alpha.0).abs() < 0.01, "Omega at {} not on Alpha's line {}", omega.0, alpha.0);
assert!((omega.1 - alpha.2).abs() < 0.5, "Omega starts at {}, Alpha ends at {}", omega.1, alpha.2);
}
#[test]
fn a_joined_paragraph_moved_to_the_next_page_has_its_own_number() {
// A paragraph going on from one with a hidden mark (#3986) that moves whole to the next page
// (its lines kept together) no longer shares that line: there its number is drawn and its
// text starts at its own indent.
let omega = "Omega ".repeat(60);
let build = |filler: usize| {
let mut text: Vec<String> = (0..filler).map(|i| format!("Filler {i}")).collect();
text.push("Alpha".into());
text.push(omega.clone());
let mut d = Document::from_text(&text.join("\n"));
let id = Arc::make_mut(&mut d.numbering).add_list(wordcraft_doc::ListKind::Numbered);
d.format_paragraphs(&Pos::body(filler, 0), &Pos::body(filler + 1, omega.len()), &|p| {
p.numbering = Some(wordcraft_doc::props::NumRef { num: id, level: 0 });
})
.unwrap();
d.para_mut(StoryRef::Body, &Path::top(filler)).unwrap().mark.hidden = Some(true);
d.para_mut(StoryRef::Body, &Path::top(filler + 1)).unwrap().props.keep_lines = Some(true);
d
};
// The page of a paragraph's first line, with its number there.
let first = |l: &DocLayout, block: usize| {
l.pages.iter().enumerate().find_map(|(pi, page)| {
page.items.iter().find_map(|it| match it {
Placed::Lines { path, para, l0: 0, .. } if *path == Path::top(block) => {
Some((pi, para.label.as_ref().map(|label| label.text.clone())))
}
_ => None,
})
})
};
for filler in 20..80 {
let d = build(filler);
let l = lay(&d);
let (Some((0, alpha)), Some((1, omega_label))) = (first(&l, filler), first(&l, filler + 1)) else { continue };
assert_eq!(alpha.as_deref(), Some("1."));
assert_eq!(omega_label.as_deref(), Some("2."), "the moved paragraph draws its number");
let (a, o) = (l.caret(&Pos::body(filler, 0)).unwrap(), l.caret(&Pos::body(filler + 1, 0)).unwrap());
assert_eq!(o.page, 1);
assert!((o.x - a.x).abs() < 0.5, "the moved paragraph's text starts at its own indent: {} vs {}", o.x, a.x);
return;
}
panic!("no filler put Alpha last on the first page with the joined paragraph moved on");
}
#[test]
fn a_joined_first_word_that_does_not_fit_goes_on_the_next_line_at_the_indent() {
// Word (#3986): when the next paragraph's first word doesn't fit after the first one's text,
// it goes on the next line, still joined (no number drawn), at the indent of the list's text.
let build = |n: usize| {
let alpha = vec!["aa"; n].join(" ");
let omega = "Omegaomegaomega tail";
let mut d = Document::from_text(&format!("{alpha}\n{omega}"));
let id = Arc::make_mut(&mut d.numbering).add_list(wordcraft_doc::ListKind::Numbered);
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(1, omega.len()), &|p| {
p.numbering = Some(wordcraft_doc::props::NumRef { num: id, level: 0 });
})
.unwrap();
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().mark.hidden = Some(true);
(d, alpha.len())
};
for n in 20..200 {
let (d, alpha_len) = build(n);
let l = lay(&d);
let (end, start) = (l.caret(&Pos::body(0, alpha_len)).unwrap(), l.caret(&Pos::body(1, 0)).unwrap());
if (start.top - end.top).abs() < 0.5 {
continue; // still on the shared line
}
let indent = l.caret(&Pos::body(0, 0)).unwrap().x;
assert!(start.top > end.top, "the first word goes below the shared line");
assert!((start.x - indent).abs() < 0.5, "at the list text's indent {indent}, not {}", start.x);
let label = l.pages.iter().flat_map(|p| &p.items).find_map(|it| match it {
Placed::Lines { path, para, .. } if *path == Path::top(1) => Some(para.label.as_ref().map(|label| label.text.clone())),
_ => None,
});
assert_eq!(label, Some(None), "still joined: no number drawn");
return;
}
panic!("no length of the first paragraph left its last line too full for the next one's first word");
}
#[test]
fn a_shared_line_is_one_line_for_line_numbers_and_vertical_alignment() {
// Word (#3986): the line two paragraphs share through a hidden mark is one line. Line
// numbering gives it one number ("Line one", the shared line, "After": 1, 2, 3), and justified
// vertical alignment keeps the two paragraphs together as one block.
let doc = |valign: wordcraft_doc::section::PageVAlign| {
let mut d = Document::from_text("Line one\nAlpha\nOmega\nAfter");
for b in d.body.iter_mut() {
if let Block::Para(p) = std::sync::Arc::make_mut(b) {
p.props.space_before = Some(0.0);
p.props.space_after = Some(0.0);
}
}
d.para_mut(StoryRef::Body, &Path::top(1)).unwrap().mark.hidden = Some(true);
d.last_section.valign = valign;
d
};
let mut d = doc(wordcraft_doc::section::PageVAlign::Top);
d.last_section.line_numbers = Some(Default::default());
let l = lay(&d);
let numbers: Vec<f32> = l.pages[0]
.items
.iter()
.filter_map(|it| match it {
Placed::Lines { story, y, .. } if *story == DECOR_STORY => Some(*y),
_ => None,
})
.collect();
assert_eq!(numbers.len(), 3, "one number per shown line: {numbers:?}");
assert!(numbers.windows(2).all(|w| w[1] > w[0] + 5.0), "no two numbers on one line: {numbers:?}");
let l = lay(&doc(wordcraft_doc::section::PageVAlign::Justify));
let y = |off: (usize, usize)| l.caret(&Pos::body(off.0, off.1)).unwrap().top;
assert!((y((2, 0)) - y((1, 0))).abs() < 0.01, "Omega stays on Alpha's line: {} vs {}", y((2, 0)), y((1, 0)));
let (g1, g2) = (y((1, 0)) - y((0, 0)), y((3, 0)) - y((1, 0)));
assert!(g1 > 100.0 && (g1 - g2).abs() < 0.05, "equal gaps around the shared line: {g1} {g2}");
}
#[test]
fn a_joined_line_with_a_hanging_indent_still_starts_after_the_text_before() {
// The joined paragraph's first-line indent reaches left of the margin: its text still starts
// after the text of the paragraph before, never left of it (#3986).
let mut d = Document::from_text("Alpha\na b c");
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().mark.hidden = Some(true);
let q = d.para_mut(StoryRef::Body, &Path::top(1)).unwrap();
q.props.indent_left = Some(0.0);
q.props.indent_first = Some(-36.0);
let l = lay(&d);
let (end, start) = (l.caret(&Pos::body(0, 5)).unwrap(), l.caret(&Pos::body(1, 0)).unwrap());
assert!((start.top - end.top).abs() < 0.01, "on the shared line");
assert!(start.x >= end.x - 0.01, "after Alpha: starts at {}, Alpha ends at {}", start.x, end.x);
}
#[test]
fn a_joined_paragraphs_shading_and_borders_start_below_the_shared_line() {
// Word (synthetic DOCX, 16.0.20625): the line a paragraph shares with the one before, whose
// mark is hidden, shows that one's shading and borders, not its own. Its own start on its next
// line (no top border there), and a paragraph that is all on the shared line shows neither and
// takes no room for its borders; what follows starts below the first one's bottom border.
let yellow = wordcraft_doc::props::Rgb(0xFF, 0xFF, 0);
let boxed = || Some(Borders::all(Border { space: 1.0, ..Border::single(1.5) }));
// "Alpha" (mark hidden) with `first`'s formatting, then `second` with its own, then "After".
let doc = |first: &dyn Fn(&mut ParaProps), second_text: &str, second: &dyn Fn(&mut ParaProps), in_cell: bool| {
let mut d = Document::from_text(&format!("Alpha\n{second_text}\nAfter"));
let a = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
a.mark.hidden = Some(true);
first(&mut a.props);
second(&mut d.para_mut(StoryRef::Body, &Path::top(1)).unwrap().props);
if in_cell {
let mut table = Table::new(1, 1, 400.0);
table.props.borders = Some(Borders::all(Border { style: BorderStyle::None, width: 0.0, color: None, space: 0.0 }));
table.rows[0].cells[0].blocks = std::mem::take(&mut d.body);
d.body = vec![std::sync::Arc::new(Block::Table(table))];
}
d
};
let path = |i: u32, in_cell: bool| if in_cell { Path(vec![0, 0, 0, i]) } else { Path::top(i as usize) };
// The shared line (top, bottom), "After"'s top, fills and the paragraphs' horizontal rules.
let laid = |d: &Document, in_cell: bool| {
crate::test_fonts();
let l = lay(d);
let at = |i: u32| l.caret(&Pos { story: StoryRef::Body, path: path(i, in_cell), off: 0 }).unwrap();
let (alpha, after) = (at(0), at(2));
let fills: Vec<Rect> = l.pages[0]
.items
.iter()
.filter_map(|i| if let Placed::Fill { rect, color } = i { (*color == yellow).then_some(*rect) } else { None })
.collect();
let rules: Vec<(f32, f32, f32, f32)> = l.pages[0]
.items
.iter()
.filter_map(
|i| if let Placed::Rule { x0, y0, x1, y1, border } = i { (border.width == 1.5).then_some((*x0, *y0, *x1, *y1)) } else { None },
)
.collect();
(alpha.top, alpha.top + alpha.height, after.top, fills, rules)
};
let none = |_: &mut ParaProps| {};
let long = format!("Omega {}", "zeta ".repeat(30));
for in_cell in [false, true] {
let (top, bottom, after, ..) = laid(&doc(&none, "Omega", &none, in_cell), in_cell);
// The second one shaded, all of it on the shared line: no shading over "Alpha".
let (t, _, a, fills, _) = laid(&doc(&none, "Omega", &|p| p.shading = Some(yellow), in_cell), in_cell);
assert!(fills.is_empty(), "in_cell={in_cell}: {fills:?}");
assert!((t - top).abs() < 0.01 && (a - after).abs() < 0.01, "in_cell={in_cell}");
// Shaded and running on: the shading starts on its own next line.
let (_, b, _, fills, _) = laid(&doc(&none, &long, &|p| p.shading = Some(yellow), in_cell), in_cell);
assert_eq!(fills.len(), 1, "in_cell={in_cell}: {fills:?}");
assert!(fills[0].y >= b - 0.01, "in_cell={in_cell}: shading from {} over the shared line ending at {b}", fills[0].y);
// The first one shaded: the shared line is.
let (t, b, _, fills, _) = laid(&doc(&|p| p.shading = Some(yellow), "Omega", &none, in_cell), in_cell);
assert_eq!(fills.len(), 1, "in_cell={in_cell}: {fills:?}");
assert!(fills[0].y <= t + 0.01 && fills[0].bottom() >= b - 0.01, "in_cell={in_cell}: {fills:?}");
// The second one boxed, all of it on the shared line: no borders, no room for them.
let (t, _, a, _, rules) = laid(&doc(&none, "Omega", &|p| p.borders = boxed(), in_cell), in_cell);
assert!(rules.is_empty(), "in_cell={in_cell}: {rules:?}");
assert!((t - top).abs() < 0.01 && (a - after).abs() < 0.01, "in_cell={in_cell}: {t} {a}");
// Boxed and running on: its box is around its own lines, open at the top, with its bottom
// border's room under it; the shared line stays where it is.
let (t, b, _, _, rules) = laid(&doc(&none, &long, &|p| p.borders = boxed(), in_cell), in_cell);
assert!((t - top).abs() < 0.01, "in_cell={in_cell}: shared line moved to {t}");
assert_eq!(rules.iter().filter(|r| r.1 == r.3).count(), 1, "in_cell={in_cell}: only the bottom border: {rules:?}");
assert!(rules.iter().all(|r| r.1.min(r.3) >= b - 0.01), "in_cell={in_cell}: a border over the shared line: {rules:?}");
// The first one boxed: what follows starts below its bottom border.
let (_, _, a, _, rules) = laid(&doc(&|p| p.borders = boxed(), "Omega", &none, in_cell), in_cell);
let bottom_rule = rules.iter().filter(|r| r.1 == r.3).map(|r| r.1).fold(f32::MIN, f32::max);
assert!(bottom_rule > bottom, "in_cell={in_cell}: {rules:?}");
assert!(a >= bottom_rule + 0.75 - 0.01, "in_cell={in_cell}: After at {a}, over the border at {bottom_rule}");
}
}
#[test]
fn a_joined_paragraph_keeps_its_revision_for_the_cache_and_the_word_being_typed() {
// The joined paragraph is laid out as a copy without its space before (#3986). The copy keeps
// the document's revision: the word being typed in it gets no squiggle, and laying the
// document out again reuses its layouts.
crate::test_fonts();
let mut d = Document::from_text("Alpha\nhelo wrld\nAfter");
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().mark.hidden = Some(true);
let rev = d.para(StoryRef::Body, &Path::top(1)).unwrap().rev;
let marks = |l: &DocLayout| -> Vec<String> {
l.pages[0]
.items
.iter()
.filter_map(|i| match i {
Placed::Lines { para, path, .. } if *path == Path::top(1) => {
Some(para.issues.iter().filter(|i| !i.2).map(|i| "helo wrld"[i.0..i.1].to_string()).collect::<Vec<_>>())
}
_ => None,
})
.flatten()
.collect()
};
let mut c = LayoutCache::new();
let opts = LayoutOptions { proofing: true, ..LayoutOptions::default() };
let both = layout(&d, &mut c, &opts);
assert_eq!(marks(&both), ["helo", "wrld"]);
let (a, b) = (both.caret(&Pos::body(0, 5)).unwrap(), both.caret(&Pos::body(1, 0)).unwrap());
assert!((a.top - b.top).abs() < 0.01, "joined");
let misses = c.misses;
let again = layout(&d, &mut c, &opts);
assert_eq!(marks(&again), ["helo", "wrld"]);
assert_eq!(c.misses, misses, "nothing laid out again");
let typing = layout(&d, &mut c, &LayoutOptions { typing_word: Some(TypingWord { rev, start: 5, end: 9 }), ..opts.clone() });
assert_eq!(marks(&typing), ["helo"], "the word being typed is left alone");
}
#[test]
fn a_numbered_heading_opening_with_a_page_break_takes_its_number_along() {
crate::test_fonts();
+165
View File
@@ -0,0 +1,165 @@
//! A paragraph going on from the line of one whose mark is hidden (#3986): what changes when it
//! moves off that line or is placed apart from it.
use super::lay;
use crate::{Arc, DocLayout, Placed, StoryRef, hit};
use wordcraft_doc::para::{Anchor, Float, Wrap};
use wordcraft_doc::props::{Border, Borders, LineSpacing, NumRef, TextFrame};
use wordcraft_doc::{Block, Document, Path, Pos, Table};
/// A table around the document's paragraphs (the cell paths are `[0, 0, 0, i]`).
fn in_cell(d: &mut Document) {
let mut table = Table::new(1, 1, 400.0);
table.rows[0].cells[0].blocks = std::mem::take(&mut d.body);
d.body = vec![Arc::new(Block::Table(table))];
}
/// The top of the lines of the body block or cell paragraph at `path`.
fn top_of(l: &DocLayout, path: &Path) -> f32 {
l.pages[0]
.items
.iter()
.find_map(|it| match it {
Placed::Lines { story: StoryRef::Body, path: p, y, .. } if p == path => Some(*y),
_ => None,
})
.unwrap_or_else(|| panic!("no lines at {path:?}"))
}
#[test]
fn a_joined_paragraph_moved_to_the_next_page_gets_its_top_border() {
// Sharing the line it takes no room for a top border; moved whole to the next page it is
// laid out on its own and draws one above its first line.
let omega = "Omega ".repeat(60);
let boxed = Some(Borders::all(Border { space: 1.0, ..Border::single(1.5) }));
for filler in 20..80 {
let mut text: Vec<String> = (0..filler).map(|i| format!("Filler {i}")).collect();
text.push("Alpha".into());
text.push(omega.clone());
let mut d = Document::from_text(&text.join("\n"));
d.para_mut(StoryRef::Body, &Path::top(filler)).unwrap().mark.hidden = Some(true);
let o = d.para_mut(StoryRef::Body, &Path::top(filler + 1)).unwrap();
(o.props.keep_lines, o.props.borders) = (Some(true), boxed);
let l = lay(&d);
let o = l.caret(&Pos::body(filler + 1, 0)).unwrap();
if l.caret(&Pos::body(filler, 0)).unwrap().page != 0 || o.page != 1 {
continue;
}
let tops = l.pages[1].items.iter().filter(|i| matches!(i, Placed::Rule { y0, y1, border, .. } if y0 == y1 && border.width == 1.5));
let above = tops.filter(|i| matches!(i, Placed::Rule { y0, .. } if *y0 < o.top)).count();
assert_eq!(above, 1, "the moved paragraph draws its top border above its first line");
return;
}
panic!("no filler moved the joined paragraph to the next page");
}
#[test]
fn a_joined_first_line_below_the_shared_line_does_not_cut_the_line_above() {
// "Omega"'s first word does not fit after "Alpha", so its first line goes below; its indent
// (inside "Alpha"'s text) must not cut "Alpha"'s hit extent.
let mut d = Document::from_text(&format!("Alpha\n{} tail", "W".repeat(48)));
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().mark.hidden = Some(true);
d.para_mut(StoryRef::Body, &Path::top(1)).unwrap().props.indent_left = Some(20.0);
let l = lay(&d);
let lines = hit::page_lines(&l.pages[0], StoryRef::Body);
let alpha = lines.iter().find(|h| h.path == &Path::top(0)).unwrap();
let omega = lines.iter().find(|h| h.path == &Path::top(1) && h.li == 0).unwrap();
assert!(omega.top > alpha.top + 1.0, "setup: the first word moved below the shared line");
let text_end = l.caret(&Pos::body(0, 5)).unwrap().x;
assert!(alpha.right >= text_end - 0.5, "Alpha's line reaches {} but its text ends at {text_end}", alpha.right);
}
#[test]
fn a_joined_paragraphs_drawings_are_relative_to_the_shared_line() {
// A drawing anchored to the paragraph, at its top: the paragraph's top is the shared line's,
// not the end of the paragraph before.
let mut d = Document::from_text("Alpha\nOmega\nAfter");
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().mark.hidden = Some(true);
let float =
Float { wrap: Wrap::InFrontOfText, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, x: 200.0, y: 0.0, dist: 0.0, ..Default::default() };
super::text_box_at(&mut d, &Pos::body(1, 0), "Box", 100.0, 40.0, float);
in_cell(&mut d);
let l = lay(&d);
let alpha = top_of(&l, &Path(vec![0, 0, 0, 0]));
let boxed = l.pages[0].items.iter().find_map(|it| match it {
Placed::Lines { story: StoryRef::Part(_), y, .. } => Some(*y),
_ => None,
});
let boxed = boxed.expect("the box's text is laid out");
assert!(boxed < alpha + 12.0, "the box's text at {boxed} is below the shared line at {alpha}");
}
#[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
// drawn (it is counted either way). The frame is its own, or given by the table's style.
let frame =
TextFrame { x_align: Some("right".into()), h_anchor: "text".into(), v_anchor: "text".into(), wrap: "around".into(), ..Default::default() };
for from_style in [false, true] {
let mut d = Document::from_text("Alpha\n7");
let id = Arc::make_mut(&mut d.numbering).add_list(wordcraft_doc::ListKind::Numbered);
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(1, 1), &|p| p.numbering = Some(NumRef { num: id, level: 0 })).unwrap();
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().mark.hidden = Some(true);
// From the table's style, the frame is given to "Alpha" too: zero dimensions cancel it there.
let (at, own) = if from_style { (0, TextFrame { w: Some(0.0), h: Some(0.0), ..frame.clone() }) } else { (1, frame.clone()) };
d.para_mut(StoryRef::Body, &Path::top(at)).unwrap().props.frame = Some(own);
in_cell(&mut d);
if from_style {
Arc::make_mut(&mut d.styles).get_mut("TableGrid").expect("Table Grid").para.frame = Some(frame.clone());
if let Some(Block::Table(t)) = d.body.first_mut().map(Arc::make_mut) {
t.props.style = Some("TableGrid".into());
}
}
let l = lay(&d);
let label = l.pages[0].items.iter().find_map(|it| match it {
Placed::Lines { path, para, .. } if path.0 == [0, 0, 0, 1] => Some(para.label.is_some()),
_ => None,
});
assert_eq!(label, Some(true), "the framed paragraph keeps its number (frame from the table style: {from_style})");
}
}
#[test]
fn a_joined_paragraphs_later_lines_start_below_a_taller_shared_line() {
// A heading whose mark is hidden, then body text going on from it: the text's first line
// shares the heading's line; its later lines start below that line and the heading's bottom
// border, not inside it (Word), whatever the text's line spacing.
let spacings = [None, Some(LineSpacing::Exactly(12.0)), Some(LineSpacing::AtLeast(12.0)), Some(LineSpacing::Multiple(2.0))];
// A large word that fits the first line of the text laid out alone but wraps off the
// narrower shared line onto the second (`big`), so the two first lines differ in height.
let cases = [false, true].into_iter().flat_map(|c| spacings.into_iter().flat_map(move |s| [(c, s, false, None), (c, s, true, None)]));
let big = [60, 70, 80].into_iter().flat_map(|at| [(false, None, false, Some(at)), (true, None, false, Some(at))]);
for (cell, spacing, bordered, large) in cases.chain(big) {
let case = format!("cell {cell}, {spacing:?}, border {bordered}, large word at {large:?}");
let mut d = Document::from_text(&format!("Heading\n{}", "body text ".repeat(40)));
d.format_range(&Pos::body(0, 0), &Pos::body(0, 7), &|c| c.size = Some(40.0)).unwrap();
if let Some(at) = large {
d.format_range(&Pos::body(1, at), &Pos::body(1, at + 4), &|c| c.size = Some(30.0)).unwrap();
}
let heading = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
heading.mark.hidden = Some(true);
if bordered {
heading.props.borders = Some(Borders { bottom: Some(Border { space: 4.0, ..Border::single(1.5) }), ..Default::default() });
}
d.para_mut(StoryRef::Body, &Path::top(1)).unwrap().props.line_spacing = spacing;
if cell {
in_cell(&mut d);
}
let l = lay(&d);
let lines = hit::page_lines(&l.pages[0], StoryRef::Body);
let heading = lines.iter().find(|h| h.path.0.last() == Some(&0)).unwrap();
// The shared line's bottom, with the heading's bottom border under it.
let rule = l.pages[0].items.iter().filter_map(|it| match it {
Placed::Rule { y0, y1, border, .. } if y0 == y1 && border.width == 1.5 => Some(*y0),
_ => None,
});
let floor = rule.fold(heading.bottom, f32::max);
assert!(!bordered || floor > heading.bottom, "setup: the border is drawn below the shared line ({case})");
let body: Vec<_> = lines.iter().filter(|h| h.path.0.last() == Some(&1)).collect();
assert!(body.len() > 2, "setup: the body text runs to several lines ({case})");
assert!(body[0].top < heading.bottom - 1.0, "the first line at {} shares the heading's line ({case})", body[0].top);
for line in &body[1..] {
assert!(line.top >= floor - 0.01, "line {} at {} starts inside the shared line, ending {floor} ({case})", line.li, line.top);
}
}
}
+8 -3
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 = "243d68e12d05e89122db6d154924bf1992e10d38" }
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
wordcraft-geom = { workspace = true, features = ["image"] }
wordcraft-doc = { workspace = true }
wordcraft-fonts = { workspace = true }
@@ -65,13 +65,18 @@ wordcraft-engine = { workspace = true, features = ["test-support"] }
# kittest's own dev-dependencies do not propagate their font features. Declare the fonts the
# interface tests lay out explicitly: default faces plus monochrome emoji fallbacks.
egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] }
egui_kittest = { workspace = true, features = ["wgpu", "snapshot"] }
egui_kittest = { workspace = true, features = ["wgpu", "snapshot", "eframe"] }
# The app-window tests run `WordApp` as an `eframe::App` (`test_harness`), so the runtime gets the app's input before
# every pass as on the desktop. The desktop app's feature set, so a workspace build shares one eframe.
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "clipboard", "wayland", "x11", "links"] }
craft-zip = { workspace = true }
# The window tests' frame driver for child viewports; it is not part of the `craft` facade.
craft-ui-test-kit = { workspace = true }
# The interface tests' fixture and access tree (`craft::ui::testing`).
craft = { workspace = true, features = ["ui-testing"] }
[build-dependencies]
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", features = ["subset"] }
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", features = ["subset"] }
serde_json = { workspace = true }
toml = "1"
+1 -1
View File
@@ -1,3 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" height="20">
<path d="M3 6 L7 3.5 L13 3.5 L17 6 L17.5 14 L13.5 16.5 L6.5 16.5 L2.5 14 Z M6 10.5 A1.5 1.5 0 1 0 9 10.5 A1.5 1.5 0 1 0 6 10.5 Z M11 10.5 A1.5 1.5 0 1 0 14 10.5 A1.5 1.5 0 1 0 11 10.5 Z" fill="currentColor" fill-rule="evenodd"/>
<path d="M3 6 L7 3.5 L13 3.5 L17 6 L17.5 14 L13.5 16.5 L6.5 16.5 L2.5 14 Z M6 10.5 A1.5 1.5 0 1 0 9 10.5 A1.5 1.5 0 1 0 6 10.5 Z M11 10.5 A1.5 1.5 0 1 0 14 10.5 A1.5 1.5 0 1 0 11 10.5 Z" fill="#1E6FD9" class="accent" fill-rule="evenodd"/>
</svg>

Before

Width:  |  Height:  |  Size: 322 B

After

Width:  |  Height:  |  Size: 332 B

+3
View File
@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" height="20">
<path d="M3 6 L7 3.5 L13 3.5 L17 6 L17.5 14 L13.5 16.5 L6.5 16.5 L2.5 14 Z M6 10.5 A1.5 1.5 0 1 0 9 10.5 A1.5 1.5 0 1 0 6 10.5 Z M11 10.5 A1.5 1.5 0 1 0 14 10.5 A1.5 1.5 0 1 0 11 10.5 Z" fill="currentColor" fill-rule="evenodd"/>
</svg>

After

Width:  |  Height:  |  Size: 322 B

+6 -2
View File
@@ -6,6 +6,7 @@ use super::{
theme, updates_ui, window_ui, windows, zotero,
};
use craft::platform::clock::monotonic_ms;
use craft::theme::ComponentSet;
use craft::ui::runtime::commands::CommandInput;
use craft::ui::runtime::env::{AltCodePages, ResolvedRoot, RootEnv, WheelSpeed};
use craft::ui::runtime::frame::{FrameInput, FrameOutput};
@@ -101,6 +102,8 @@ impl WordApp {
command_catalog_lang: "",
key_overrides: Default::default(),
command_states: Default::default(),
command_states_cache: None,
keytip_cache: None,
fonts_frames: 0,
clipboard_published: false,
printing: Default::default(),
@@ -184,7 +187,7 @@ impl WordApp {
}
/// This frame's root values: the wheel speed, the Alt-code pages, the interface mode,
/// motion, scale and direction. Built from the saved settings every frame, so a change
/// motion, scale, direction and the component set (WordCraft takes the productivity set). Built from the saved settings every frame, so a change
/// applies at once.
pub fn root_env(&self) -> RootEnv {
let lang = i18n::Lang::from_pref(&self.ui.language);
@@ -204,7 +207,8 @@ impl WordApp {
.direction(direction)
.mode(self.ui.theme.mode())
.wheel_speed(WheelSpeed::new(line, point))
.alt_code_pages(AltCodePages::new(ansi, oem));
.alt_code_pages(AltCodePages::new(ansi, oem))
.set(ComponentSet::Productivity);
env.motion = self.ui.animations.motion();
env.sizes = std::sync::Arc::clone(&APP_SIZES);
env
+221 -19
View File
@@ -1,7 +1,7 @@
//! The app's side of the framework command runtime: the catalog of commands and their default
//! chords, the per-frame state (enabled, checked, hint) and the running of what the runtime fired.
use std::collections::HashSet;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use craft::keymap::Overrides;
@@ -52,6 +52,21 @@ const GATED_UI_COMMANDS: &[(&str, &str)] = &[
("ui.zotero.removeCodes", "Unlink Citations"),
];
/// Word feature catalog entries whose command is not yet registered in `registry`: each gets a
/// catalog entry without a chord (preventing unregistered-command warnings) and a disabled state
/// until an engine command takes its id.
fn unimplemented_catalog_commands(registry: &wordcraft_engine::Registry) -> impl Iterator<Item = (&'static str, &'static str)> + '_ {
let mut seen = HashSet::new();
wordcraft_engine::catalog::CATALOG.lines().filter_map(move |line| {
let mut parts = line.split('|');
let _tab = parts.next()?;
let _group = parts.next()?;
let feature = parts.next()?;
let id = parts.next()?;
(registry.get(id).is_none() && seen.insert(id)).then_some((id, feature))
})
}
/// The default chords of an engine command: its `shortcut`, one binding per `" / "` piece.
fn default_bindings(shortcut: &str) -> impl Iterator<Item = Binding> + '_ {
shortcut.split(" / ").filter(|piece| !piece.is_empty()).filter_map(|piece| Binding::parse(piece).ok())
@@ -68,6 +83,62 @@ fn with_word_chords(catalog: AppCatalog) -> AppCatalog {
.fold(catalog, |catalog, command| catalog.replace_defaults(command.id(), Vec::new()))
}
/// Precomputed command references, translated hints, and last gate results for
/// [`WordApp::command_input`], rebuilt when the engine registry or interface language changes.
///
/// Every command's gate predicate still runs on every frame so enabled/disabled state is never
/// stale; only the per-frame `CATALOG.lines()` parsing, `i18n` hint formatting, and full
/// `CommandStates` map rebuild are skipped when nothing changed.
pub(crate) struct CommandStatesCache {
registry: Arc<wordcraft_engine::Registry>,
lang: &'static str,
/// `(id, location, label, prebuilt CommandRef, last (enabled, reason))` for every registered
/// engine command, in registry order.
registered: Vec<(&'static str, &'static str, &'static str, CommandRef, Option<(bool, Option<&'static str>)>)>,
/// `(id, prebuilt CommandRef, last enabled)` for gated `ui.*` commands.
ui_commands: Vec<(&'static str, CommandRef, Option<bool>)>,
/// `(id, prebuilt CommandRef, last enabled)` for unimplemented Word catalog commands.
unimplemented: Vec<(&'static str, CommandRef, Option<bool>)>,
/// Precomputed `CommandRef` and last enabled state for `ui.dialog {"name": "commands"}`.
commands_dialog: (CommandRef, Option<bool>),
/// Translated fallback hint shared by all unimplemented catalog commands.
unavailable_hint: Option<Arc<str>>,
/// Cached translated hints by `(spec index, disabled reason)` for the current language.
hints: HashMap<(usize, Option<&'static str>), Option<Arc<str>>>,
}
impl CommandStatesCache {
fn new(registry: Arc<wordcraft_engine::Registry>, lang: &'static str) -> Self {
let registered = registry.all().iter().map(|spec| (spec.id, spec.location, spec.label, CommandRef::new(spec.id), None)).collect();
let ui_commands = ["ui.collapseRibbon", "ui.resetInterfaceSize", "ui.print", "ui.printSubmit"]
.into_iter()
.chain(GATED_UI_COMMANDS.iter().map(|(id, _)| *id))
.map(|id| (id, CommandRef::new(id), None))
.collect();
let unimplemented = unimplemented_catalog_commands(&registry).map(|(id, _)| (id, CommandRef::new(id), None)).collect();
let commands_dialog = (CommandRef::with_params("ui.dialog", json!({"name": "commands"})), None);
let unavailable_hint = crate::widgets::command_hint("", "", Some("")).map(Arc::from);
CommandStatesCache { registry, lang, registered, ui_commands, unimplemented, commands_dialog, unavailable_hint, hints: HashMap::new() }
}
fn matches(&self, registry: &Arc<wordcraft_engine::Registry>, lang: &'static str) -> bool {
self.lang == lang && Arc::ptr_eq(&self.registry, registry)
}
fn hint_for(&mut self, idx: usize, location: &str, label: &str, reason: Option<&'static str>) -> Option<Arc<str>> {
self.hints.entry((idx, reason)).or_insert_with(|| crate::widgets::command_hint(location, label, reason).map(Arc::from)).clone()
}
}
/// Gate check for a command known to live in `app.session.registry` (skips the extra registry lookup).
fn gate_registered(app: &WordApp, id: &str) -> (bool, Option<&'static str>) {
if !app.has_document() && !super::commands::works_without_document(id) {
return (false, None);
}
let reason = app.session.why_disabled(id);
(reason.is_none(), reason)
}
impl WordApp {
/// The app's commands as the keymap knows them: every engine command with its default
/// chords, then the interface commands. The interface commands come last because a tie in the
@@ -123,6 +194,11 @@ impl WordApp {
for (id, label) in GATED_UI_COMMANDS {
defs.push(CommandDef::new(CommandRef::new(*id), tl!(*label), Scope::app()));
}
for (id, feature) in unimplemented_catalog_commands(&registry) {
if seen.insert(id) {
defs.push(CommandDef::new(CommandRef::new(id), tl!(feature), Scope::app()));
}
}
// Word's Alt chords (Alt+Q, Alt+F7, Ctrl+Alt+1…) fire while the person types in the page:
// plain keys type, and every modified chord is offered to the keymap first.
match AppCatalog::new(defs, generation) {
@@ -157,28 +233,78 @@ impl WordApp {
if let Some(catalog) = self.catalog() {
input = input.catalog(catalog);
}
let mut states = CommandStates::new();
for spec in registry.all() {
let (enabled, reason) = gate(self, spec.id); // A toggle's checked state is bound at its ribbon button, not here.
let mut state = CommandState::new().enabled(enabled);
if let Some(hint) = crate::widgets::command_hint(spec.location, spec.label, reason) {
state = state.hint(hint);
let lang = crate::i18n::current().code();
let (mut cache, fresh_cache) = match self.command_states_cache.take() {
Some(cache) if cache.matches(&registry, lang) => (cache, false),
_ => (CommandStatesCache::new(registry, lang), true),
};
// Re-evaluate every command's gate without allocating on idle frames. A fresh cache has
// `None` in every `last` slot, so the same compare pass collects every entry for it.
let mut reg_changes: Vec<(usize, bool, Option<&'static str>)> = Vec::new();
for (i, &(id, _, _, _, last)) in cache.registered.iter().enumerate() {
let current = gate_registered(self, id);
if last != Some(current) {
reg_changes.push((i, current.0, current.1));
}
states.set(CommandRef::new(spec.id), state);
}
// Print acts on the document, so with none open it is off like the engine's commands (#1129); a command with
// no state here resolves as enabled.
let ids = ["ui.collapseRibbon", "ui.resetInterfaceSize", "ui.print", "ui.printSubmit"]
.into_iter()
.chain(GATED_UI_COMMANDS.iter().map(|(id, _)| *id));
for id in ids {
states.set(CommandRef::new(id), CommandState::new().enabled(command_enabled(self, id)));
let mut ui_changes: Vec<(usize, bool)> = Vec::new();
for (i, &(id, _, last)) in cache.ui_commands.iter().enumerate() {
let enabled = command_enabled(self, id);
if last != Some(enabled) {
ui_changes.push((i, enabled));
}
}
let commands = CommandRef::with_params("ui.dialog", json!({"name": "commands"}));
states.set(commands, CommandState::new().enabled(command_enabled(self, "ui.dialog")));
if *self.command_states != states {
self.command_states.edit(|kept| *kept = states);
let mut unimpl_changes: Vec<(usize, bool)> = Vec::new();
for (i, &(id, _, last)) in cache.unimplemented.iter().enumerate() {
let enabled = command_enabled(self, id);
if last != Some(enabled) {
unimpl_changes.push((i, enabled));
}
}
let dialog_enabled = command_enabled(self, "ui.dialog");
let dialog_changed = cache.commands_dialog.1 != Some(dialog_enabled);
let any_changed = !reg_changes.is_empty() || !ui_changes.is_empty() || !unimpl_changes.is_empty() || dialog_changed;
if fresh_cache || any_changed {
let apply = |kept: &mut CommandStates| {
for (i, enabled, reason) in reg_changes {
let (_, location, label, _, _) = cache.registered[i];
cache.registered[i].4 = Some((enabled, reason));
let mut state = CommandState::new().enabled(enabled);
if let Some(hint) = cache.hint_for(i, location, label, reason) {
state = state.hint(hint);
}
kept.set(cache.registered[i].3.clone(), state);
}
for (i, enabled) in ui_changes {
cache.ui_commands[i].2 = Some(enabled);
kept.set(cache.ui_commands[i].1.clone(), CommandState::new().enabled(enabled));
}
for (i, enabled) in unimpl_changes {
cache.unimplemented[i].2 = Some(enabled);
let mut state = CommandState::new().enabled(enabled);
if let Some(hint) = cache.unavailable_hint.as_ref() {
state = state.hint(Arc::clone(hint));
}
kept.set(cache.unimplemented[i].1.clone(), state);
}
if dialog_changed {
cache.commands_dialog.1 = Some(dialog_enabled);
kept.set(cache.commands_dialog.0.clone(), CommandState::new().enabled(dialog_enabled));
}
};
if fresh_cache {
let mut states = CommandStates::new();
apply(&mut states);
if *self.command_states != states {
self.command_states.edit(|kept| *kept = states);
}
} else {
self.command_states.edit(apply);
}
}
self.command_states_cache = Some(cache);
input.states(&self.command_states)
}
@@ -277,4 +403,80 @@ mod tests {
crate::undo_marks::apply_edits(&mut app, end, apply);
assert_eq!(app.session.undo_depth(), after_undo, "the late Commit of the taken-back gesture adds no step");
}
/// #7310: unimplemented Word feature catalog commands publish a disabled state so ribbon
/// buttons and keytips bound to them resolve disabled instead of falling back to enabled.
#[test]
fn unimplemented_catalog_commands_publish_disabled_state() {
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), Default::default());
let _ = app.command_input();
for id in ["tools.dictate", "draw.inkToMath", "review.translate", "review.blockAuthors"] {
assert!(app.session.registry.get(id).is_none(), "{id} is still an unimplemented stub");
let state = app.command_states.get(&CommandRef::new(id));
assert!(
state.is_some_and(|s| !s.is_enabled()),
"unimplemented catalog command {id} must publish an explicit disabled state, got {state:?}"
);
}
}
/// Cached `command_input()` keeps steady-state idle calls zero-change while immediately reflecting
/// table/context transitions and document-open state changes.
#[test]
fn command_input_cache_tracks_state_transitions_and_is_noop_when_idle() {
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), Default::default());
let _ = app.command_input();
let rev_after_first = app.command_states.revision();
assert!(
!app.command_states.get(&CommandRef::new("table.deleteRow")).unwrap().is_enabled(),
"table.deleteRow starts disabled outside a table"
);
assert!(app.command_states.get(&CommandRef::new("format.bold")).unwrap().is_enabled(), "format.bold starts enabled");
// Repeated idle calls must not mutate `command_states` or bump its revision.
for _ in 0..5 {
let _ = app.command_input();
}
assert_eq!(app.command_states.revision(), rev_after_first, "idle frames leave command_states revision untouched");
// Entering a table enables `table.deleteRow` immediately on the next `command_input()`.
app.run("insert.table", json!({"rows": 2, "cols": 2})).unwrap();
let _ = app.command_input();
let rev_after_table = app.command_states.revision();
assert_ne!(rev_after_table, rev_after_first, "state change bumps command_states revision");
assert!(app.command_states.get(&CommandRef::new("table.deleteRow")).unwrap().is_enabled(), "table.deleteRow is enabled inside a table");
// Closing the document disables document commands immediately.
app.no_document = Some(app.session.document_id());
let _ = app.command_input();
assert!(!app.command_states.get(&CommandRef::new("format.bold")).unwrap().is_enabled(), "format.bold disables when no document is open");
// Dropping the cache and rebuilding from scratch must produce the exact same `CommandStates`.
let incremental = (*app.command_states).clone();
app.command_states_cache = None;
let _ = app.command_input();
assert_eq!(*app.command_states, incremental, "incremental cache matches full rebuild exactly");
// Swapping the registry rebuilds `command_states` cleanly and drops commands that are no
// longer registered.
app.no_document = None;
let full_registry = app.session.registry.clone();
app.session.registry = std::sync::Arc::new(wordcraft_engine::Registry::new(vec![wordcraft_engine::CommandSpec::new(
"test.ephemeral",
"Ephemeral",
"Home",
|_, _| Ok(json!({})),
)]));
let _ = app.command_input();
assert!(
app.command_states.get(&CommandRef::new("test.ephemeral")).is_some_and(|s| s.is_enabled()),
"custom registry command is published when registered"
);
app.session.registry = full_registry;
let _ = app.command_input();
assert!(
app.command_states.get(&CommandRef::new("test.ephemeral")).is_none(),
"swapping back to the default registry clears removed commands from command_states"
);
}
}
+22 -8
View File
@@ -1,5 +1,5 @@
use craft::host::{PickId, Picked};
use craft::platform::open::{DropTarget, DroppedFile, Intake};
use craft::platform::open::{DroppedFile, Intake};
use craft::quit::{CloseAnswer, CloseGuard, CloseScope, GuardStep};
use craft::ui::dialog::{DialogId, DialogResult, UnsavedChangesDialog};
use craft::ui::shell::embed::CloseDecision;
@@ -181,6 +181,7 @@ impl WordApp {
/// Close prompt `id` from outside and drop the answer that leaves behind.
pub(crate) fn close_prompt(&mut self, id: DialogId) {
if let Some(ctx) = self.ctx.clone() {
crate::dialogs::chrome::forget_nudge(&ctx, id);
self.dialog_host.cancel_by_id(&ctx, id);
}
let _ = self.dialog_host.take_by_id::<UnsavedChangesDialog>(id);
@@ -191,6 +192,9 @@ impl WordApp {
pub(crate) fn pump_close_prompt(&mut self) {
let Some(id) = self.closing.as_ref().and_then(|c| c.prompt) else { return };
let Some(result) = self.dialog_host.take_by_id::<UnsavedChangesDialog>(id) else { return };
if let Some(ctx) = self.ctx.as_ref() {
crate::dialogs::chrome::forget_nudge(ctx, id);
}
if let Some(closing) = self.closing.as_mut() {
closing.prompt = None;
}
@@ -329,7 +333,7 @@ impl WordApp {
// A save that never reached its destination leaves no stamp of it, when the document is as
// the save left it (an edit since keeps its own marks and stays unsaved).
let mut undone = false;
if !matches!(picked, Picked::Paths(_) | Picked::Downloaded(_))
if !matches!(picked, Picked::Paths(_) | Picked::Saved { .. } | Picked::Downloaded(_))
&& save.document == current
&& save.rev == self.session.rev()
&& let Some(undo) = save.undo_stamp.take()
@@ -338,7 +342,7 @@ impl WordApp {
undone = true;
}
// A download the browser accepted is a finished save too: the page holds no file of it.
if matches!(picked, Picked::Paths(_) | Picked::Downloaded(_)) {
if matches!(picked, Picked::Paths(_) | Picked::Saved { .. } | Picked::Downloaded(_)) {
log::info!("saved {} through the save picker", save.name);
// The page now holds the document as that file (a hosted Save As or first Save, S-L159):
// the next Save goes back to it. A download names nothing the app could reopen.
@@ -381,12 +385,14 @@ impl WordApp {
}
let result = match picked {
// Only when nothing changed since and no later save of it is still unconfirmed.
Picked::Paths(_) | Picked::Downloaded(_) if !self.session.dirty && self.session.rev() == save.rev && !self.save_unconfirmed() => {
Picked::Paths(_) | Picked::Saved { .. } | Picked::Downloaded(_)
if !self.session.dirty && self.session.rev() == save.rev && !self.save_unconfirmed() =>
{
let step = self.with_guard(|g| g.saved());
self.drive_guard(step, None)
}
// Edited while the picker was open (those edits may not be written yet): ask again.
Picked::Paths(_) | Picked::Downloaded(_) => {
Picked::Paths(_) | Picked::Saved { .. } | Picked::Downloaded(_) => {
let step = self.with_guard(|g| g.retry_after_failure());
self.drive_guard(step, None)
}
@@ -632,8 +638,8 @@ impl WordApp {
let Some(intake) = self.services.intake.as_ref() else { return };
for item in intake.take() {
match item {
Intake::Dropped { files, target } => self.open_dropped(&files, target),
Intake::Open(paths) => {
Intake::Dropped { files } => self.open_dropped(&files),
Intake::Open(paths) | Intake::OpenFor { paths, .. } => {
for p in paths {
// A path that is not Unicode cannot be passed on as text: skipped.
if let Some(path) = p.to_str()
@@ -649,6 +655,14 @@ impl WordApp {
Intake::Quit => {
self.quit();
}
// An OS open request that arrived as bytes, with no path.
Intake::Bytes { name, bytes } => {
let data = wordcraft_engine::cmd::insert::base64_encode(bytes.as_ref());
if let Err(e) = self.run("file.open", json!({"path": name, "data": data})) {
self.report_open_failure(&name, &e);
}
self.ui.backstage = false;
}
}
}
}
@@ -656,7 +670,7 @@ impl WordApp {
/// Route files dropped on the window, in drop order: the one place the drop rules live. A drop
/// behind a modal dialog does nothing, since it would insert a picture or open a document
/// under it. Every drop target routes by file kind, so `_target` does not change the routing.
pub(crate) fn open_dropped(&mut self, files: &[DroppedFile], _target: DropTarget) {
pub(crate) fn open_dropped(&mut self, files: &[DroppedFile]) {
if self.modal_open() {
return;
}
+141
View File
@@ -158,4 +158,145 @@ mod tests {
let missing = missing_glyphs(&stack, &FontRef::proportional(), samples, false);
assert!(missing.is_empty(), "symbols without a glyph: {missing:#?}");
}
/// An installed Arabic font is asked for only when Arabic text needs one (and no embedded
/// Arabic face covers it): neither installing the UI font stack for English/CJK/Arabic nor
/// triggering CJK on-demand fallback ever asks for an Arabic system font, and Arabic on-demand
/// fallback never asks for a CJK system font.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn the_installed_arabic_font_is_asked_for_by_arabic_alone() {
use std::path::PathBuf;
use std::sync::Mutex;
use craft::host::Wake;
use craft::i18n::Han;
use craft::ui::fonts::{FontCandidates, on_demand_registered};
struct RecordingCandidates {
scripts: Mutex<Vec<String>>,
}
impl RecordingCandidates {
fn new() -> Arc<Self> {
Arc::new(Self { scripts: Mutex::new(Vec::new()) })
}
fn scripts(&self) -> Vec<String> {
self.scripts.lock().map(|guard| guard.clone()).unwrap_or_default()
}
}
impl FontCandidates for RecordingCandidates {
fn files(&self, script: &str, han: Option<Han>) -> Vec<PathBuf> {
if let Ok(mut scripts) = self.scripts.lock() {
scripts.push(script.to_owned());
}
SystemCandidates.files(script, han)
}
fn covers(&self, data: &[u8], c: char) -> Option<u32> {
SystemCandidates.covers(data, c)
}
fn pending(&self) -> bool {
SystemCandidates.pending()
}
fn wake_when_ready(&self, wake: Wake) {
SystemCandidates.wake_when_ready(wake);
}
}
let paint = |ctx: &egui::Context, text: &str| {
for _ in 0..6 {
ctx.run_ui(egui::RawInput::default(), |ui| {
ui.label(text);
})
.drop_without_applying_deltas();
}
};
let is_cjk_script = |script: &str| matches!(script, "Hani" | "Hira" | "Kana" | "Hang" | "Bopo");
let en = Lang::EN;
let ja = crate::i18n::fixture_lang("ja", "\tHome\tホーム\n");
let ar = crate::i18n::fixture_lang("ar", "\tHome\tالرئيسية\n");
// Installing the production `ui_fonts` stack and painting Latin text never requests or
// loads an installed Arabic or CJK system font up front.
for lang in [en, ja, ar] {
let ctx = egui::Context::default();
let spy = RecordingCandidates::new();
ui_fonts(lang).on_demand(Arc::clone(&spy) as Arc<dyn FontCandidates>).install(&ctx);
assert!(on_demand_registered(&ctx).is_empty(), "{}: installing ui_fonts reads no system font eagerly", lang.code());
assert!(spy.scripts().is_empty(), "{}: installing ui_fonts requests no system font candidates", lang.code());
paint(&ctx, "Hello");
assert!(on_demand_registered(&ctx).is_empty(), "{}: Latin UI text reads no system font", lang.code());
assert!(spy.scripts().is_empty(), "{}: Latin UI text requests no system font candidates", lang.code());
}
let embedded_arabic: Vec<String> = CRAFT_FONTS.iter().filter(|f| f.has_script("Arab")).map(EmbeddedFace::name).collect();
let ar_ctx = egui::Context::default();
let ar_stack = ui_fonts(ar).install(&ar_ctx);
let en_stack = ui_fonts(en).stack();
let ja_stack = ui_fonts(ja).stack();
if !embedded_arabic.is_empty() {
assert!(
ar_stack.chain(&FontRef::proportional()).first().is_some_and(|name| embedded_arabic.contains(name)),
"Arabic UI leads with its embedded Arabic face"
);
assert!(
!en_stack.chain(&FontRef::proportional()).first().is_some_and(|name| embedded_arabic.contains(name)),
"English UI does not lead with an Arabic face"
);
assert!(
!ja_stack.chain(&FontRef::proportional()).first().is_some_and(|name| embedded_arabic.contains(name)),
"CJK UI does not lead with an Arabic face"
);
paint(&ar_ctx, "مرحبا");
assert!(ar_ctx.fonts_mut(|f| f.has_glyph(&egui::FontId::proportional(14.0), 'ع')), "embedded Arabic face draws Arabic text");
assert!(on_demand_registered(&ar_ctx).is_empty(), "no installed Arabic system font is read when an embedded Arabic face covers Arabic");
} else {
paint(&ar_ctx, "مرحبا");
let registered = on_demand_registered(&ar_ctx);
let arabic_candidates = SystemCandidates.files("Arab", None);
assert!(!registered.is_empty() || cfg!(not(any(target_os = "macos", windows))), "macOS and Windows ship an installed Arabic font");
if !registered.is_empty() {
assert_eq!(registered.len(), 1, "Arabic text registers one installed Arabic face");
assert!(arabic_candidates.contains(&registered[0].1), "registered face {:?} came from Arabic system candidates", registered[0].1);
assert!(ar_ctx.fonts_mut(|f| f.has_glyph(&egui::FontId::proportional(14.0), 'ع')), "installed Arabic system font draws Arabic text");
}
}
// CJK on-demand lookup through `ui_fonts` never asks for an Arabic system font (U+3400 is
// CJK Extension A, outside embedded catalog subsets, so it exercises CJK on-demand lookup
// even in builds with `CRAFT_FONTS_DIR`).
let cjk_spy = RecordingCandidates::new();
let cjk_ctx = egui::Context::default();
ui_fonts(ja).on_demand(Arc::clone(&cjk_spy) as Arc<dyn FontCandidates>).install(&cjk_ctx);
paint(&cjk_ctx, "日本語 㐀");
let cjk_scripts = cjk_spy.scripts();
assert!(!cjk_scripts.iter().any(|s| s == "Arab"), "CJK fallback never asks for an Arabic font: {cjk_scripts:?}");
if !cjk_ctx.fonts_mut(|f| f.has_glyph(&egui::FontId::proportional(14.0), '\u{3400}')) || !on_demand_registered(&cjk_ctx).is_empty() {
assert!(cjk_scripts.iter().any(|s| is_cjk_script(s)), "uncovered CJK text asks for CJK candidates: {cjk_scripts:?}");
}
// Arabic on-demand lookup when no embedded Arabic face is present asks for Arabic alone
// and never triggers a CJK system-font lookup.
let ar_spy = RecordingCandidates::new();
let ar_no_embed_ctx = egui::Context::default();
if embedded_arabic.is_empty() {
ui_fonts(ar).on_demand(Arc::clone(&ar_spy) as Arc<dyn FontCandidates>).install(&ar_no_embed_ctx);
} else {
UiFonts::new(&I18nScripts)
.languages(&["en", "ja", "ar"])
.ui_language(ar.code())
.on_demand(Arc::clone(&ar_spy) as Arc<dyn FontCandidates>)
.install(&ar_no_embed_ctx);
}
paint(&ar_no_embed_ctx, "مرحبا");
let ar_scripts = ar_spy.scripts();
assert!(ar_scripts.iter().any(|s| s == "Arab"), "Arabic text without an embedded Arabic face asks for Arab: {ar_scripts:?}");
assert!(!ar_scripts.iter().any(|s| is_cjk_script(s)), "Arabic fallback never asks for a CJK font: {ar_scripts:?}");
}
}
+16 -8
View File
@@ -81,6 +81,7 @@ impl WordApp {
let mode = self.screen_mode();
let dropped = self.ribbon_dropped;
let key = self.windows.window_key();
let ribbon_out = std::cell::RefCell::new(None);
let shell = AppShell::new(key)
.mode_set(ScreenModeSet::Document)
.screen_mode(Bind::given(mode))
@@ -94,12 +95,12 @@ impl WordApp {
// tabs and collapsed every one of them.
.top(Slot::new("ribbonDrop").drops().size(SlotSize::Content), |ui, _cx, app: &mut WordApp| {
if !stale(app) {
ribbon_slot(app, ui);
*ribbon_out.borrow_mut() = Some(ribbon::show(app, ui));
}
})
.top(Slot::new("ribbon").size(SlotSize::Content), |ui, _cx, app: &mut WordApp| {
if !stale(app) {
ribbon_slot(app, ui);
*ribbon_out.borrow_mut() = Some(ribbon::show(app, ui));
}
})
// As tall as the bar: a failure's line under the message puts Install below the first line, and a slot of
@@ -132,6 +133,11 @@ impl WordApp {
self.follow_screen_mode(out.screen_mode);
}
self.ribbon_dropped = out.dropped;
// Keytips run outside the ribbon slots so legacy sequences and their hint still work when
// no ribbon shows (Focus, Full Screen View) and anchor under the slim screen bar.
let ribbon = ribbon_out.into_inner().unwrap_or_else(ribbon::no_ribbon);
let screen_bar = out.regions.slots.iter().find(|(slot, _)| *slot == "screenBar").map(|(_, rect)| *rect);
crate::keytips::show(ui, self, &ribbon, screen_bar);
out.regions
}
@@ -145,20 +151,22 @@ impl WordApp {
// PLAN: assumed `updates_ui::run(app: &mut WordApp)` (shell-w13, sh.A20) opens the updater's dialogs on the host.
updates_ui::run(self);
crate::dialogs::host::prepare(self);
let had_dialogs = !self.dialog_host.is_empty();
self.dialog_host.run(ui);
crate::dialogs::host::settle(self, ctx);
crate::dialogs::chrome::apply_modal_nudge(self, ui);
if moved(self) {
return;
}
if had_dialogs && self.dialog_host.is_empty() && !self.file_dialog_open() && !self.ui.backstage {
self.canvas.focus_page(ctx);
self.canvas.focus_pending = true;
self.canvas.focus_page_after_pass();
ctx.request_repaint();
}
self.refocus_after_chrome_click(ctx, regions);
if let Some(url) = self.canvas.open_url.take() {
ctx.open_url(egui::OpenUrl::new_tab(url));
}
}
}
/// The ribbon, then its keytips, in a top slot: the keytips read what the ribbon recorded this pass.
fn ribbon_slot(app: &mut WordApp, ui: &mut egui::Ui) {
let out = ribbon::show(app, ui);
crate::keytips::show(ui, app, &out);
}
+9 -9
View File
@@ -4,7 +4,8 @@
use craft::ui::buttons::Button;
use craft::ui::contract::{Bind, Props as _, Show as _, clicked};
use craft::ui::shell::{RecentFile, RecentList, RecentSort, RecentView, StartAction, StartLayout, StartScreen, Template};
use egui::Ui;
use craft::ui::style::DataColor;
use egui::{Color32, Ui};
use serde_json::json;
use super::{HOME_TEMPLATES, TEMPLATES, TemplateThumbs, error_line, heading, label, open_recent, thumbs};
@@ -77,7 +78,9 @@ pub(super) fn home(ui: &mut Ui, app: &mut WordApp) {
let recent = recent_files(app);
let cards = template_cards(&TEMPLATES[..HOME_TEMPLATES.min(TEMPLATES.len())]);
let store = thumbs::store(&ctx);
let source = TemplateThumbs { region: app.session.region() };
let region = app.session.region();
let (wide, high) = thumbs::page_aspect(&region);
let source = TemplateThumbs { region };
let (mut view, mut sort) = (RecentView::List, RecentSort::Opened);
let out = StartScreen::new(Bind::bound(&mut view), Bind::bound(&mut sort), &recent)
.layout(StartLayout::Greeting)
@@ -85,6 +88,9 @@ pub(super) fn home(ui: &mut Ui, app: &mut WordApp) {
.templates(&cards)
.more_templates(label("More templates →"))
.max_recent(app.ui.recent_shown())
.picture_aspect(wide, high)
.card_zoom(1.0)
.page_paper(DataColor::new(Color32::WHITE))
.thumbnails(&store, &source)
.show(ui);
run_actions(app, &ctx, out.actions);
@@ -112,12 +118,6 @@ pub(super) fn open(ui: &mut Ui, app: &mut WordApp) {
error_line(ui, &error);
}
let recent = recent_files(app);
let store = thumbs::store(&ctx);
let source = TemplateThumbs { region: app.session.region() };
let out = RecentList::new(&recent)
.max_recent(app.ui.recent_shown())
.empty(label("Documents you open will show up here."))
.thumbnails(&store, &source)
.show(ui);
let out = RecentList::new(&recent).max_recent(app.ui.recent_shown()).empty(label("Documents you open will show up here.")).show(ui);
run_actions(app, &ctx, out.actions);
}
+20 -9
View File
@@ -12,12 +12,13 @@ use craft::ui::contract::{
use craft::ui::layout_components::Stack;
use craft::ui::list::ThumbAspect;
use craft::ui::notices::Notice;
use craft::ui::primitives::IconSpec;
use craft::ui::primitives::{ContentPainterCx, IconSpec};
use craft::ui::runtime::env::Label;
use craft::ui::shell::{Template, ThumbKey};
use craft::ui::style::DataColor;
use craft::ui::text::TextField;
use craft::ui::tile_grid::{CaptionPlace, Tile, TileGrid};
use egui::Ui;
use egui::{Color32, Rect, Shape, Ui, vec2};
use serde_json::json;
use super::home::template_cards;
@@ -30,13 +31,13 @@ const PAGE_WIDE: u16 = 3;
const PAGE_HIGH: u16 = 4;
/// A grid of template tiles, one per card, that reports the chosen key.
fn grid(name: Label) -> TileGrid<'static, String> {
fn grid(name: Label, wide: u16, high: u16) -> TileGrid<'static, String> {
TileGrid::<String>::new(name)
.select(SelectMode::Single)
.activate(ActivateOn::Click)
.caption(CaptionPlace::Below)
.card()
.aspect(f32::from(PAGE_WIDE) / f32::from(PAGE_HIGH))
.aspect(f32::from(wide) / f32::from(high))
.sizing(Sizing::FillWidth)
.natural_height(true)
}
@@ -58,6 +59,14 @@ fn read_listing(app: &WordApp) -> PersonalListing {
PersonalListing { key, folder, templates }
}
/// Paints a personal template card thumbnail: a white page surface with a centered 44×44 pt
/// `documentTemplate` icon (#7373).
pub(super) fn paint_personal_card(cx: &ContentPainterCx, rect: Rect) {
cx.data_shapes([Shape::rect_filled(rect, 2.0, Color32::WHITE)]);
let icon_rect = Rect::from_center_size(rect.center(), vec2(44.0, 44.0));
cx.icon(icon_rect, &IconSpec::svg(IconId::new("documentTemplate")).data_color(DataColor::new(Color32::from_gray(150))));
}
/// New: the whole template gallery with a search box, then the personal templates (#2852); no
/// Recent list (that is on Home and Open). The search covers both.
///
@@ -87,16 +96,18 @@ pub(super) fn show(ui: &mut Ui, app: &mut WordApp) {
return;
}
let store = thumbs::store(&ctx);
let source = thumbs::TemplateThumbs { region: app.session.region() };
let region = app.session.region();
let (wide, high) = thumbs::page_aspect(&region);
let source = thumbs::TemplateThumbs { region };
if !found.is_empty() {
let (store, source) = (&store, &source);
let cards = template_cards(&found);
let items = keyed(&cards, |t: &Template| t.id.clone()).with_text(|t| Cow::Borrowed(t.name.as_str()));
let out = grid(label("Templates")).show_items(ui, &items, &mut |id, _| {
let out = grid(label("Templates"), wide, high).show_items(ui, &items, &mut |id, _| {
let Some(card) = cards.iter().find(|c| &c.id == id) else { return Tile::new(Label::Empty) };
let thumb = ThumbKey::Template(card.id.clone());
Tile::new(Label::from(card.name.clone()))
.thumb(ThumbAspect::new(PAGE_WIDE, PAGE_HIGH), move |cx, rect| thumbs::paint(cx, rect, store, source, &thumb))
.thumb(ThumbAspect::new(wide, high), move |cx, rect| thumbs::paint(cx, rect, store, source, &thumb))
});
for id in activated(out.response.events) {
let _ = app.run("file.new", json!({"template": id}));
@@ -131,9 +142,9 @@ pub(super) fn show(ui: &mut Ui, app: &mut WordApp) {
let tiles: Vec<&PersonalTemplate> = personal_found.iter().filter(|p| p.category == category).collect();
let items = keyed(&tiles, |p: &&PersonalTemplate| p.path.clone()).with_text(|p| Cow::Borrowed(p.label.as_str()));
let name = if category.is_empty() { label("Personal templates") } else { Label::from(category.to_owned()) };
let out = grid(name).id_salt(("personal-templates", category.to_owned())).show_items(ui, &items, &mut |path, _| {
let out = grid(name, PAGE_WIDE, PAGE_HIGH).id_salt(("personal-templates", category.to_owned())).show_items(ui, &items, &mut |path, _| {
let Some(p) = tiles.iter().find(|p| &p.path == path) else { return Tile::new(Label::Empty) };
Tile::new(Label::from(p.label.clone())).icon(IconSpec::svg(IconId::new("documentTemplate"))).tooltip(p.path.clone())
Tile::new(Label::from(p.label.clone())).thumb(ThumbAspect::new(PAGE_WIDE, PAGE_HIGH), paint_personal_card).tooltip(p.path.clone())
});
for path in activated(out.response.events) {
let failed = open_personal(app, &path, &ctx).err();
+52
View File
@@ -353,6 +353,21 @@ fn new_lists_personal_templates_and_opens_one() {
let _ = std::fs::remove_dir_all(&dir);
}
/// #7373: Personal template cards in File › New paint a white page surface and document icon.
#[test]
fn personal_template_cards_render_as_page_cards() {
let dir = personal_dir("card-paint");
let memo = dir.join("Proposal.dotx");
write_template(&memo, "Proposal template text");
let h = new_page_harness(Some(dir.clone()));
let card = h.query_by_label("Proposal");
assert!(card.is_some(), "personal template tile exists");
let rect = card.unwrap().rect();
assert!(rect.height() > rect.width(), "personal template card is portrait oriented");
drop(h);
let _ = std::fs::remove_dir_all(&dir);
}
/// An empty (or not yet made) templates folder says where templates come from; no folder (the
/// web) shows no Personal section. Home keeps only the built-ins.
#[test]
@@ -840,3 +855,40 @@ fn a_file_pages_title_is_productions_size() {
assert!(title.size > section.size + 6.0, "the title stands above a section heading: {title:?} over {section:?}");
}
}
/// The template cards on File › Home and File › New use the portrait aspect of the active region,
/// and Home cards use card_zoom(1.0) so they do not stretch across the row (#7372, #7149 items 2-3).
#[test]
fn backstage_template_cards_aspect_and_zoom() {
let mut letter_app = new_app();
letter_app.session.system_region = wordcraft_geom::Region::from_tag("en-US");
let (wide_us, high_us) = super::thumbs::page_aspect(&letter_app.session.region());
assert_eq!((wide_us, high_us), (17, 22), "US region uses 17:22 (Letter) aspect");
let mut a4_app = new_app();
a4_app.session.system_region = wordcraft_geom::Region::from_tag("en-GB");
let (wide_gb, high_gb) = super::thumbs::page_aspect(&a4_app.session.region());
assert_eq!((wide_gb, high_gb), (70, 99), "GB region uses 70:99 (A4) aspect");
// Home template cards: portrait and narrow (~150 pt wide, not stretched across the row)
let h = file_page(new_app(), "home");
let card = h.get_by_label("Blank document").rect();
assert!(card.height() > card.width(), "Home template card is portrait: {card:?}");
assert!(card.width() < 300.0, "card zoom keeps cards narrow instead of filling row: {card:?}");
}
/// File › Open presents the recent list without thumbnail letterboxing (#7372).
#[test]
fn file_open_recent_list_has_no_thumbnail_letterboxing() {
let app = new_app();
let h = file_page(app, "open");
assert!(h.query_by_label("Browse…").is_some(), "Browse button exists");
assert!(h.query_all_by_label("Recent").next().is_some(), "Recent section exists");
assert!(h.query_by_label("Documents you open will show up here.").is_some(), "empty state message exists");
let mut populated = new_app();
populated.ui.recent = vec!["/tmp/sample.docx".into()];
let h2 = file_page(populated, "open");
let row = recent_row(&h2, "sample.docx").expect("recent row renders");
assert!(row.rect().height() > 0.0, "recent row has non-zero height: {:?}", row.rect());
}
+11 -3
View File
@@ -1,11 +1,18 @@
//! The template thumbnails of the File page: the first page of each built-in template, drawn in a
//! throwaway session so the user's document is never touched.
use craft::ui::primitives::{ContentPainterCx, Priority, Revision, ThumbPaint, ThumbRender, ThumbRequest, ThumbSource, ThumbnailOptions, Thumbnails};
use craft::ui::primitives::{
ContentPainterCx, Priority, Revision, ThumbFit, ThumbPaint, ThumbRender, ThumbRequest, ThumbSource, ThumbnailOptions, Thumbnails,
};
use craft::ui::shell::ThumbKey;
use craft::ui::style::{Corners, SurfaceKind};
use craft::ui::style::{Corners, DataColor, SurfaceKind};
use serde_json::json;
/// The shape of a document page in `region`, wide to high (Letter 17:22 or A4 70:99).
pub(crate) fn page_aspect(region: &wordcraft_geom::Region) -> (u16, u16) {
if region.uses_letter() { (17, 22) } else { (70, 99) }
}
/// The salt every reader of the File page's thumbnails asks the store with, so New, Home and the
/// recent rows share one loader and one set of pictures.
const SALT: &str = "wordcraft.templates";
@@ -20,7 +27,8 @@ pub(crate) fn store(ctx: &egui::Context) -> Thumbnails<ThumbKey> {
pub(crate) fn paint(cx: &ContentPainterCx, rect: egui::Rect, store: &Thumbnails<ThumbKey>, source: &dyn ThumbSource<ThumbKey>, key: &ThumbKey) {
let request = ThumbRequest::for_cell(rect.width().max(rect.height()), cx.pixels_per_point());
let state = store.state(cx.painter.ctx(), source, key, &request, Priority::VISIBLE);
if !store.paint(cx, rect, &state, &ThumbPaint::default()) {
let paint = ThumbPaint::default().fit(ThumbFit::Cover).checker(false).paper(DataColor::new(egui::Color32::WHITE));
if !store.paint(cx, rect, &state, &paint) {
cx.surface(rect, SurfaceKind::Sunken, Corners::None);
}
}
+38 -11
View File
@@ -12,7 +12,7 @@ use std::sync::Arc;
use craft::behavior::kurbo::{Point, Size};
use craft::pages::layout::{Fit, LayoutOptions, PageDisplay, SCREEN_POINTS_PER_POINT};
use craft::pages::ui::reading::{ReadingMetrics, reading_size};
use craft::pages::ui::{MarkArea, MarkKind, PageBody, PageView, PageViewState, PlacedPage, ReadingNav, ReadingState, ReadingView, TextMarks};
use craft::pages::ui::{GoTo, MarkArea, MarkKind, PageBody, PageView, PageViewState, PlacedPage, ReadingNav, ReadingState, ReadingView, TextMarks};
use craft::ui::canvas::{Autoscroll, ContextSource, MiddleButton, NavigationOptions, ToolHost, ToolHostResponse, ToolPass, WheelScheme};
use craft::ui::contract::Show as _;
@@ -156,6 +156,10 @@ pub struct CanvasState {
pub(crate) read_force_reflow: bool,
/// Web Layout's width follows the window once a drag has settled, not on every frame of it.
web_viewport: reading::Settle,
/// Side gutter the last `PageView` pass laid pages out with (`PageSpacing::side`), in screen points.
pub(crate) page_side: Option<f32>,
/// `PageView`'s side gutter changed since the last Web Layout pass, so Web Layout must reflow at once.
web_force_reflow: bool,
/// First text position on the column currently leading the reading view, captured from the last
/// pass's layout. Survives changing page sizes, even when the caret stays elsewhere.
pub(crate) read_first_visible: Option<Pos>,
@@ -371,7 +375,7 @@ impl CanvasState {
/// The comment whose balloon is selected, as the document's comment id.
pub fn selected_balloon(&self) -> Option<u32> {
self.comments.selected.and_then(|id| u32::try_from(id.0).ok())
self.comments.selected.lead.and_then(|id| u32::try_from(id.0).ok())
}
}
@@ -405,6 +409,8 @@ impl Default for CanvasState {
nav_to_caret: false,
read_force_reflow: false,
web_viewport: Default::default(),
page_side: None,
web_force_reflow: false,
read_first_visible: None,
dragging: false,
column_drag: None,
@@ -465,16 +471,19 @@ fn update_viewport(app: &mut WordApp, full: Rect, metrics: &ReadingMetrics, side
// Without an anchor (Read Mode was just entered) the view starts at the caret.
app.canvas.scroll_to_caret |= reflow_anchor.is_none();
}
app.canvas.web_force_reflow = false;
} else {
if app.session.view.mode == wordcraft_layout::ViewMode::Web {
// Web Layout wraps to the work area (#1876).
let scale = app.session.view.zoom.clamp(0.1, 5.0) * PX_PER_PT;
// The page view keeps its side gutter (the rail width) clear on both sides of a page, so the page
// The page view keeps its side gutter (`PageSpacing::side`) clear on both sides of a page, so the page
// fits the window only when its width leaves that room.
let w = web_layout_width((full.width() - 2.0 * side).max(0.0), scale);
let changed = (app.session.view.web_width - w).abs() > 0.5;
// At once on entry or a zoom (the viewport holds still), after a window drag has settled.
if app.canvas.web_viewport.apply(full.size(), ctx.input(|i| i.time), changed, false) {
let forced = std::mem::take(&mut app.canvas.web_force_reflow);
// At once on entry, a zoom, or a page-spacing change (the viewport holds still), after a window drag
// has settled.
if app.canvas.web_viewport.apply(full.size(), ctx.input(|i| i.time), changed, forced) {
app.session.view.web_width = w;
// The pixel offset no longer points at the same text: keep the caret's line in view.
app.canvas.scroll_to_caret = true;
@@ -483,6 +492,7 @@ fn update_viewport(app: &mut WordApp, full: Rect, metrics: &ReadingMetrics, side
}
} else {
app.canvas.web_viewport.leave();
app.canvas.web_force_reflow = false;
}
app.canvas.read_force_reflow = false;
app.canvas.read_first_visible = None;
@@ -609,7 +619,7 @@ fn mark_areas(app: &mut WordApp, layout: &DocLayout, selected: &[(usize, wordcra
fn navigation_options() -> NavigationOptions {
let mut options = NavigationOptions::default();
options.middle_button =
if cfg!(any(target_os = "macos", target_os = "ios", target_arch = "wasm32")) { MiddleButton::Pan } else { MiddleButton::Autoscroll };
if cfg!(any(target_os = "macos", target_os = "ios", target_arch = "wasm32")) { MiddleButton::Pan } else { MiddleButton::AutoScroll };
options.wheel = WheelScheme::Document;
options
}
@@ -732,7 +742,8 @@ fn show_reading(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: R
pub fn show(app: &mut WordApp, ui: &mut Ui) {
let full = ui.available_rect_before_wrap();
let Some(metrics) = reading_metrics::read(ui) else { return };
let layout = prepare_layout(app, full, &metrics, Env::of(ui).tokens.size.rail.width, ui.ctx());
let side = app.canvas.page_side.unwrap_or(0.0);
let layout = prepare_layout(app, full, &metrics, side, ui.ctx());
if app.session.view.read_mode {
show_reading(app, ui, &layout, full, &metrics);
} else {
@@ -754,7 +765,7 @@ fn show_pages(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: Rec
if let Some(c) = c
&& let Some(page) = layout.pages.get(c.page)
{
state.go_to = Some((c.page, f64::from(c.top / page.h.max(1.0))));
state.go_to = Some(GoTo::Top { page: c.page, fraction: f64::from(c.top / page.h.max(1.0)) });
state.current = c.page;
}
}
@@ -864,13 +875,27 @@ fn show_pages(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: Rec
} else {
screen_rects(&selected, body.pages)
};
app.canvas.mini_anchor = crate::mini_toolbar::visible_anchor(anchor_rects, body.view.rect);
app.canvas.mini_anchor = crate::mini_toolbar::visible_anchor(anchor_rects, body.view.rect, crate::mini_toolbar::starts_rtl(app));
// The bar is its own floating layer: shown after the host, it keeps its buttons' presses (S-L410).
crate::mini_toolbar::show(app, ui, body);
}
});
let caret = caret_after.or(caret);
app.canvas.page_keys = source.into_keys();
let side = out.spacing.side as f32;
if side.is_finite() {
let side = side.max(0.0);
if app.canvas.page_side.is_none_or(|prev| (prev - side).abs() > 0.01) {
app.canvas.page_side = Some(side);
if app.session.view.mode == wordcraft_layout::ViewMode::Web {
app.canvas.web_force_reflow = true;
ui.ctx().request_discard("page view side gutter changed");
if !ui.ctx().will_discard() {
ui.ctx().request_repaint();
}
}
}
}
// This pass's own input changed the document under the pages it drew: run the pass again, so the frame that
// delivers a key paints its text (production laid out and painted in the one pass) rather than the next frame.
if ran && !Arc::ptr_eq(&laid_before, &app.session.layout()) {
@@ -908,7 +933,7 @@ fn show_pages(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: Rec
ui.ctx().request_repaint();
}
if let Some(go) = fix.go_to {
state.go_to = Some(go);
state.go_to = Some(GoTo::Top { page: go.0, fraction: go.1 });
ui.ctx().request_repaint();
}
// Dragging a selection past the view's edge scrolls on.
@@ -920,7 +945,9 @@ fn show_pages(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: Rec
let per_unit = v.zoom.max(f64::EPSILON);
let size = Size::new(out.layout.size.width / per_unit, out.layout.size.height / per_unit);
if Autoscroll::scroll(&mut v, step, size).is_some() {
out.adopt(&mut state, &v);
// The view moved in document units; the state keeps screen points.
state.offset.0 += (v.center.x - view.center.x) * view.zoom;
state.offset.1 += (v.center.y - view.center.y) * view.zoom;
ui.ctx().request_repaint();
}
}
+8 -6
View File
@@ -3,7 +3,7 @@
//! and its drafts are `CanvasState::comments`, the one copy the Comments pane shares.
use craft::review::ui::{BalloonItem, BalloonPlace, CommentBalloons, CommentEdit};
use craft::review::{CommentAnchor, CommentMessage, CommentThread, ReviewStatus, Revision, RevisionKind, ThreadId};
use craft::review::{CommentAnchor, CommentMessage, CommentThread, Revision, RevisionKind, ThreadId};
use super::geometry::{FLOAT_WIDTH, floating_comments, markup_width, shown_comment};
use super::{Color32, CommentDisplay, DocLayout, Env, Pos, Pos2, StoryRef, Ui, WordApp, json};
@@ -68,7 +68,8 @@ pub(crate) fn balloons(app: &mut WordApp, ui: &mut Ui, out: &craft::pages::ui::P
/// Applies what a card reported through the commands the Comments pane uses.
fn apply(app: &mut WordApp, cards: &[Card], edit: CommentEdit) {
match edit {
CommentEdit::Select(thread) => {
CommentEdit::Select(threads) => {
let Some(thread) = threads.first().copied() else { return };
let Some(id) = app_id(thread) else { return };
focus_balloon(app, id);
let pos = cards.iter().find_map(|c| match &c.what {
@@ -149,7 +150,7 @@ fn thread_of(app: &WordApp, id: u32, page: usize, anchor: Pos2, color: Color32)
let c = app.session.doc.comments.get(&cid)?;
let created = c.date_utc.as_deref().map(unix_seconds).filter(|t| *t > 0).unwrap_or_else(|| unix_seconds(&c.date));
let text = app.session.doc.plain_text(StoryRef::Part(c.part)).trim().to_string();
Some(CommentMessage { author: author_name(&c.author), created, modified: None, text, reactions: Vec::new(), read: true })
Some(CommentMessage { author: author_name(&c.author), created, modified: None, text, reactions: Vec::new(), read: true, deletable: true })
})
.collect();
Some(CommentThread {
@@ -158,7 +159,8 @@ fn thread_of(app: &WordApp, id: u32, page: usize, anchor: Pos2, color: Color32)
kind: None,
color: Some([color.r(), color.g(), color.b()]),
messages,
status: ReviewStatus::None,
statuses: Vec::new(),
reply_statuses: Vec::new(),
marked: false,
locked: false,
resolved: root.resolved,
@@ -253,7 +255,7 @@ fn focus_balloon(app: &mut WordApp, id: u32) {
let text = app.session.doc.comments.get(&id).filter(|_| editable).map(|c| app.session.doc.plain_text(StoryRef::Part(c.part)));
let thread = thread_id(id);
let comments = &mut app.canvas.comments;
comments.selected = Some(thread);
comments.selected = craft::behavior::Selection::single(thread);
if comments.editing.as_ref().is_none_or(|(t, ..)| *t != thread) {
comments.editing = text.map(|t| (thread, 0, t));
}
@@ -275,5 +277,5 @@ pub fn deselect_balloon(app: &mut WordApp) {
// What was written is cleared by the write; a draft the document refused (read-only protection) stays, with its
// reason on the status line, for when the balloon is selected again or the document is saved or closed (#1348).
write_back(app, id);
app.canvas.comments.selected = None;
app.canvas.comments.selected = craft::behavior::Selection::default();
}
+3 -7
View File
@@ -8,7 +8,7 @@ use craft::behavior::{Input, Metrics};
use craft::pages::ui::{PageBody, PlacedPage};
use craft::ui::canvas::ToolPass;
use craft::ui::contract::{Access, Common, Component, Cx, MeasureCx, NoValue, Outcome, PaintUi, Props as _, Role, Show as _};
use craft::ui::fonts::{FaceBytes, MAX_INTERFACE_FACE_BYTES};
use craft::ui::fonts::FaceBytes;
use craft::ui::primitives::{FaceRun, PaintShape, StrokeWidth, TextRun};
use craft::ui::runtime::env::Label;
use craft::ui::style::{ComponentStyle, DataColor, StyleColor, StyleCx};
@@ -293,14 +293,10 @@ pub(crate) fn face_key(face: wordcraft_fonts::FaceRef) -> String {
format!("wordcraft-face:{}", face.id())
}
/// The bytes, index and variation setting of `face`, read the first time it is drawn. A file larger than the framework
/// draws over the interface fonts is not copied: the composition stays in the interface font (a document's CJK
/// fallback can be 19 MB).
/// The bytes, index and variation setting of `face`, read the first time it is drawn. The framework's document-face
/// registry keeps the faces within its byte budget.
fn face_bytes(face: wordcraft_fonts::FaceRef) -> Option<FaceBytes> {
let data = face.data();
if data.len() > MAX_INTERFACE_FACE_BYTES {
return None;
}
Some(FaceBytes::new(std::sync::Arc::from(data), face.index()).coords(face.coords.iter().copied()))
}
+35 -18
View File
@@ -253,6 +253,24 @@ fn drawing_over_the_pages_follows_the_read_mode_page_color() {
assert_eq!(blank(&a), Rgb::WHITE, "the paper under the raster, not the page color");
}
/// #299: the caret's colour is worked out only when the caret is drawn: with text selected
/// there is no caret, so the page's draw list isn't built for it.
#[test]
fn caret_colour_is_not_worked_out_while_the_caret_is_hidden() {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("Hello WordCraft")), Default::default());
a.run("select.text", json!({"text": "Hello"})).unwrap();
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
a,
);
h.run_steps(4);
assert!(h.state().canvas.caret_bg.is_none(), "no caret, no colour lookup");
}
/// Show revisions in balloons: a document whose only revision is a deletion gets the markup
/// area for its balloon; the other modes have nothing to show there, and neither does the view
/// while the Comments pane is open.
@@ -427,20 +445,20 @@ fn selection_bar_clicks_select_lines() {
page_to_screen(h.state_mut(), c.page, 30.0, c.top + c.height * (li + 0.5)).expect("on screen")
};
let line_start = |h: &mut H, at: Pos2| {
let placed = *h.state().canvas.shown.pages.iter().find(|p| p.rect.contains(at)).expect("page");
let placed = h.state().canvas.shown.pages.iter().find(|p| p.rect.contains(at)).expect("page").clone();
let p = placed.to_page(at);
let layout = h.state_mut().session.layout();
layout.selection_bar_at(placed.page, p.x as f32, p.y as f32).expect("in the selection bar")
};
let span = |h: &mut H, pos: &Pos| h.state_mut().session.layout().line_span(pos, 0).expect("line");
let button = |at: Pos2, pressed: bool| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() };
let clicks_drag = |h: &mut H, from: Pos2, to: Pos2, clicks: usize| {
let button = |at: Pos2, pressed: bool, modifiers: Modifiers| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers };
let clicks_drag = |h: &mut H, from: Pos2, to: Pos2, clicks: usize, mods: Modifiers| {
h.event(Event::PointerMoved(from));
for i in 0..clicks {
h.event(button(from, true));
h.event(button(from, true, mods));
h.app_frame();
if i + 1 < clicks {
h.event(button(from, false));
h.event(button(from, false, mods));
h.app_frame();
}
}
@@ -448,7 +466,7 @@ fn selection_bar_clicks_select_lines() {
h.event(Event::PointerMoved(from + (to - from) * (k as f32 / 4.0)));
h.app_frame();
}
h.event(button(to, false));
h.event(button(to, false, mods));
for _ in 0..3 {
h.app_frame();
}
@@ -462,22 +480,22 @@ fn selection_bar_clicks_select_lines() {
let at = margin(&mut h, Pos::body(0, 0), 1.0);
let l2 = line_start(&mut h, at);
assert!(l2.off > 0 && l2.path == wordcraft_doc::Path::top(0));
clicks_drag(&mut h, at, at, 1);
clicks_drag(&mut h, at, at, 1, Modifiers::NONE);
let (_, l2_end, _) = span(&mut h, &l2);
assert_eq!(h.state().session.sel.ordered(), (l2.clone(), l2_end.clone()), "the line");
// Double-click: the paragraph, mark included.
pause(&mut h);
clicks_drag(&mut h, at, at, 2);
clicks_drag(&mut h, at, at, 2, Modifiers::NONE);
assert_eq!(h.state().session.sel.ordered(), (Pos::body(0, 0), Pos::body(1, 0)), "the paragraph");
// Triple-click: the whole document.
pause(&mut h);
clicks_drag(&mut h, at, at, 3);
clicks_drag(&mut h, at, at, 3, Modifiers::NONE);
assert_eq!(h.state().session.sel.ordered(), (Pos::body(0, 0), Pos::body(2, 10)), "everything");
// Drag from beside the first line down past the third: three whole lines.
pause(&mut h);
let (from, to) = (margin(&mut h, Pos::body(0, 0), 0.0), margin(&mut h, Pos::body(0, 0), 2.0));
let l3 = line_start(&mut h, to);
clicks_drag(&mut h, from, to, 1);
clicks_drag(&mut h, from, to, 1, Modifiers::NONE);
let (_, l3_end, _) = span(&mut h, &l3);
let sel = h.state().session.sel.clone();
assert_eq!((sel.anchor, sel.focus), (Pos::body(0, 0), l3_end), "three lines");
@@ -486,7 +504,7 @@ fn selection_bar_clicks_select_lines() {
let second = margin(&mut h, Pos::body(1, 0), 0.0);
h.event(Event::ModifiersChanged(Modifiers::SHIFT));
h.app_frame();
clicks_drag(&mut h, second, second, 1);
clicks_drag(&mut h, second, second, 1, Modifiers::SHIFT);
h.event(Event::ModifiersChanged(Modifiers::default()));
h.app_frame();
let sel = h.state().session.sel.clone();
@@ -1227,15 +1245,14 @@ fn a_cjk_composition_uses_the_cjk_ui_font() {
assert_eq!(row.glyphs.len(), 3, "one glyph per composed kana");
let family = composition_font(&drawn).map(|f| f.family).expect("a font");
assert_eq!(family, egui::FontFamily::Name(format!("face+ui:{}", super::caret::face_key(run.requested_face)).into()), "in the text's face");
let (chain, interface) = h.ctx.fonts(|f| {
let families = &f.definitions().families;
(families.get(&family).cloned().unwrap_or_default(), families.get(&egui::FontFamily::Proportional).cloned().unwrap_or_default())
});
// The framework serves the face with the interface fonts behind it; what the face lacks is drawn from them, so each
// kana has a full-width glyph (a missing one would be a narrow box or nothing).
let size = composition_font(&drawn).map(|f| f.size).expect("a size");
assert!(
!interface.is_empty() && interface.iter().all(|f| chain.contains(f)),
"the face's chain goes on with the interface fonts: {chain:?} {interface:?}"
row.glyphs.iter().all(|g| g.advance_width >= size * 0.8),
"the kana come from the interface fonts: {:?}",
row.glyphs.iter().map(|g| g.advance_width).collect::<Vec<_>>()
);
assert_eq!(chain.len(), interface.len() + 1, "and no other document face is borrowed: {chain:?}");
}
/// The composition is drawn in the font and size of the text it goes into, as Word draws it, its
+1 -1
View File
@@ -259,7 +259,7 @@ fn comment_harness() -> (H, u32) {
/// Click comment `id`'s balloon (from no selected balloon): the card is selected and its own
/// edit has the keyboard in its field.
fn click_balloon(h: &mut H, id: u32) {
h.state_mut().canvas.comments.selected = None;
h.state_mut().canvas.comments.selected = craft::behavior::Selection::default();
steps(h, 2);
let card = h.state().canvas.balloon_rects.iter().find(|(i, _)| *i == id).map(|(_, r)| *r).expect("the comment has a balloon");
click_at(h, card.left_top() + vec2(30.0, 8.0));
@@ -260,6 +260,19 @@ fn table_gridlines_skip_edges_a_border_draws() {
);
}
/// #5967: a new table has borders on every edge, so it shows no gridline at all; with its
/// borders removed every edge shows one.
#[test]
fn a_bordered_table_shows_no_gridlines() {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
a.run("insert.table", json!({"rows": 2, "cols": 3})).unwrap();
assert!(a.session.view.table_gridlines, "View Gridlines is on by default");
let segs = |a: &mut WordApp| gridline_segments(&a.session.layout().pages[0], true, None).len();
assert_eq!(segs(&mut a), 0);
a.run("table.borders", json!({"kind": "none"})).unwrap();
assert_eq!(segs(&mut a), 6 * 4, "every edge of the six cells");
}
/// The drawing grid the page shows starts at the text area's top left, stays inside it, spaces
/// its lines by the settings the same both ways or differently across and down, and falls back
/// to the spec's 1/8 inch for a missing spacing.
+3 -4
View File
@@ -3,7 +3,6 @@
use craft::behavior::IconId;
use craft::ui::buttons::IconButton;
use craft::ui::contract::{BodyCx, Props as _, Show as _, TooltipSpec};
use craft::ui::runtime::inspect;
use egui::Ui;
use serde_json::json;
@@ -11,9 +10,9 @@ use super::Screen;
use crate::WordApp;
/// Fills the screen-bar slot. Focus: a `more` button that drops the ribbon down over the page. Immersive: the
/// command search field. The bar is an inspected region, where the keytips hang their hint while no ribbon shows.
/// command search field.
pub(crate) fn show(ui: &mut Ui, _cx: &mut BodyCx<'_>, app: &mut WordApp) {
inspect::record(ui, crate::keytips::screen_bar_region(), |ui| match Screen::of(&app.session.view) {
match Screen::of(&app.session.view) {
Screen::Focus => {
let out = IconButton::new(IconId::new("wordcraft.more"))
.label(tl!("Show the ribbon").to_string())
@@ -27,5 +26,5 @@ pub(crate) fn show(ui: &mut Ui, _cx: &mut BodyCx<'_>, app: &mut WordApp) {
_ => {
super::search::show(app, ui, false);
}
});
}
}
+6 -3
View File
@@ -4,9 +4,9 @@ use craft::behavior::IconId;
use craft::keymap::CommandRef;
use craft::ui::buttons::IconButton;
use craft::ui::contract::{Bind, Props as _, Show as _, TooltipSpec};
use craft::ui::menu::HelpEntry;
use craft::ui::menu::search::{HelpEntry, SearchIndex, SearchWords, Synonyms};
use craft::ui::patterns::panels::{CommandPalette, PaletteFace};
use craft::ui::runtime::env::{Label, WordTemplate};
use craft::ui::runtime::env::{Env, Label, WordTemplate};
use craft::ui::runtime::inspect;
use egui::Ui;
use serde_json::json;
@@ -64,7 +64,10 @@ pub(super) fn show(app: &mut WordApp, ui: &mut Ui, compact: bool) -> egui::Rect
}
rect = Some(button.response.rect);
}
let out = CommandPalette::new(name.clone(), &entries, Bind::bound(&mut open))
let env = Env::of(ui);
let view = env.view();
let index = SearchIndex::new(&view, &entries, &Synonyms::of(&view.words::<SearchWords>()));
let out = CommandPalette::new(name.clone(), &entries, &index, Bind::bound(&mut open))
.face(if compact { PaletteFace::Dialog } else { PaletteFace::InPlace })
.placeholder(Label::from(name.clone()))
.suggested((Label::from(tl!("Suggested").to_string()), suggested))
+89 -80
View File
@@ -5,11 +5,13 @@ use std::cell::RefCell;
use craft::behavior::IconId;
use craft::keymap::CommandRef;
use craft::theme::ControlSize;
use craft::theme::variant::Variant;
use craft::ui::bars::{Bar, BarKind};
use craft::ui::buttons::{Button, ButtonOutput, IconButton, ToggleButton};
use craft::ui::contract::{Bind, BodyCx, Props as _, Show as _, ShowContainer as _, TooltipSpec, Trigger};
use craft::ui::contract::{Bind, BodyCx, Gap, Props as _, Show as _, ShowContainer as _, TooltipSpec, Trigger};
use craft::ui::display::{Divider, Text};
use craft::ui::layout_components::Row;
use craft::ui::menu::{Menu, MenuItem};
use craft::ui::value_drag::{Slider, SliderScale};
use egui::Ui;
@@ -209,85 +211,92 @@ fn missing_fonts(app: &mut WordApp, ui: &mut Ui) {
fn controls(app: &mut WordApp, ui: &mut Ui, fit: usize) -> Option<egui::Rect> {
use craft::ui::contract::Outcome as _;
let mut rects = Vec::new();
let focus = if fit >= 2 {
IconButton::command(IconId::new("focus"), CommandRef::new("view.focus")).label(tl!("Focus").to_string()).show(ui).response
} else {
Button::command(CommandRef::new("view.focus"))
.label(tl!("Focus").to_string())
.icon(IconId::new("focus"))
.variant(Variant::GHOST)
.show(ui)
.response
};
rects.push(focus.rect);
// Icons only, Read Mode first and Web Layout last, each named in its tooltip, the current view on (prod
// `chrome.rs:925-943`).
let (mode, read) = (app.session.view.mode, app.session.view.read_mode);
for (id, icon, name, on) in [
("view.readMode", "readMode", tl!("Read Mode"), read),
("view.printLayout", "printLayout", tl!("Print Layout"), mode == wordcraft_layout::ViewMode::Print && !read),
("view.webLayout", "webLayout", tl!("Web Layout"), mode == wordcraft_layout::ViewMode::Web),
] {
// No command carries a checked state, so the view is given at the button (S-L415).
let out = ToggleButton::new(name.to_string(), Bind::given(on))
.command(CommandRef::new(id))
.icon(crate::icons::id(icon))
.icon_only()
.tooltip(TooltipSpec::new(name.to_string()))
.show(ui);
rects.push(out.response().rect);
}
let reading = app.session.view.read_mode;
// Reading zoom changes only reading presentation, never the normal view zoom.
let current = if reading { f64::from(app.session.view.read_zoom) } else { app.canvas.zoom() };
let percent = (current * 100.0).round();
let step = |app: &mut WordApp, plus: bool| {
if reading {
let value = if plus { (percent + 10.0).min(150.0) } else { (percent - 10.0).max(75.0) };
let _ = app.run("view.readTextSize", json!({"value": value}));
let _ = Row::new().gap(Gap::Section).show(ui, |ui, _| {
let focus = if fit >= 2 {
IconButton::command(IconId::new("focus"), CommandRef::new("view.focus")).label(tl!("Focus").to_string()).show(ui).response
} else {
let _ = app.run(if plus { "view.zoomIn" } else { "view.zoomOut" }, json!({}));
}
};
let out = IconButton::new(IconId::new("wordcraft.minus"))
.label(tl!("Zoom Out").to_string())
.tooltip(TooltipSpec::new(tl!("Zoom Out").to_string()))
.show(ui);
rects.push(out.response.rect);
if out.response.clicked() {
step(app, false);
}
if fit < 1 {
let mut value = current;
let range = if reading { 0.75..=1.5 } else { 0.1..=5.0 };
let name = if reading { tl!("Text Size") } else { tl!("Zoom") };
let slider = Slider::new(Bind::bound(&mut value), range)
.scale(if reading { SliderScale::Linear } else { SliderScale::Log })
// A plain rail, as the old zoom slider's (prod `chrome.rs:911`): no fill up to the thumb.
.fill(false)
.label(name.to_string())
.show(ui);
rects.push(slider.response().rect);
if let Some(v) = slider.value() {
let command = if reading { "view.readTextSize" } else { "view.zoom" };
let _ = app.run(command, json!({"value": (*v * 100.0).round()}));
}
}
let out = IconButton::new(IconId::new("wordcraft.plus"))
.label(tl!("Zoom In").to_string())
.tooltip(TooltipSpec::new(tl!("Zoom In").to_string()))
.show(ui);
rects.push(out.response.rect);
if out.response.clicked() {
step(app, true);
}
if !reading {
// PLAN: assumed Button::room_for (ribbon-w2, S-L418)
let out = Button::new(format!("{percent}%")).variant(Variant::GHOST).room_for(format!("{MOST_ZOOM_PERCENT}%")).show(ui);
rects.push(out.response.rect);
if out.clicked() {
let _ = app.run("ui.dialog", json!({"name": "zoom"}));
}
}
Button::command(CommandRef::new("view.focus"))
.label(tl!("Focus").to_string())
.icon(IconId::new("focus"))
.variant(Variant::GHOST)
.show(ui)
.response
};
rects.push(focus.rect);
// Icons only, Read Mode first and Web Layout last, each named in its tooltip, the current view on (prod
// `chrome.rs:925-943`).
let _ = Row::new().gap(Gap::Item).show(ui, |ui, _| {
let (mode, read) = (app.session.view.mode, app.session.view.read_mode);
for (id, icon, name, on) in [
("view.readMode", "readMode", tl!("Read Mode"), read),
("view.printLayout", "printLayout", tl!("Print Layout"), mode == wordcraft_layout::ViewMode::Print && !read),
("view.webLayout", "webLayout", tl!("Web Layout"), mode == wordcraft_layout::ViewMode::Web),
] {
// No command carries a checked state, so the view is given at the button (S-L415).
let out = ToggleButton::new(name.to_string(), Bind::given(on))
.command(CommandRef::new(id))
.icon(crate::icons::id(icon))
.icon_only()
.tooltip(TooltipSpec::new(name.to_string()))
.show(ui);
rects.push(out.response().rect);
}
});
let reading = app.session.view.read_mode;
// Reading zoom changes only reading presentation, never the normal view zoom.
let current = if reading { f64::from(app.session.view.read_zoom) } else { app.canvas.zoom() };
let percent = (current * 100.0).round();
let step = |app: &mut WordApp, plus: bool| {
if reading {
let value = if plus { (percent + 10.0).min(150.0) } else { (percent - 10.0).max(75.0) };
let _ = app.run("view.readTextSize", json!({"value": value}));
} else {
let _ = app.run(if plus { "view.zoomIn" } else { "view.zoomOut" }, json!({}));
}
};
let _ = Row::new().show(ui, |ui, _| {
let out = IconButton::new(IconId::new("wordcraft.minus"))
.label(tl!("Zoom Out").to_string())
.tooltip(TooltipSpec::new(tl!("Zoom Out").to_string()))
.show(ui);
rects.push(out.response.rect);
if out.response.clicked() {
step(app, false);
}
if fit < 1 {
let mut value = current;
let range = if reading { 0.75..=1.5 } else { 0.1..=5.0 };
let name = if reading { tl!("Text Size") } else { tl!("Zoom") };
let slider = Slider::new(Bind::bound(&mut value), range)
.size(ControlSize::Md)
.scale(if reading { SliderScale::Linear } else { SliderScale::Log })
// A plain rail, as the old zoom slider's (prod `chrome.rs:911`): no fill up to the thumb.
.fill(false)
.label(name.to_string())
.show(ui);
rects.push(slider.response().rect);
if let Some(v) = slider.value() {
let command = if reading { "view.readTextSize" } else { "view.zoom" };
let _ = app.run(command, json!({"value": (*v * 100.0).round()}));
}
}
let out = IconButton::new(IconId::new("wordcraft.plus"))
.label(tl!("Zoom In").to_string())
.tooltip(TooltipSpec::new(tl!("Zoom In").to_string()))
.show(ui);
rects.push(out.response.rect);
if out.response.clicked() {
step(app, true);
}
if !reading {
// PLAN: assumed Button::room_for (ribbon-w2, S-L418)
let out = Button::new(format!("{percent}%")).variant(Variant::GHOST).room_for(format!("{MOST_ZOOM_PERCENT}%")).show(ui);
rects.push(out.response.rect);
if out.clicked() {
let _ = app.run("ui.dialog", json!({"name": "zoom"}));
}
}
});
});
super::union(rects)
}
+320
View File
@@ -76,6 +76,34 @@ fn new_app() -> WordApp {
WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), crate::Services::default())
}
/// A saved .docx (so AutoSave can cover it) in the harness.
fn autosave_harness() -> (egui_kittest::Harness<'static, WordApp>, std::path::PathBuf) {
let dir = std::env::temp_dir().join(format!("wordcraft-ui-autosave-label-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("draft.docx");
let mut a = new_app();
a.run("text.insert", json!({"text": "Hello"})).unwrap();
a.run("file.save", json!({"path": path.to_string_lossy()})).unwrap();
assert!(a.autosaves(), "a saved .docx is covered by AutoSave");
let h = harness(a);
(h, dir)
}
/// #3370: clicking the AutoSave switch label toggles AutoSave on and off.
#[test]
fn clicking_the_autosave_label_toggles_autosave() {
let (mut h, dir) = autosave_harness();
assert!(h.state().autosaves());
h.get_by_label("AutoSave").click();
crate::test_harness::frames(&mut h, 2);
assert!(!h.state().autosaves(), "clicking the text turns AutoSave off");
h.get_by_label("AutoSave").click();
crate::test_harness::frames(&mut h, 2);
assert!(h.state().autosaves(), "and clicking it again turns it back on");
let _ = std::fs::remove_dir_all(&dir);
}
/// #701: the arrow beside Undo lists the session's undo steps, newest first; clicking the third
/// row undoes three steps at once.
#[test]
@@ -103,6 +131,39 @@ fn undo_list_matches_the_session_and_undoes_up_to_the_clicked_row() {
assert_eq!(h.query_all_by_role(Role::ListBoxOption).count(), 0, "the list closes");
}
/// #3040: clicking a row in the Undo History popover undoes the step and returns keyboard focus
/// to the document so typing continues immediately.
#[test]
fn undo_list_row_returns_focus_to_the_document() {
use egui::accesskit::Role;
let mut a = new_app();
a.run("text.insert", json!({"text": "Hello"})).unwrap();
assert_eq!(a.session.undo_history().len(), 1);
let mut h = harness(a);
assert!(h.state().canvas.focused(&h.ctx), "canvas starts focused");
let arrow = h.get_by_label("Undo History").rect().center();
click_at(&mut h, arrow, egui::PointerButton::Primary);
assert_eq!(h.query_all_by_role(Role::ListBoxOption).count(), 1, "the arrow opens the Undo list");
assert!(!h.state().canvas.focused(&h.ctx), "the open Undo list holds the keyboard");
let row = h.get_by_role_and_label(Role::ListBoxOption, "Typing").rect().center();
click_at(&mut h, row, egui::PointerButton::Primary);
assert_eq!(h.query_all_by_role(Role::ListBoxOption).count(), 0, "picking a row closes the Undo list");
assert!(h.state().session.undo_history().is_empty(), "the step was undone");
assert_eq!(h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body), "", "the undone text is gone");
assert!(h.state().canvas.focused(&h.ctx), "the row click returns focus to the document");
h.event(egui::Event::Text("!".into()));
crate::test_harness::frames(&mut h, 2);
assert_eq!(
h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body),
"!",
"typing reaches the document immediately after picking an Undo list row"
);
}
/// #1975: the zoom percentage gains and loses digits (9% → 100% → 500%); the controls to its
/// left must not shift with it.
#[test]
@@ -437,6 +498,96 @@ fn status_bar_texts_stop_before_the_controls_in_a_narrow_window() {
assert!(painted_on_row_of(&wide, focus).iter().any(|(t, _)| t == "Track Changes: On"), "a wide window shows everything");
}
/// Finds the painted track and knob rects inside a rendered `craft::ui::choice::Switch`.
/// `Switch` sets `PARTS = false` and exposes only its `Role::Switch` node and toggled state, so
/// the thumb position is read from the unblurred filled shapes painted inside the switch rect.
fn switch_track_and_knob(shapes: &[egui::epaint::ClippedShape], switch_rect: egui::Rect) -> (egui::Rect, egui::Rect) {
fn filled_rects(shape: &egui::Shape, inside: egui::Rect, out: &mut Vec<egui::Rect>) {
match shape {
egui::Shape::Vec(children) => children.iter().for_each(|c| filled_rects(c, inside, out)),
egui::Shape::Rect(r) if r.blur_width == 0.0 && r.fill != egui::Color32::TRANSPARENT && inside.contains_rect(r.rect) => {
out.push(r.rect);
}
_ => {}
}
}
let mut rects = Vec::new();
for clipped in shapes {
filled_rects(&clipped.shape, switch_rect.expand(1.0), &mut rects);
}
let track = rects
.iter()
.copied()
.filter(|r| r.width() > r.height())
.max_by(|a, b| a.area().total_cmp(&b.area()))
.unwrap_or_else(|| panic!("expected painted switch track inside {switch_rect:?}: {rects:?}"));
let knob = rects
.iter()
.copied()
.filter(|r| track.contains_rect(*r) && r.width() < track.width())
.max_by(|a, b| a.area().total_cmp(&b.area()))
.unwrap_or_else(|| panic!("expected painted switch knob inside track {track:?}: {rects:?}"));
(track, knob)
}
/// The AutoSave switch renders its knob on the right when on and on the left when off in a
/// left-to-right interface, and mirrors through `WordApp::root_env()` for an Arabic interface.
#[test]
fn the_autosave_knob_sits_right_when_on_and_mirrors_right_to_left() {
use craft::i18n::Direction;
use egui::accesskit::{Role, Toggled};
struct ResetLang;
impl Drop for ResetLang {
fn drop(&mut self) {
crate::i18n::apply_language(crate::i18n::Lang::EN);
}
}
let _reset = ResetLang;
let mut a = new_app();
a.ui.animations = crate::theme::Animations::Off;
a.ui.language = "en".into();
// Mark the document as saved here without touching disk (`session.dirty` stays false).
let path = std::path::PathBuf::from("draft.docx");
a.session.path = Some(path.clone());
a.autosave_path = Some(path);
let mut h = harness(a);
// Arabic UI labels draw even when built without `CRAFT_FONTS_DIR` (embedded Arabic faces).
h.ctx.set_missing_glyph_policy(egui::MissingGlyphPolicy::Tofu);
let mut measure = |lang: crate::i18n::Lang, on: bool| -> (egui::Rect, egui::Rect) {
h.state_mut().run("ui.language", json!({"value": lang.code()})).unwrap();
h.state_mut().run("file.autosave", json!({"value": on})).unwrap();
let want_dir = if lang.rtl() { Direction::Rtl } else { Direction::Ltr };
assert_eq!(h.state().root_env().direction, want_dir, "root_env supplies direction for {}", lang.code());
assert_eq!(h.state().autosaves(), on);
crate::test_harness::frames(&mut h, 4);
let label = crate::i18n::tr(lang, "AutoSave");
let node = h.get_by_role_and_label(Role::Switch, label);
assert_eq!(node.accesskit_node().toggled(), Some(if on { Toggled::True } else { Toggled::False }));
switch_track_and_knob(&h.output().shapes, node.rect())
};
let (ltr_on_track, ltr_on_knob) = measure(crate::i18n::Lang::EN, true);
let (ltr_off_track, ltr_off_knob) = measure(crate::i18n::Lang::EN, false);
assert!(ltr_on_knob.center().x > ltr_on_track.center().x, "left to right, on: knob sits right ({ltr_on_knob:?} in {ltr_on_track:?})");
assert!(ltr_off_knob.center().x < ltr_off_track.center().x, "left to right, off: knob sits left ({ltr_off_knob:?} in {ltr_off_track:?})");
let Some(ar) = crate::i18n::Lang::from_code("ar") else {
eprintln!("skipped RTL check: built without the craft-i18n Arabic catalog (set CRAFT_I18N_DIR to a checkout)");
return;
};
let (rtl_on_track, rtl_on_knob) = measure(ar, true);
let (rtl_off_track, rtl_off_knob) = measure(ar, false);
assert!(rtl_on_knob.center().x < rtl_on_track.center().x, "right to left, on: knob sits left ({rtl_on_knob:?} in {rtl_on_track:?})");
assert!(rtl_off_knob.center().x > rtl_off_track.center().x, "right to left, off: knob sits right ({rtl_off_knob:?} in {rtl_off_track:?})");
assert!(rtl_on_track.center().x > ltr_on_track.center().x, "right to left mirrors the AutoSave switch toward the start (right) edge");
assert!(((ltr_on_knob.center().x - ltr_on_track.min.x) - (rtl_on_track.max.x - rtl_on_knob.center().x)).abs() <= 0.5);
assert!(((ltr_off_knob.center().x - ltr_off_track.min.x) - (rtl_off_track.max.x - rtl_off_knob.center().x)).abs() <= 0.5);
}
/// #7311: the title bar's Discord community button keeps its solid accent fill and contrasting
/// `on_strong` icon/label in both wide (pill with label) and narrow (compact icon-only) windows,
/// across Light and Dark themes, and still dispatches `ui.discord` when clicked.
@@ -550,3 +701,172 @@ fn title_bar_discord_button_keeps_accent_fill_and_icon_contrast_in_wide_and_narr
}
}
}
/// #7445: the title bar's Discord community button uses the dedicated single-ink `discordPill` icon
/// with `on_strong` contrast over the solid accent pill, while the ribbon's Review › Help › Community
/// Discord button retains the branded `discord` icon with `class="accent"` ink.
#[test]
fn discord_icons_distinguish_title_bar_pill_and_ribbon_accent() {
use egui::accesskit::Role;
fn to_color32(rgba: craft::theme::Rgba) -> egui::Color32 {
egui::Color32::from(craft::theme::Srgba::from(rgba))
}
fn collect_shapes<'a>(shapes: &'a [egui::epaint::ClippedShape], out: &mut Vec<&'a egui::Shape>) {
for clipped in shapes {
fn walk<'a>(shape: &'a egui::Shape, out: &mut Vec<&'a egui::Shape>) {
match shape {
egui::Shape::Vec(children) => {
for child in children {
walk(child, out);
}
}
other => out.push(other),
}
}
walk(&clipped.shape, out);
}
}
for theme in ["light", "dark"] {
let mut a = new_app();
a.ui.show_discord = true;
a.ui.language = "en".into();
a.run("ui.theme", json!({"value": theme})).unwrap();
a.run("ui.tab", json!({"tab": "Help"})).unwrap();
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 700.0)).build_ui_state(app_frame, a);
crate::test_harness::frames(&mut h, 6);
let env = craft::ui::runtime::env::Env::of_root(&h.ctx);
let on_strong = to_color32(env.tokens.color.text.on_strong);
let accent_solid = to_color32(env.tokens.color.accent.solid);
let mut shapes = Vec::new();
collect_shapes(&h.output().shapes, &mut shapes);
// 1. Title-bar button uses discordPill icon (single-ink text.on_strong).
let title_bar_node = h.get_by_role_and_label(Role::Button, "Discord");
let title_bar_rect = title_bar_node.rect();
assert!(title_bar_rect.is_positive(), "{theme}: Title-bar Discord button must be laid out");
let title_bar_icon_on_strong = shapes.iter().any(|s| match s {
egui::Shape::Mesh(mesh) => {
let bounds = mesh.calc_bounds();
title_bar_rect.expand(1.5).contains_rect(bounds) && !mesh.vertices.is_empty() && mesh.vertices.iter().all(|v| v.color == on_strong)
}
_ => false,
});
assert!(title_bar_icon_on_strong, "{theme}: Title-bar Discord icon inside {title_bar_rect:?} must paint in text.on_strong ({on_strong:?})");
// 2. Ribbon Help › Community Discord button uses discord icon with class="accent".
let ribbon_node = h
.query_all_by_role(Role::Button)
.find(|n| n.accesskit_node().label().is_some_and(|l| l.contains("Discord")) && n.rect() != title_bar_rect)
.expect("Ribbon Community Discord button");
let ribbon_rect = ribbon_node.rect();
assert!(ribbon_rect.is_positive(), "{theme}: Ribbon Community Discord button must be laid out");
let ribbon_icon_accent = shapes.iter().any(|s| match s {
egui::Shape::Mesh(mesh) => {
let bounds = mesh.calc_bounds();
ribbon_rect.expand(1.5).contains_rect(bounds) && !mesh.vertices.is_empty() && mesh.vertices.iter().all(|v| v.color == accent_solid)
}
_ => false,
});
assert!(ribbon_icon_accent, "{theme}: Ribbon Community Discord icon inside {ribbon_rect:?} must paint in accent.solid ({accent_solid:?})");
}
}
/// #7319: view mode toggle buttons (Read Mode, Print Layout, Web Layout) in the status bar are grouped
/// with `Gap::Item` intra-group spacing, separated from Focus and Zoom controls via `Gap::Section`.
/// The Zoom slider has size `ControlSize::Md`, giving its thumb a 14 pt grab affordance matching sibling `IconButton`s.
#[test]
fn status_bar_view_mode_toggles_and_zoom_slider_proportions() {
use egui::accesskit::Role;
let h = harness(new_app());
let focus = h.get_by_role_and_label(Role::Button, "Focus").rect();
let read_mode = h.get_by_role_and_label(Role::Button, "Read Mode").rect();
let print_layout = h.get_by_role_and_label(Role::Button, "Print Layout").rect();
let web_layout = h.get_by_role_and_label(Role::Button, "Web Layout").rect();
let zoom_out = h.get_by_role_and_label(Role::Button, "Zoom Out").rect();
let slider = h.get_by_role_and_label(Role::Slider, "Zoom").rect();
let zoom_in = h.get_by_role_and_label(Role::Button, "Zoom In").rect();
let env = craft::ui::runtime::env::Env::of_root(&h.ctx);
let gap_section = env.tokens.space.gap.section;
let gap_item = env.tokens.space.gap.item;
let gap_row = env.tokens.space.gap.row;
let glyph_md = env.tokens.size.icon.glyph_md;
// 1. Spacing and grouping:
// Focus -> View modes group gap is Gap::Section.
let focus_to_views_gap = read_mode.min.x - focus.max.x;
assert!(
(focus_to_views_gap - gap_section).abs() <= 0.5,
"Focus and Read Mode should be separated by Gap::Section ({gap_section} pt), got {focus_to_views_gap}"
);
// Intra-group spacing between view mode toggle buttons is Gap::Item.
let read_to_print_gap = print_layout.min.x - read_mode.max.x;
let print_to_web_gap = web_layout.min.x - print_layout.max.x;
assert!(
(read_to_print_gap - gap_item).abs() <= 0.5,
"Read Mode and Print Layout intra-group spacing should be Gap::Item ({gap_item} pt), got {read_to_print_gap}"
);
assert!(
(print_to_web_gap - gap_item).abs() <= 0.5,
"Print Layout and Web Layout intra-group spacing should be Gap::Item ({gap_item} pt), got {print_to_web_gap}"
);
// View modes group -> Zoom controls group gap is Gap::Section.
let views_to_zoom_gap = zoom_out.min.x - web_layout.max.x;
assert!(
(views_to_zoom_gap - gap_section).abs() <= 0.5,
"Web Layout and Zoom Out should be separated by Gap::Section ({gap_section} pt), got {views_to_zoom_gap}"
);
// Zoom controls intra-group spacing is default row gap (Gap::Row).
let zoom_out_to_slider_gap = slider.min.x - zoom_out.max.x;
let slider_to_zoom_in_gap = zoom_in.min.x - slider.max.x;
assert!(
(zoom_out_to_slider_gap - gap_row).abs() <= 0.5,
"Zoom Out and Zoom Slider intra-group spacing should be Gap::Row ({gap_row} pt), got {zoom_out_to_slider_gap}"
);
assert!(
(slider_to_zoom_in_gap - gap_row).abs() <= 0.5,
"Zoom Slider and Zoom In intra-group spacing should be Gap::Row ({gap_row} pt), got {slider_to_zoom_in_gap}"
);
// 2. Zoom slider thumb proportions:
// Slider thumb is rendered as a round knob sized at glyph_md (14 pt) for ControlSize::Md.
fn collect_shapes<'a>(shapes: &'a [egui::epaint::ClippedShape], out: &mut Vec<&'a egui::Shape>) {
for clipped in shapes {
fn walk<'a>(shape: &'a egui::Shape, out: &mut Vec<&'a egui::Shape>) {
match shape {
egui::Shape::Vec(children) => {
for child in children {
walk(child, out);
}
}
other => out.push(other),
}
}
walk(&clipped.shape, out);
}
}
let mut shapes = Vec::new();
collect_shapes(&h.output().shapes, &mut shapes);
let has_14pt_knob = shapes.iter().any(|s| match s {
egui::Shape::Rect(r) => {
let rect = r.rect;
slider.expand(2.0).contains_rect(rect) && (rect.width() - glyph_md).abs() <= 0.5 && (rect.height() - glyph_md).abs() <= 0.5
}
_ => false,
});
assert!(has_14pt_knob, "Zoom slider should paint a {glyph_md} pt thumb (ControlSize::Md) matching 14 pt IconButton icons inside {slider:?}");
}
+7 -2
View File
@@ -200,6 +200,11 @@ fn undo_arrow(app: &mut WordApp, ui: &mut Ui, enabled: bool) -> egui::Rect {
app.chrome.undo_mark = if open { mark } else { UndoMark::default() };
if let Some(count) = picked {
let _ = app.run("edit.undoTo", json!({"count": count}));
// Picking a row closes the Undo History popover on its foreground layer; return keyboard
// focus to the document both now and after the pass's overlay-close focus hook (#3040).
app.canvas.focus_page(ui.ctx());
app.canvas.focus_page_after_pass();
ui.ctx().request_repaint();
}
out.response.rect
}
@@ -256,7 +261,7 @@ fn trailing(app: &mut WordApp, ui: &mut Ui, step: usize) -> Option<egui::Rect> {
if app.ui.show_discord {
let tip = TooltipSpec::new(tl!("Join the ArtCraft community on Discord").to_string());
let clicked = if step >= 1 {
let out = IconButton::new(IconId::new("discord"))
let out = IconButton::new(IconId::new("discordPill"))
.label(tl!("Discord").to_string())
.variant(Variant::Custom(DISCORD_ICON))
.glyphs(GlyphRole::Tool)
@@ -266,7 +271,7 @@ fn trailing(app: &mut WordApp, ui: &mut Ui, step: usize) -> Option<egui::Rect> {
out.response.clicked()
} else {
let out =
Button::new(tl!("Discord").to_string()).icon(IconId::new("discord")).variant(Variant::Custom(DISCORD_PILL)).tooltip(tip).show(ui);
Button::new(tl!("Discord").to_string()).icon(IconId::new("discordPill")).variant(Variant::Custom(DISCORD_PILL)).tooltip(tip).show(ui);
rects.push(out.response.rect);
out.clicked()
};
+3 -3
View File
@@ -13,7 +13,7 @@ use craft::color_ui::ui::{ColorPickerDialog, ColorPickerDialogLayout, ColorPicke
use craft::keymap::CommandRef;
use craft::theme::Srgba;
use craft::ui::buttons::{SplitButton, SplitMenu};
use craft::ui::choice::SwatchTable;
use craft::ui::choice::{CellMarks, SwatchTable};
use craft::ui::contract::{BodyCx, Hover, NoValue, Props as _, Show as _, clicked};
use craft::ui::dialog::{DialogId, DialogResult};
use craft::ui::menu::{MenuItem, MenuItemOutput};
@@ -307,7 +307,7 @@ fn swatch_table(
let out = SwatchTable::new(name.to_string(), &swatches)
.per_row(per_row)
.tips(true)
.marked(|i: &usize| colors.get(*i).copied() == current && current.is_some())
.marks(|i: &usize| CellMarks::default().edge(colors.get(*i).copied() == current && current.is_some()))
.show_all(ui);
let picked = out.selected.and_then(|i| colors.get(i).copied());
let preview = match out.preview {
@@ -490,7 +490,7 @@ fn highlight_body(ui: &mut Ui, app: &mut WordApp, cx: &mut BodyCx<'_>) -> ColorP
let out = SwatchTable::new("Highlight Colors".to_string(), &swatches)
.per_row(5)
.tips(true)
.marked(|i: &usize| shown.get(*i).is_some_and(|(h, _)| h.ooxml() == in_effect))
.marks(|i: &usize| CellMarks::default().edge(shown.get(*i).is_some_and(|(h, _)| h.ooxml() == in_effect)))
.show_all(ui);
let mut picked = None;
if let Some((h, c)) = out.selected.and_then(|i| shown.get(i)) {
+1 -1
View File
@@ -9,7 +9,7 @@
//! control library
//! - `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?}`: PNG of the window; `ui.render {path?, page?, scale?}`: page PNG
//! - `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`)
//! - `ui.resize`, `ui.focus`, `ui.closeWindow`, `ui.clipboard`, `ui.replayAt`, `ui.accessTree`
//! - `ui.parity`: feature catalog parity
+7 -4
View File
@@ -376,10 +376,13 @@ fn handle_request(app: &mut WordApp, ctx: &egui::Context, req: &ControlRequest)
"ui.inspect" => ok(inspect(app, ctx)),
"ui.parity" => ok(wordcraft_engine::catalog::parity(&app.session.registry)),
"ui.clickText" => click_text(app, ctx, p),
"ui.screenshot" => {
let token = app.next_capture_token();
Reply::screenshot(token, s("path").map(str::to_string), app.active_viewport())
}
"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())
}
Err(e) => err(e),
},
"ui.render" => {
let page = p.get("page").and_then(Value::as_u64).unwrap_or(1);
let scale = p.get("scale").and_then(Value::as_f64).map_or(2.0, |v| v as f32);
+6 -2
View File
@@ -307,7 +307,8 @@ fn control_keyboard_reaches_the_background_document_once() {
assert_eq!(body_text(h.state()), "Seed", "one Undo reverses the one text input");
}
/// Control text and keys target the focused widget of a dialog, not the document, and Escape closes it.
/// Control text and keys target the focused widget of a dialog, not the document. The Find dialog is modeless, so the
/// first Escape reverts the field's typing and the second closes the dialog.
#[test]
fn control_keyboard_keeps_the_background_widget_target() {
let mut a = app();
@@ -325,7 +326,10 @@ fn control_keyboard_keeps_the_background_widget_target() {
assert_eq!(body_text(h.state()), "Seed", "the Find field, not the document, owns the input");
send(&mut h, "ui.key", json!({"key": "Escape"}));
frames(&mut h, 6);
assert_eq!(open(&mut h), 0, "Escape closes the dialog");
assert!(open(&mut h) > 0, "the first Escape reverts the field and leaves the dialog open");
send(&mut h, "ui.key", json!({"key": "Escape"}));
frames(&mut h, 6);
assert_eq!(open(&mut h), 0, "the second Escape closes the dialog");
assert_eq!(body_text(h.state()), "Seed");
}
+143 -15
View File
@@ -66,22 +66,59 @@ pub fn credits() -> Credits {
}
/// The About tab's contents: name, blurb, version and build, and the project links in the old About's order (site,
/// Discord, source), one to a line.
/// Discord, source), one to a line. A Nightly window names its channel, its exact feed version
/// and commit, and offers a link to report a problem.
pub fn about_info() -> AboutInfo {
let build = option_env!("WORDCRAFT_BUILD_SHA").map(|s| s.get(..8).unwrap_or(s)).unwrap_or(tl!("development build"));
// The dialog's own "Version {version}" words the line, so this is the number and the build only.
let version = crate::i18n::fmt(tl!("{version} ({build})"), &[("version", env!("CARGO_PKG_VERSION")), ("build", build)]);
AboutInfo::new(
tl!("WordCraft").to_string(),
tl!("A free, open-source word processor written from scratch in Rust.\nPart of the Crafting Apps from the ArtCraft team.").to_string(),
version.to_string(),
)
.links([
AboutLink::new(tl!("getartcraft.com/apps/wordcraft").to_string(), "https://getartcraft.com/apps/wordcraft"),
AboutLink::new(tl!("Join us on Discord: discord.gg/artcraft").to_string(), "https://discord.gg/artcraft"),
AboutLink::new(tl!("Source code: github.com/storytold/wordcraft").to_string(), "https://github.com/storytold/wordcraft"),
])
.built_with(tl!("MIT OR Apache-2.0. Copyright (c) 2026 ArtCraft Team and the WordCraft contributors.").to_string())
about_info_for(crate::os_window::identity(), option_env!("WORDCRAFT_BUILD_SHA"))
}
/// The About tab's three lines for `identity`: (name, blurb, version line). A Nightly window's
/// are English only: they are not one of the stable catalogs' strings.
fn about_text(identity: crate::os_window::LaunchIdentity, commit: Option<&str>) -> (String, String, String) {
match identity {
crate::os_window::LaunchIdentity::NightlyV1 => {
let version = option_env!("WORDCRAFT_VERSION").unwrap_or(env!("CARGO_PKG_VERSION"));
let commit = commit.filter(|value| !value.is_empty()).unwrap_or("unavailable");
(
crate::os_window::name_for(identity).to_string(),
"A free, open-source word processor written from scratch in Rust.\nPart of the Crafting Apps from the ArtCraft team.".to_string(),
format!("{version}\nCommit: {commit}"),
)
}
crate::os_window::LaunchIdentity::Stable => {
let build = commit.map(|s| s.get(..8).unwrap_or(s)).unwrap_or(tl!("development build"));
// The dialog's own "Version {version}" words the line, so this is the number and the build only.
let version = crate::i18n::fmt(tl!("{version} ({build})"), &[("version", env!("CARGO_PKG_VERSION")), ("build", build)]);
(
tl!("WordCraft").to_string(),
tl!("A free, open-source word processor written from scratch in Rust.\nPart of the Crafting Apps from the ArtCraft team.")
.to_string(),
version.to_string(),
)
}
}
}
fn about_info_for(identity: crate::os_window::LaunchIdentity, commit: Option<&str>) -> AboutInfo {
let (name, blurb, version) = about_text(identity, commit);
if identity == crate::os_window::LaunchIdentity::NightlyV1 {
return AboutInfo::new(name, blurb, version)
.links([
AboutLink::new("getartcraft.com/apps/wordcraft".to_string(), "https://getartcraft.com/apps/wordcraft"),
AboutLink::new("Join us on Discord: discord.gg/artcraft".to_string(), "https://discord.gg/artcraft"),
AboutLink::new("Source code: github.com/storytold/wordcraft".to_string(), "https://github.com/storytold/wordcraft"),
// Opens only after a click; nothing is collected or sent automatically.
AboutLink::new("Report a problem".to_string(), "https://github.com/storytold/wordcraft/issues"),
])
.built_with("MIT OR Apache-2.0. Copyright (c) 2026 ArtCraft Team and the WordCraft contributors.".to_string());
}
AboutInfo::new(name, blurb, version)
.links([
AboutLink::new(tl!("getartcraft.com/apps/wordcraft").to_string(), "https://getartcraft.com/apps/wordcraft"),
AboutLink::new(tl!("Join us on Discord: discord.gg/artcraft").to_string(), "https://discord.gg/artcraft"),
AboutLink::new(tl!("Source code: github.com/storytold/wordcraft").to_string(), "https://github.com/storytold/wordcraft"),
])
.built_with(tl!("MIT OR Apache-2.0. Copyright (c) 2026 ArtCraft Team and the WordCraft contributors.").to_string())
}
/// The About dialog opened on `tab`, with the Language data tab after Models (`AboutTab::App(0)`). The name
@@ -90,3 +127,94 @@ pub(crate) fn about(tab: AboutTab) -> HostedAbout {
// PLAN: assumed `HostedAbout::layout(self, AboutLayout) -> Self` (look-dialogs-b framework fix)
HostedAbout::new(about_info(), credits()).app_tab(language_data_tab()).tab(tab).layout(AboutLayout::Listed)
}
/// A Nightly window's About names its channel, keeps the full feed version and commit, invents
/// nothing when the commit is missing, and adds the report link the stable About does not have.
#[cfg(test)]
mod nightly_about_tests {
use crate::os_window::LaunchIdentity;
const COMMIT: &str = "0123456789abcdef0123456789abcdef01234567";
#[test]
fn nightly_about_names_the_channel_and_keeps_the_full_version_and_commit() {
let (name, blurb, version) = super::about_text(LaunchIdentity::NightlyV1, Some(COMMIT));
assert_eq!(name, "WordCraft Nightly");
assert!(blurb.contains("word processor"));
let package = option_env!("WORDCRAFT_VERSION").unwrap_or(env!("CARGO_PKG_VERSION"));
assert_eq!(version, format!("{package}\nCommit: {COMMIT}"));
}
#[test]
fn nightly_about_invents_no_provenance_when_the_commit_is_missing() {
for commit in [None, Some("")] {
let (_, _, version) = super::about_text(LaunchIdentity::NightlyV1, commit);
assert!(version.ends_with("\nCommit: unavailable"), "{version}");
}
}
#[test]
fn only_the_nightly_about_offers_the_report_link_and_the_stable_name_is_unchanged() {
let nightly = super::about_info_for(LaunchIdentity::NightlyV1, Some(COMMIT));
assert!(nightly.links.iter().any(|link| link.url == "https://github.com/storytold/wordcraft/issues"));
let stable = super::about_info_for(LaunchIdentity::Stable, Some(COMMIT));
assert!(!stable.links.iter().any(|link| link.url == "https://github.com/storytold/wordcraft/issues"));
let (name, _, _) = super::about_text(LaunchIdentity::Stable, Some(COMMIT));
assert_eq!(name, "WordCraft");
}
}
#[cfg(test)]
mod tests {
use std::cell::RefCell;
use std::rc::Rc;
use craft::ui::contract::Role;
use craft::ui::dialog::DialogHost;
use craft::ui::testing::Fixture;
use super::*;
fn column_header(fixture: &Fixture, label: &str) -> egui::Rect {
fixture
.by_role(Role::COLUMN_HEADER)
.into_iter()
.find(|cell| fixture.tree().name_of(cell.node) == Some(label))
.unwrap_or_else(|| panic!("missing column header {label:?}"))
.rect
}
fn table_rect(fixture: &Fixture) -> egui::Rect {
fixture.by_role(Role::TABLE).first().expect("the credits table shows").rect
}
/// Verifies that WordCraft's `about(AboutTab::Models)` (`AboutLayout::Listed` with the baked
/// `MODELS` table) fits within the dialog and refits its `Company` column when narrowed.
/// The original drag-then-content-change refit check (#5588) belongs in `craft-libs` and is
/// tracked in `storytold/craft-libs#3372`.
#[test]
fn models_table_refits_to_narrower_window() {
let wide = egui::vec2(1400.0, 800.0);
let narrow = egui::vec2(660.0, 800.0);
let host = Rc::new(RefCell::new(DialogHost::new()));
let shown_host = Rc::clone(&host);
let mut fixture = Fixture::new(move |ui| shown_host.borrow_mut().run(ui));
fixture.room(wide);
host.borrow_mut().open(about(AboutTab::Models));
fixture.settle();
let wide_table = table_rect(&fixture);
let wide_company = column_header(&fixture, "Company");
let wide_last = column_header(&fixture, "Lines +/\u{2212}");
assert!(wide_last.right() <= wide_table.right() + 1.0, "the table opens fitted to the dialog: {wide_last:?} in {wide_table:?}");
fixture.room(narrow).settle();
let slim_table = table_rect(&fixture);
let slim_company = column_header(&fixture, "Company");
let slim_last = column_header(&fixture, "Lines +/\u{2212}");
assert!(slim_table.width() < wide_table.width() - 1.0, "hosted About shrinks with window: {slim_table:?} vs {wide_table:?}");
assert!(slim_company.width() < wide_company.width() - 1.0, "hosted About refits its Company column: {slim_company:?} vs {wide_company:?}");
assert!(slim_last.right() <= slim_table.right() + 1.0, "the narrower table still fits its last column: {slim_last:?} in {slim_table:?}");
}
}
+1 -1
View File
@@ -287,7 +287,7 @@ pub(crate) fn show(app: &mut WordApp, ui: &mut Ui, layout: &DocLayout, body: &Pa
);
}
}
if out.apply || out.discard {
if out.apply.is_some() || out.discard {
leave(app);
}
}
+1
View File
@@ -9,6 +9,7 @@ use serde_json::Value;
use crate::WordApp;
mod bookmarks;
pub(crate) mod chrome;
mod customize_keyboard;
mod enclose;
mod find;
+166
View File
@@ -0,0 +1,166 @@
//! Modal dialog chrome: modal nudge/shake animations and decorations (#3859, #4076, #7321).
use craft::ui::runtime::env::Env;
use craft::ui::style::rgba_color;
use egui::emath::TSTransform;
use egui::{Context, CornerRadius, Id, LayerId, Order, Stroke, StrokeKind, Ui, vec2};
use crate::WordApp;
/// How long a modal window shakes or flashes after a press beside it, in seconds.
pub(crate) const NUDGE_SECS: f64 = 0.4;
/// The `ctx.data` key for when the window `id` was last nudged, in this document window: the data
/// is shared by all of them.
pub(crate) fn nudge_id(ctx: &Context, id: Id) -> Id {
id.with(("nudge", ctx.viewport_id()))
}
/// Forgets a nudge of the window `id` as it closes, so it doesn't go on when the window reopens.
pub(crate) fn forget_nudge(ctx: &Context, id: Id) {
let key = nudge_id(ctx, id);
ctx.data_mut(|d| {
d.remove::<f64>(key);
});
}
/// The shake's sideways offset at `t` (0 to 1) through it: three swings either way of up to 6
/// points, dying away.
pub(crate) fn shake_offset(t: f32) -> f32 {
6.0 * (t * 3.0 * std::f32::consts::TAU).sin() * (1.0 - t)
}
/// Triggers a shake/nudge animation on dialog `id` if not already running.
pub(crate) fn trigger_prompt_nudge(ctx: &Context, id: Id) {
let key = nudge_id(ctx, id);
let now = ctx.input(|i| i.time);
let running = ctx.data(|d| d.get_temp::<f64>(key)).is_some_and(|s| (0.0..NUDGE_SECS).contains(&(now - s)));
if !running {
ctx.data_mut(|d| d.insert_temp(key, now));
}
ctx.request_repaint();
}
/// Applies modal shake / nudge animation (or accent border flashes under reduced motion) to the
/// active modal dialog. Also detects presses beside the dialog (on the backdrop or outside) to
/// trigger the nudge.
pub(crate) fn apply_modal_nudge(app: &mut WordApp, ui: &mut Ui) {
let ctx = ui.ctx().clone();
if craft::ui::runtime::measure::active(&ctx) {
return;
}
// Forget nudge on every dialog close, so reopening within NUDGE_SECS opens still.
// Tracking the host-provided open_serial distinguishes successive opens sharing the same ID.
let prev_open_key = Id::NULL.with("modal_dialogs_open_last_pass").with(ctx.viewport_id());
let prev_open: Vec<(Id, u64)> = ctx.data(|d| d.get_temp(prev_open_key)).unwrap_or_default();
let current_open: Vec<(Id, u64)> =
app.dialog_host.open_dialogs().into_iter().filter_map(|d| app.dialog_host.open_serial(d.id).map(|s| (d.id, s))).collect();
for (closed_id, prev_serial) in &prev_open {
if !current_open.iter().any(|(id, serial)| id == closed_id && serial == prev_serial) {
forget_nudge(&ctx, *closed_id);
}
}
ctx.data_mut(|d| d.insert_temp(prev_open_key, current_open));
let prompt_id = app.closing.as_ref().and_then(|c| c.prompt).filter(|&id| app.dialog_host.get_dyn(id).is_some());
let target_id =
prompt_id.or_else(|| app.dialog_host.shows_modal().then(|| app.dialog_host.open_dialogs().into_iter().next_back().map(|d| d.id)).flatten());
let Some(id) = target_id else {
return;
};
let hosted = app.dialog_host.get_dyn(id).is_some();
if !hosted {
return;
}
// When popups/menus are open inside a modal dialog, overlay::top points to the popup.
// Walk up .parent to locate the target modal dialog's own overlay entry so clicking
// inside the dialog (outside the popup) does not falsely trigger a shake.
let top_id = craft::ui::runtime::overlay::top(&ctx);
let mut modal_entry = top_id.and_then(|tid| craft::ui::runtime::overlay::entry(&ctx, tid));
while let Some(entry) = modal_entry.as_ref() {
if entry.rank.is_modal() {
break;
}
modal_entry = entry.parent.and_then(|pid| craft::ui::runtime::overlay::entry(&ctx, pid));
}
let modal_entry = modal_entry.filter(|e| e.rank.is_modal());
let modal_layer_id = ctx.memory(|m| m.top_modal_layer());
let (dialog_rect, area_layer_id) = if let Some(ref entry) = modal_entry {
(Some(entry.rect), Some(LayerId::new(Order::Foreground, craft::ui::runtime::memory::sub(entry.id, "area"))))
} else if let Some(layer) = modal_layer_id {
(ctx.memory(|m| m.area_rect(layer.id)), Some(layer))
} else {
(None, None)
};
let Some(rect) = dialog_rect else {
return;
};
// Include the modal dialog's rectangle and all open overlays in its family
// (such as dropdown popups or submenus) so presses on popup extensions are inside.
let mut inside_rects = vec![rect];
if let Some(ref entry) = modal_entry {
for family_id in craft::ui::runtime::overlay::family(&ctx, entry.id) {
if let Some(e) = craft::ui::runtime::overlay::entry(&ctx, family_id) {
inside_rects.push(e.rect);
if let Some(anchor) = e.anchor {
inside_rects.push(anchor);
}
}
}
}
let is_inside = |pos: egui::Pos2| inside_rects.iter().any(|r| r.contains(pos));
let beside = ctx.input(|i| {
let event_pressed = i.events.iter().any(|e| match e {
egui::Event::PointerButton { pos, pressed: true, button: egui::PointerButton::Primary, .. } => !is_inside(*pos),
_ => false,
});
let held_pressed = i.pointer.any_pressed() && i.pointer.press_origin().is_some_and(|p| !is_inside(p));
event_pressed || held_pressed
});
if beside {
trigger_prompt_nudge(&ctx, id);
}
let key = nudge_id(&ctx, id);
let now = ctx.input(|i| i.time);
let start = match ctx.data(|d| d.get_temp::<f64>(key)).filter(|s| (0.0..NUDGE_SECS).contains(&(now - s))) {
Some(s) => s,
None => return,
};
ctx.request_repaint();
let t = ((now - start) / NUDGE_SECS).clamp(0.0, 1.0) as f32;
let animate = app.animations_on() && app.system_animations();
if animate {
let offset = shake_offset(t);
let transform = TSTransform::from_translation(vec2(offset, 0.0));
if let Some(area_layer) = area_layer_id {
ctx.transform_layer_shapes(area_layer, transform);
}
if let Some(modal_layer) = modal_layer_id
&& Some(modal_layer) != area_layer_id
{
ctx.transform_layer_shapes(modal_layer, transform);
}
} else if ((t * 4.0) as u32).is_multiple_of(2) {
let env = Env::of(ui);
let radius = CornerRadius::from(env.tokens.shape.radius.window);
let stroke = Stroke::new(2.0, rgba_color(env.tokens.color.accent.solid));
if let Some(area_layer) = area_layer_id {
ctx.layer_painter(area_layer).rect_stroke(rect, radius, stroke, StrokeKind::Inside);
}
if let Some(modal_layer) = modal_layer_id
&& Some(modal_layer) != area_layer_id
{
ctx.layer_painter(modal_layer).rect_stroke(rect, radius, stroke, StrokeKind::Inside);
}
}
}
@@ -147,10 +147,14 @@ pub(crate) fn open(app: &mut WordApp, _name: &str, _params: &Value, parent: Opti
#[cfg(test)]
mod tests {
use craft::keymap::Binding;
use craft::keymap::{Binding, CommandRef};
use craft::ui::dialog::dialog_id;
use egui::accesskit::Role;
use egui_kittest::kittest::{By, NodeT, Queryable};
use serde_json::json;
use wordcraft_engine::Session;
use super::KEY;
use crate::{Services, WordApp};
fn app() -> WordApp {
@@ -181,4 +185,66 @@ mod tests {
assert_eq!(chords(&b, "format.bold"), Some(Vec::new()));
assert_eq!(chords(&b, "format.italic"), Some(italic));
}
/// #1905: a command with no shortcuts shows `None` in the Current shortcuts list, whereas a
/// command with a built-in shortcut shows its binding instead of `None`.
#[test]
fn keys_list_without_shortcuts_says_none() {
let mut a = app();
super::open(&mut a, KEY, &json!({}), None).expect("dialog opens");
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_eframe(|_| a);
h.run_steps(2);
let keymap = craft::ui::runtime::commands::keymap(&h.ctx).expect("command board installs a keymap");
let unbound_id = h
.state()
.session
.registry
.all()
.iter()
.find(|spec| {
let cmd = CommandRef::new(spec.id);
keymap.bindable(&cmd).is_some() && keymap.bindings(&cmd).is_empty()
})
.map(|spec| spec.id.to_string())
.expect("a bindable command with no built-in shortcut");
assert!(!keymap.bindings(&CommandRef::new("format.bold")).is_empty(), "format.bold has a built-in shortcut");
let dlg_id = dialog_id(KEY);
let ctx = h.ctx.clone();
let select = |h: &mut egui_kittest::Harness<'_, WordApp>, id: &str| {
h.state_mut().dialog_host.set_json_field(&ctx, dlg_id, "command", json!(id)).expect("command field accepts id");
h.run_steps(3);
let selected = h
.state()
.dialog_host
.open_dialogs()
.into_iter()
.find(|d| d.id == dlg_id)
.and_then(|d| d.fields)
.and_then(|fields| fields.get("command").and_then(|v| v.as_str()).map(str::to_owned));
assert_eq!(selected.as_deref(), Some(id), "dialog selected {id}");
};
let keys_list_labels = |h: &egui_kittest::Harness<'_, WordApp>| -> Vec<String> {
let list = h.get_by_role_and_label(Role::List, "Current shortcuts:");
let list_id = list.accesskit_node().id();
let rect = list.rect();
h.query_all(By::new())
.filter(|n| n.accesskit_node().id() != list_id && !n.accesskit_node().is_hidden() && n.accesskit_node().bounding_box().is_some())
.filter(|n| rect.contains_rect(n.rect()))
.filter_map(|n| n.accesskit_node().label())
.collect()
};
// Positive contrast: a bound command lists its shortcut and does not show the empty `None` placeholder.
select(&mut h, "format.bold");
let bound_labels = keys_list_labels(&h);
assert!(!bound_labels.is_empty(), "bound command lists its shortcut");
assert!(!bound_labels.iter().any(|t| t == "None"), "bound command keys list does not say None: {bound_labels:?}");
// Target behavior: an unbound command shows `None` inside the Current shortcuts list.
select(&mut h, &unbound_id);
let unbound_labels = keys_list_labels(&h);
assert!(unbound_labels.iter().any(|t| t == "None"), "empty keys list says None: {unbound_labels:?}");
}
}
+7 -4
View File
@@ -14,7 +14,7 @@ use craft::ui::contract::{
use craft::ui::dialog::DialogId;
use craft::ui::display::Text;
use craft::ui::layout_components::Row;
use craft::ui::list::{ListRow, ThumbAspect};
use craft::ui::list::{ListRow, ThumbAspect, ThumbSize};
// PLAN: assumed `FormCx::accept` (dialogs-w5, S-L285)
use craft::ui::patterns::form_dialogs::FormCx;
use craft::ui::primitives::DataWidth;
@@ -22,7 +22,7 @@ use craft::ui::runtime::env::Label;
use craft::ui::style::DataColor;
use craft::ui::table::Table;
use craft::ui::text::TextField;
use craft::ui::tile_grid::{Tile, TileGrid};
use craft::ui::tile_grid::{GridZoom, Tile, TileGrid};
use egui::{Color32, Ui, Vec2};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
@@ -272,6 +272,9 @@ fn chart_grid(ui: &mut Ui, colors: [Color32; 3], form: &mut ChartTypeForm) -> bo
let current = kinds.iter().position(|k| *k == form.kind).unwrap_or(0);
let source = keyed(&positions, |i| *i);
let out = TileGrid::<usize>::new(tl!("Chart types").to_string())
.thumb_size(ThumbSize::Large)
.zoom(GridZoom::Fixed(1.6))
.aspect(19.0 / 15.0)
.select(SelectMode::Single)
.card_columns(3)
// Every type shows, as in production, so the dialog's body is the one scroll.
@@ -288,12 +291,12 @@ fn chart_grid(ui: &mut Ui, colors: [Color32; 3], form: &mut ChartTypeForm) -> bo
let mut activated = false;
for event in out.response.events {
match event {
CollectionEvent::Selection(SelectionChange::Set(keys)) => {
CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } => {
if let Some(kind) = keys.last().and_then(|k| kinds.get(*k)) {
form.kind = *kind;
}
}
CollectionEvent::Selection(SelectionChange::Toggle(key)) => {
CollectionEvent::Selection { change: SelectionChange::Toggle(key), .. } => {
if let Some(kind) = kinds.get(key) {
form.kind = *kind;
}
+2 -2
View File
@@ -26,7 +26,7 @@ pub(crate) mod symbol;
pub use columns::DropCapForm;
pub use date_time::DateTimeForm;
#[cfg(test)]
pub(crate) use date_time::date_time_preview_matches;
pub(crate) use date_time::date_time_previews_at;
pub use field::{DATE_FORMATS, FIELD_CATEGORIES, FIELDS, FieldForm, FieldKind, NUMBER_FORMATS, STYLEREF_SWITCHES, field_kind};
pub(crate) use symbol::SymbolDialog;
pub use symbol::{RECENT_SYMBOLS, RecentSymbol, SPECIAL, SUBSETS, SymbolForm, remember_symbol, subset_of};
@@ -107,7 +107,7 @@ pub(super) fn list_index(ui: &mut Ui, label: &Label, rows: &[String], current: O
let mut picked = Picked { selected: None, activated: None };
for event in events {
match event {
CollectionEvent::Selection(SelectionChange::Set(set)) => picked.selected = set.last().copied(),
CollectionEvent::Selection { change: SelectionChange::Set(set), .. } => picked.selected = set.last().copied(),
CollectionEvent::Activate(row) => {
picked.selected = Some(row);
picked.activated = Some(row);
@@ -35,14 +35,16 @@ const PT_DATE_FORMATS: &[&str] = &[
"HH:mm:ss",
];
/// The date preview list consists of document values (not interface strings).
/// The i18n audit recognizes these dynamic values instead of treating month names as UI labels.
/// What the Date and Time preview list shows at the instant `unix`: document values, not
/// interface strings. The i18n audit recognizes these instead of treating month names, dates and
/// times as labels.
#[cfg(test)]
pub(crate) fn date_time_preview_matches(value: &str) -> bool {
PT_DATE_FORMATS.iter().chain(DATE_FORMATS.iter()).any(|picture| {
wordcraft_engine::cmd::insert::format_date_in(picture, Some("pt-BR")) == value
|| wordcraft_engine::cmd::insert::format_date_in(picture, Some("en-US")) == value
})
pub(crate) fn date_time_previews_at(unix: u64) -> impl Iterator<Item = String> {
let offset = wordcraft_engine::cmd::local_offset_secs(unix);
PT_DATE_FORMATS
.iter()
.chain(DATE_FORMATS.iter())
.flat_map(move |picture| ["pt-BR", "en-US"].map(|lang| wordcraft_engine::cmd::insert::format_date_at_in(picture, Some(lang), unix, offset)))
}
/// State of the Word-like Insert > Date & Time dialog.
@@ -8,7 +8,7 @@ use craft::ui::dialog::{DialogId, DialogResult, DialogStack, HeldAnswer, HeldOk,
use craft::ui::display::{Kbd, Text};
use craft::ui::form::Field;
use craft::ui::layout_components::Stack;
use craft::ui::list::{ListRow, ThumbAspect};
use craft::ui::list::{ListRow, ThumbAspect, ThumbSize};
use craft::ui::patterns::form_dialogs::{FormCx, FormDialog};
use craft::ui::primitives::ContentPainterCx;
use craft::ui::runtime::env::Label;
@@ -501,7 +501,7 @@ fn symbol_body(
&mut |t, _| Tab::new(word(if *t == 0 { "Symbols" } else { "Special Characters" })),
);
for event in out.response.events {
if let CollectionEvent::Selection(SelectionChange::Set(keys)) = event
if let CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } = event
&& let Some(t) = keys.last()
{
form.tab = *t;
@@ -570,7 +570,7 @@ fn special_table(ui: &mut Ui, form: &mut SymbolForm) -> bool {
let mut activated = false;
for event in events {
match event {
CollectionEvent::Selection(SelectionChange::Set(set)) => {
CollectionEvent::Selection { change: SelectionChange::Set(set), .. } => {
if let Some(at) = set.last() {
form.special = *at;
}
@@ -639,6 +639,7 @@ fn recent_row(ui: &mut Ui, form: &mut SymbolForm, dark: bool) {
let events = {
let recent = &form.recent;
TileGrid::new(word("Recently used symbols:"))
.thumb_size(ThumbSize::Medium)
.select(SelectMode::Single)
.caption(CaptionPlace::None)
.card_columns(RECENT_SYMBOLS)
@@ -654,7 +655,7 @@ fn recent_row(ui: &mut Ui, form: &mut SymbolForm, dark: bool) {
.events
};
for event in events {
if let CollectionEvent::Selection(SelectionChange::Set(rows)) = event
if let CollectionEvent::Selection { change: SelectionChange::Set(rows), .. } = event
&& let Some(r) = rows.last().and_then(|i| form.recent.get(*i)).cloned()
&& let Some(c) = r.ch.chars().next()
{
@@ -681,8 +682,12 @@ fn glyph_grid(ui: &mut Ui, form: &mut SymbolForm, dark: bool) -> bool {
let font = form.shown_font().to_string();
let events = {
let chars = &form.chars;
let mut grid =
TileGrid::new(word("Symbols")).select(SelectMode::Single).max_rows(8).caption(CaptionPlace::None).selection(Bind::bound(&mut selection));
let mut grid = TileGrid::new(word("Symbols"))
.thumb_size(ThumbSize::Medium)
.select(SelectMode::Single)
.max_rows(8)
.caption(CaptionPlace::None)
.selection(Bind::bound(&mut selection));
if let Some(at) = reveal {
grid = grid.reveal(at);
}
@@ -697,7 +702,7 @@ fn glyph_grid(ui: &mut Ui, form: &mut SymbolForm, dark: bool) -> bool {
let (mut picked, mut activated) = (None, false);
for event in events {
match event {
CollectionEvent::Selection(SelectionChange::Set(rows)) => picked = rows.last().copied().or(picked),
CollectionEvent::Selection { change: SelectionChange::Set(rows), .. } => picked = rows.last().copied().or(picked),
CollectionEvent::Activate(row) => {
picked = Some(row);
activated = true;
@@ -1,3 +1,4 @@
use egui_kittest::kittest::Queryable;
use serde_json::json;
use super::*;
@@ -118,6 +119,25 @@ fn symbol_dialog_inserts_with_its_font() {
assert_eq!(f.params().unwrap(), json!({"char": "\u{2665}"}));
}
/// #7326: Recently used symbols and Symbols map use compact tile sizing so the dialog
/// fits comfortably within default window bounds without vertical overflow.
#[test]
fn symbol_dialog_uses_compact_tile_grids() {
let mut a = app();
remember_symbol(&mut a, "©", "DejaVu Sans");
let mut h = testing::harness(a);
let id = crate::dialogs::open(h.state_mut(), "symbol", &json!({})).expect("symbol dialog opens");
h.run_steps(3);
assert!(h.state().dialog_host.get_dyn(id).is_some(), "the symbol dialog is open");
let dialog = h.get_by_role_and_label(egui::accesskit::Role::Dialog, "Symbol").rect();
assert!(dialog.height() <= 900.0, "complete dialog should fit within default desktop viewport: {}", dialog.height());
assert!(dialog.max.y <= 900.0, "complete dialog should not overflow viewport bottom: {}", dialog.max.y);
let symbols = h.get_by_role_and_label(egui::accesskit::Role::ListBox, "Symbols").rect();
assert!(symbols.height() < 500.0, "symbols grid should be compact: {}", symbols.height());
let recent = h.get_by_role_and_label(egui::accesskit::Role::ListBox, "Recently used symbols:").rect();
assert!(recent.height() < 80.0, "recently used symbols row should be compact: {}", recent.height());
}
/// The Field dialog builds the field code from its options.
#[test]
fn field_dialog_builds_the_instruction() {
@@ -355,3 +375,21 @@ fn date_time_dialog_keeps_open_and_displays_invalid_picture_error() {
assert!(a.dialog_host.get_dyn(id).is_some(), "the dialog stays open");
assert_eq!(a.session.doc.plain_text(wordcraft_doc::StoryRef::Body), "");
}
/// #4832: Document Information fields are offered and format instructions match the chosen
/// format.
#[test]
fn field_dialog_lists_the_document_information_fields() {
let listed: Vec<&str> = FIELDS.iter().filter(|(_, cat, _)| *cat == "Document Information").map(|(n, _, _)| *n).collect();
for name in ["COMMENTS", "KEYWORDS", "LASTSAVEDBY", "NUMCHARS", "REVNUM", "SUBJECT"] {
assert!(listed.contains(&name), "{name} in {listed:?}");
}
let a = app();
let mut f = FieldForm::new(&a);
f.select("REVNUM");
f.number_format = "ROMAN".into();
f.preserve = false;
assert_eq!(f.instruction(), r"REVNUM \* ROMAN");
f.select("SUBJECT");
assert_eq!(f.instruction(), "SUBJECT");
}
@@ -452,8 +452,8 @@ impl WordForm for LanguageForm {
.show_items(ui, &source, &mut |i, _| ListRow::new(Label::from(list.get(*i).map(|(_, n)| n.clone()).unwrap_or_default())));
// A language is always chosen: a Clear leaves it, and a Toggle of the chosen row picks it again.
let picked = shown.events.into_iter().find_map(|event| match event {
CollectionEvent::Selection(SelectionChange::Set(keys)) => keys.last().copied(),
CollectionEvent::Selection(SelectionChange::Toggle(key)) => Some(key),
CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } => keys.last().copied(),
CollectionEvent::Selection { change: SelectionChange::Toggle(key), .. } => Some(key),
_ => None,
});
if let Some((tag, _)) = picked.and_then(|i| list.get(i)) {
+91 -7
View File
@@ -14,9 +14,9 @@ use craft::ui::patterns::form_dialogs::FormCx;
use craft::ui::primitives::{ContentPainterCx, TextRun};
use craft::ui::runtime::env::{Label, LengthUnits, UnitKind};
use craft::ui::sections::Section;
use craft::ui::style::{Corners, SurfaceKind, TypeRole};
use craft::ui::style::TypeRole;
use craft::ui::text::{NumberField, TextField};
use egui::{Rect, Ui, pos2, vec2};
use egui::{Color32, Rect, Ui, pos2};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use wordcraft_doc::section::NumFormat;
@@ -272,7 +272,7 @@ impl ListForm {
.show_items(ui, &source, &mut |at, _| ListRow::new((*at + 1).to_string()))
.events;
for event in events {
if let CollectionEvent::Selection(SelectionChange::Set(keys)) = event
if let CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } = event
&& let Some(chosen) = keys.last()
{
self.level = *chosen;
@@ -293,7 +293,10 @@ impl ListForm {
/// being edited at full strength and the others faded.
fn preview(rows: Vec<PreviewRow>, edited: usize) -> impl Fn(&ContentPainterCx, Rect) {
move |cx: &ContentPainterCx, rect: Rect| {
cx.surface(rect, SurfaceKind::Sunken, Corners::All);
cx.data_shapes([
egui::Shape::rect_filled(rect, 2.0, Color32::WHITE),
egui::Shape::rect_stroke(rect, 2.0, egui::Stroke::new(1.0, Color32::from_gray(160)), egui::StrokeKind::Inside),
]);
let row = rect.height() / LEVELS as f32;
// Positions are points, scaled so 4.5 inches fit.
let scale = (rect.width() - 16.0).max(1.0) / 324.0;
@@ -302,14 +305,20 @@ fn preview(rows: Vec<PreviewRow>, edited: usize) -> impl Fn(&ContentPainterCx, R
let top = rect.top() + row * i as f32;
let paint = |cx: &ContentPainterCx| {
let run = TextRun::new(r.sample.clone()).role(TypeRole::Caption);
let width = cx.with_draw(|draw| draw.layout(&run, f32::INFINITY).size().x);
let layout = cx.with_draw(|draw| draw.layout(&run, f32::INFINITY));
let width = layout.size().x;
let x = x_of(r.aligned_at);
let number_x = match r.align.as_str() {
"center" => x - width / 2.0,
"right" => x - width,
_ => x,
};
cx.with_draw(|draw| draw.text(Rect::from_min_size(pos2(number_x, top), vec2(width + 1.0, row)), &run));
let spare = if layout.galley.rows.len() <= 1 { (row - layout.size().y).max(0.0) } else { 0.0 };
cx.data_shapes([egui::Shape::galley_with_override_text_color(
pos2(number_x, top + spare / 2.0),
layout.galley.clone(),
Color32::BLACK,
)]);
let text_x = match r.follow.as_str() {
"space" => number_x + width + 3.0,
"nothing" => number_x + width,
@@ -317,7 +326,7 @@ fn preview(rows: Vec<PreviewRow>, edited: usize) -> impl Fn(&ContentPainterCx, R
};
let bar = Rect::from_min_max(pos2(text_x, top + row / 2.0 - 2.0), pos2(rect.right() - 8.0, top + row / 2.0 + 2.0));
if bar.width() > 0.0 {
let draw_bar = |cx: &ContentPainterCx| cx.data_shapes([egui::Shape::rect_filled(bar, 1.0, cx.ink())]);
let draw_bar = |cx: &ContentPainterCx| cx.data_shapes([egui::Shape::rect_filled(bar, 1.0, Color32::BLACK)]);
cx.faded(0.45, draw_bar);
}
};
@@ -789,4 +798,79 @@ mod tests {
a.run("review.trackingOptions", json!({"moveToMark": v})).unwrap();
}
}
/// #7325: the Define New Multilevel List dialog preview renders an opaque white paper sheet
/// with a crisp stroke outline across both Light and Dark themes, and renders level samples
/// and text bars in fixed dark ink.
#[test]
fn define_new_multilevel_list_preview_opaque_paper_in_both_themes() {
use egui::epaint::ClippedShape;
fn collect_shapes<'a>(shapes: &'a [ClippedShape], out: &mut Vec<&'a egui::Shape>) {
for clipped in shapes {
fn walk<'a>(shape: &'a egui::Shape, out: &mut Vec<&'a egui::Shape>) {
match shape {
egui::Shape::Vec(children) => {
for child in children {
walk(child, out);
}
}
other => out.push(other),
}
}
walk(&clipped.shape, out);
}
}
for theme in ["light", "dark"] {
let mut a = app();
a.run("ui.theme", json!({"value": theme})).unwrap();
let mut h = harness(a);
assert_eq!(h.state_mut().run("list.define", json!({})).unwrap(), json!({"pending": "defineList"}));
h.run_steps(2);
let mut shapes = Vec::new();
collect_shapes(&h.output().shapes, &mut shapes);
// Verify the preview paper sheet is painted as an opaque white rect
let white_rects: Vec<_> = shapes
.iter()
.filter_map(|s| match s {
egui::Shape::Rect(r)
if r.fill == egui::Color32::WHITE && (r.rect.width() - 80.0).abs() <= 5.0 && (r.rect.height() - 48.0).abs() <= 5.0 =>
{
Some(r)
}
_ => None,
})
.collect();
assert!(!white_rects.is_empty(), "{theme}: preview sheet must have an opaque white paper background");
// Verify crisp stroke border (StrokeKind::Inside with gray 160)
let stroke_rects: Vec<_> = shapes
.iter()
.filter_map(|s| match s {
egui::Shape::Rect(r)
if r.stroke.color == egui::Color32::from_gray(160)
&& (r.rect.width() - 80.0).abs() <= 5.0
&& (r.rect.height() - 48.0).abs() <= 5.0 =>
{
Some(r)
}
_ => None,
})
.collect();
assert!(!stroke_rects.is_empty(), "{theme}: preview sheet must have a crisp stroke border");
// Verify sample text has black override text color in both themes
let black_text_samples: Vec<_> = shapes
.iter()
.filter_map(|s| match s {
egui::Shape::Text(t) if t.override_text_color == Some(egui::Color32::BLACK) => Some(t),
_ => None,
})
.collect();
assert!(!black_text_samples.is_empty(), "{theme}: preview text samples must override text color with black");
}
}
}
+1 -1
View File
@@ -446,7 +446,7 @@ impl BordersForm {
let out = strip
.show_items(ui, &source, &mut |key, _| Tab::new(tabs.iter().find(|tab| tab.0 == *key).map_or_else(String::new, |tab| tab.1.clone())));
for event in out.response.events {
if let CollectionEvent::Selection(SelectionChange::Set(keys)) = event
if let CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } = event
&& let Some(chosen) = keys.last()
{
self.tab = *chosen;
@@ -313,11 +313,11 @@ impl WordForm for SourceManagerForm {
.show_items(ui, &source, &mut |i, _| ListRow::new(Label::from(rows.get(*i).cloned().unwrap_or_default())));
for event in shown.events {
match event {
CollectionEvent::Selection(SelectionChange::Set(keys)) => self.selected = keys.last().copied(),
CollectionEvent::Selection(SelectionChange::Toggle(key)) => {
CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } => self.selected = keys.last().copied(),
CollectionEvent::Selection { change: SelectionChange::Toggle(key), .. } => {
self.selected = if self.selected == Some(key) { None } else { Some(key) };
}
CollectionEvent::Selection(SelectionChange::Clear) => self.selected = None,
CollectionEvent::Selection { change: SelectionChange::Clear, .. } => self.selected = None,
_ => {}
}
}
@@ -322,8 +322,8 @@ impl WordForm for TocStylesForm {
// A level is always picked: Clear and a Toggle off keep the current one.
for event in shown.events {
let picked = match event {
CollectionEvent::Selection(SelectionChange::Set(keys)) => keys.last().copied(),
CollectionEvent::Selection(SelectionChange::Toggle(key)) => Some(key),
CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } => keys.last().copied(),
CollectionEvent::Selection { change: SelectionChange::Toggle(key), .. } => Some(key),
_ => None,
};
if let Some(at) = picked {
+84 -3
View File
@@ -401,7 +401,7 @@ fn list_table(ui: &mut Ui, name: &str, rows: &[(String, String)], second: bool,
});
let mut picked = None;
for event in out.events {
if let CollectionEvent::Selection(SelectionChange::Set(keys)) = event
if let CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } = event
&& let Some(key) = keys.into_iter().last()
{
picked = Some(key);
@@ -560,7 +560,7 @@ impl WordForm for AutoCorrectForm {
.natural_height(true)
.show_items(ui, &source, &mut |key, _| Tab::new(tab_name(*key)));
for event in strip.response.events {
if let CollectionEvent::Selection(SelectionChange::Set(keys)) = event
if let CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } = event
&& let Some(key) = keys.into_iter().last()
{
self.tab = key.min(2);
@@ -632,7 +632,7 @@ mod tests {
use egui_kittest::kittest::Queryable;
let mut app = app("");
app.run("tools.autocorrect", json!({})).unwrap();
let mut h = crate::test_harness::builder().with_size(vec2(1440.0, 900.0)).build_ui_state(
let mut h = crate::test_harness::builder().allow_missing_glyphs().with_size(vec2(1440.0, 900.0)).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
@@ -665,4 +665,85 @@ mod tests {
}
assert_eq!(h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body), "Hello. world");
}
/// #3036: the Replace list says so when the filter matches nothing instead of going blank.
#[test]
fn the_autocorrect_list_says_when_the_filter_matches_nothing() {
let mut app = app("");
app.session.prefs.autocorrect.entries.push(("brb".to_string(), "be right back".to_string()));
app.run("tools.autocorrect", json!({})).unwrap();
fn texts(h: &egui_kittest::Harness<'_, WordApp>) -> Vec<String> {
fn extract(shape: &egui::Shape, out: &mut Vec<String>) {
match shape {
egui::Shape::Text(t) => out.push(t.galley.text().to_string()),
egui::Shape::Vec(v) => v.iter().for_each(|s| extract(s, out)),
_ => {}
}
}
let mut out = Vec::new();
for clipped in &h.output().shapes {
extract(&clipped.shape, &mut out);
}
out
}
let mut h = crate::test_harness::builder().allow_missing_glyphs().with_size(vec2(1440.0, 900.0)).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
app,
);
for _ in 0..4 {
h.step();
}
assert!(!texts(&h).iter().any(|t| t.contains("(none)")), "entries show, no hint");
if let Some(host) = h.state_mut().dialog_host.get_mut::<FormHost<AutoCorrectForm>>() {
host.form_mut().from = "zzz".to_string();
} else {
panic!("the AutoCorrect form is open");
}
for _ in 0..2 {
h.step();
}
assert!(texts(&h).iter().any(|t| t.contains("(none)")), "no matches: the hint shows");
}
/// #6046: Compare › More shows "Show changes at:" and its two choices each on one line. The
/// column is not the grid's last, so it first gets the grid's minimum cell width; wrapped to
/// that, its text broke after every few letters and the column stayed that narrow.
#[test]
fn compare_more_keeps_the_show_changes_at_column_on_one_line() {
use egui_kittest::kittest::Queryable;
let mut app = app("Original text.");
app.run("review.compare", json!({})).unwrap();
let mut h = crate::test_harness::builder().allow_missing_glyphs().with_size(vec2(1440.0, 900.0)).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
app,
);
h.run_steps(4);
h.get_by_label("More >>").click();
h.run_steps(4);
let one_line = h.get_by_label("New document").rect().height();
for label in ["Word level", "Character level"] {
let r = h.get_by_label(label).rect();
assert!(r.height() <= one_line + 1.0, "{label} wraps: {r:?}, one line is {one_line}");
}
fn find_galley<'a>(shape: &'a egui::Shape, text: &str) -> Option<&'a std::sync::Arc<egui::Galley>> {
match shape {
egui::Shape::Text(t) if t.galley.text() == text => Some(&t.galley),
egui::Shape::Vec(v) => v.iter().find_map(|s| find_galley(s, text)),
_ => None,
}
}
let galley = h.output().shapes.iter().find_map(|s| find_galley(&s.shape, "Show changes at:")).expect("Show changes at: text galley");
assert_eq!(galley.rows.len(), 1, "Show changes at: must be on one line, but has {} rows", galley.rows.len());
// The next column starts after the widest of them.
let (left, right) = (h.get_by_label("Character level").rect(), h.get_by_label("Show changes in:").rect());
assert!(right.left() >= left.right(), "the columns overlap: {left:?} {right:?}");
}
}
+40 -1
View File
@@ -190,7 +190,7 @@ impl RibbonDialog {
&mut |page, _| Tab::new(tabs.iter().find(|tab| tab.0 == *page).map_or_else(String::new, |tab| tab.1.clone())),
);
for event in out.response.events {
if let CollectionEvent::Selection(SelectionChange::Set(pages)) = event
if let CollectionEvent::Selection { change: SelectionChange::Set(pages), .. } = event
&& let Some(page) = pages.last()
&& *page != self.page
{
@@ -788,6 +788,7 @@ pub(crate) fn open(app: &mut WordApp, name: &str, _params: &Value, parent: Optio
#[cfg(test)]
mod tests {
use super::*;
use egui_kittest::kittest::Queryable;
use serde_json::json;
use wordcraft_engine::Session;
@@ -859,4 +860,42 @@ mod tests {
crate::test_harness::frames(&mut h, 3);
assert_ne!(h.state().session.view.ruler, ruler, "the custom group's button runs its command");
}
/// #1845: typing in the command filter searches across all commands regardless of category,
/// and Add >> places the selected command on the Quick Access Toolbar.
#[test]
fn command_filter_narrows_the_picker_and_add_works() {
let mut a = app();
a.run("tools.customizeRibbon", json!({})).unwrap();
let id = craft::ui::dialog::dialog_id("customizeRibbon");
assert!(a.dialog_host.open_dialogs().iter().any(|d| d.id == id), "the dialog is open");
let (category, current) = {
let d = a.dialog_host.get_by_id::<RibbonDialog>(id).expect("dialog exists");
(d.category.clone(), d.command.clone())
};
// Empty filter keeps the category scope.
let unfiltered = matching_commands(&a, &category, "");
assert!(!unfiltered.is_empty());
// Typing searches every command, ignoring the category.
let filter = "bold";
let cmds = matching_commands(&a, &category, filter);
assert!(cmds.iter().any(|(cmd_id, _)| cmd_id == "format.bold"));
assert!(cmds.len() < a.session.registry.all().len());
let ctx = egui::Context::default();
a.dialog_host.set_json_field(&ctx, id, "filter", json!(filter)).unwrap();
prepare(&mut a, id);
let picked = select_in(&cmds, &current);
assert!(!picked.is_empty());
a.dialog_host.set_json_field(&ctx, id, "command", json!(picked)).unwrap();
// The dialog's Add >> adds the filtered pick to the Quick Access Toolbar.
a.run("tools.customizeRibbon", json!({"qatAdd": picked})).unwrap();
assert!(a.session.ribbon.qat().contains(&picked.as_str()));
assert!(a.session.ribbon.qat().contains(&"format.bold"));
}
}

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