Compare commits

...
Author SHA1 Message Date
FredApps 6854bd1fb3 Merge remote-tracking branch 'origin/main' into pr6863 2026-11-16 16:05:20 +01:00
FredApps 4356771236 geom: pin craft-tiff to craft-libs main at the merge of #1867 (6ef2c053) 2026-11-16 16:05:20 +01:00
Dylan M. Taylor cdf146cabd Merge pull request #6759 from RickiNano/fix/6757-unequal-formats-linear
Layout: a paragraph over many pages lays out in linear time (#6757)
2026-11-16 07:38:06 -05:00
Martin BallandClaude Opus 5.5 54e3e1cf34 CI: fix red SonarCloud on main (#6859)
The coverage shards failed six tests on every main push:
- three UI glyph tests: the Sonar job had no craft-fonts. Pass the same
  fonts-ref as ci.yml.
- three layout linear-time tests: llvm-cov instrumentation pushes the
  8x time ratio past 24 (24.2-31.2). Ignore them under cfg(coverage),
  which cargo llvm-cov sets; the gate CI still runs them.


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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 12:06:41 +00:00
Dylan M. Taylor 97c13a2990 geom: delegate TIFF compression inspection to craft-tiff 2026-11-16 06:44:41 -05:00
Martin BallandClaude Opus 5.5 fe8a8a838c Header pictures: while editing the header, a click selects its Behind Text picture wherever no header text covers it (#5601)
* Header pictures: while editing the header, a click selects its Behind Text picture wherever no header text covers it

Header and footer Behind Text pictures skip the deferred drag-over-text path
where the plain hit test picked them with no text under them, and a right-click
selects them (and sets the page they were hit on) so Reset Picture and Wrap
Text act on them. Tests cover a header and a footer, a drag, and a repeated
picture right-clicked on another page.

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

* #5601: header Behind Text picture: a left-click selects the copy clicked on a repeated page

The press branch of pointer() selected the picture but left page_hint on the page being edited, so on a header picture repeated on page 2 the frame and handles were resolved and drawn on page 1. Set page_hint to the picked object's page, as select_at does for a right-click. Adds a left-click counterpart to the right-click test.

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

* #5601: header text hit test checks each line's own extent

CodeRabbit: hf_text_at took the whole paragraph's right edge from its last line, so
a click on a long first line past a short last line's end counted as clear of text
and selected the Behind Text picture under it. Each line now has its own band and
extent.

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

* #5601: pin that centred and right-aligned header lines cover their whole band

Line::left/right are the edges available to a line, not where its ink sits,
so a centred or right-aligned header line already covers the Behind Text
picture across its band (indent and floats narrow it) plus 40pt. Test pins
that, and the parity row now says what counts as covering the picture.

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

* #5601: pin Line.left/right as band edges in the header band test

Assert the band's left edge is the 150pt indent, the centred/right ink
starts well inside it, and a click between the indent and the ink is
text. Fails if Line.left were the ink extent.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 10:08:59 +00:00
2bd6f372c5 File › Print: reopened, the page doesn't repeat the last job's message (#5597)
* File › Print: opened again, the page doesn't repeat the last job's message

"Print job submitted…" (or a failure) stayed on the Print page the next
time it was opened. The job's outcome is said once in the status bar, so a
fresh open drops it; a failure arriving while the page is open stays, and
printer status (finding printers, none found) still shows.

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

* Print page: the last job's marker is kept per window, since egui counts passes per viewport

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

* #5597: decide the Print page's hidden job message per window

The shared printing.message is no longer cleared on reopening Print (ui.printSettings
and other windows still report it). Each window remembers what it said (status bar or
Print page) and hides only that; a result that arrived under File's other pages is
not counted as said. Tests: failure-on-open-page now depends on reopen detection,
never-said and two-window state.

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

* #5597: follow the job message by generation, not by text

A retry that fails again with the same words is a new result and shows. A generation
(WordApp::print_gen) is bumped when a job starts and when the message changes; each
window's Print memo stores generations, so cross-window comparison is by identity too.
Also: update the print_memo doc comment, drop an empty branch, align the docs row date.

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

---------

Co-authored-by: Martin Ball <martin.ball@ucsmedical.co.uk>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 10:07:57 +00:00
8a1f101c46 Save As and Export: Browse in WordCraft when the system dialog doesn't appear (#3535) (#3801) (#5790)
* Save As and Export: Browse in WordCraft when the system dialog doesn't appear (#3535) (#3801)

Ported from #3801 by VoiceLessQ onto current main.

Re-resolved against main:
- file_browser.rs tests: rebuilt whole, keeping main's #3859 tests (browser
  above the dialog, Escape, dialog closing into the browser, modeless
  keyboard, no keytips) and the PR's #3535 export tests.
- print_page.rs: EXPORT_FORMATS now carries main's OpenDocument Text
  Template (*.ott) and Flat OpenDocument Text (*.fodt) in main's order;
  main's tests module kept.
- docs/control-protocol.md: ui.fileBrowser purpose "export" added to main's
  current row (keeps ui.displayServer).
- docs/ui-parity.md: File dialogs row merged with main's Linux display
  server row, #3955 history row kept, status line and revision history
  bumped.

Added a test that the ott and fodt export types get their extension and
write the file.

Co-Authored-By: VoiceLessQ <44067308+VoiceLessQ@users.noreply.github.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCVCCEo7u5wetHaJRU4

* #3535: Word XML export from the system dialog adds .xml to a typed name

CodeRabbit: the system Save dialog accepts any name, and the engine takes the
explicit Flat OPC format only for an .xml path, so `letter` failed to export. The
extension is added as the built-in browser does; an existing file at the new name
is refused, since the dialog never confirmed replacing it.

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

* #3535: an existing file at the .xml name is refused on the status bar

CodeRabbit: export_dialog drops ask_file's result, so the refusal was silent with a
blocking Save dialog. finish_pick now puts it on the status bar as well.

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

* #3535: Export refusals show on the Export page; a typed document extension gives way to the chosen type's

A refused or failed export is said on the Export page (Backstage hides the status bar), as Save As does. A known document extension on the typed name is replaced by the chosen Export type's, and any other is kept with the extension added.

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

* #3535: Print page shows export errors; cancel clears them; export_name edge cases

The export error is drawn inside export_formats, so the Print page shows it as well as the Export page. Cancelling an export drops an earlier error. export_name treats a name that is only a known extension (.txt) as that extension and drops a trailing dot before adding the type's.

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

* #3535: Export error is per window; a dotfile export name gets a real extension

The export error moves from a shared Context-data id into per-window state (swapped with the window like missing_fonts), so one window's frame outside Backstage no longer erases another's message. export_name treats a dotfile name such as .docx as a stem, so the engine's explicit-format guard (Path::extension) accepts the result; Word 2003 XML exports are named the same way.

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

---------

Co-authored-by: Martin Ball <martin.ball@ucsmedical.co.uk>
Co-authored-by: VoiceLessQ <44067308+VoiceLessQ@users.noreply.github.com>
Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 10:06:53 +00:00
42f8559b97 Review › Language: set the whole document's proofing language (#3518) (#5810)
* #3518: Review › Language can set the whole document's proofing language

review.language takes scope "selection" (default, unchanged) or "document":
every run and paragraph mark of every story (body, headers, footers, notes,
comments, text boxes, table cells, glossary) takes lang/noProof in one undo
step, selection unchanged, pending typing format follows. The Language dialog
gets an "Apply to the whole document" check box.

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

* #3518: whole-document OK sends only what was changed in the Language dialog

With "Apply to the whole document" ticked, OK sends noProof only if the user
changed it from the dialog's opening value, and lang if changed or if neither
changed (never the engine's en-US default). Heading reads "Mark the whole
document as:" while ticked. Glossary walker uses doc's PARA_WALK_DEPTH (now pub).

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

* #3518: whole-document OK with Do not check ticked marks the whole document

CodeRabbit: with the caret's text already not checked, the box was unchanged, so a
whole-document OK never sent noProof and the rest of the document stayed checked.
A ticked box is now always sent; an unticked, unchanged one is still omitted.

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

* #3518: refuse whole-document language changes under protection

Protection leaves only its exceptions editable, so document scope is refused before anything changes. The post-check now compares the glossary, which no story-level check reached.

* #3518: whole-document language keeps per-run proofing, returns selection, skips glossary while tracking

- Language dialog: whole-document OK sends noProof only when the box was changed, so a language-only change no longer marks everything no-proof.
- review.language scope "document" returns the caret/selection result (plus scope).
- Whole-document change skips glossary blocks while Track Changes and Track Formatting are on (tracked formatting does not cover them).

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

* #3518: whole-document Do not check is sent when the box is clicked; report skipped glossary

- Language dialog: a whole-document OK sends noProof iff the Do-not-check box was clicked (proof_touched), so ticking it with the caret in a no-proof run still marks the whole document, while a language-only change leaves other runs alone.
- review.language document scope reports "glossarySkipped": true when the glossary was skipped under Track Changes + Track Formatting; doc comment reworded to state only the limitation.
- Docs status line and revision row bumped to 2026-11-16.

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

---------

Co-authored-by: Martin Ball <martin.ball@ucsmedical.co.uk>
Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-authored-by: Dylan M. Taylor <dylan@dylanmtaylor.com>
2026-11-16 10:05:15 +00:00
Martin BallandClaude Sonnet 5.5 bf8b37759c Ctrl/Cmd+Shift+V pastes text only when no formatting was copied, as in Word (#1537) (#5616)
* #1537: Ctrl/Cmd+Shift+V pastes text only when no formatting was copied, as in Word for Windows

With formatting picked up by Ctrl/Cmd+Shift+C it still pastes the formatting.
Closes #1537, #4943; takes over #1562.

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

* #1537: review — a browser's Mod+Shift+V paste event pastes text only, once (CodeRabbit)

On the web the key no longer pastes as well: the paste event that follows carries the text.

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

* #1537: review — copied formatting stays for every Mod+Shift+V; a browser's paste after it is ignored (wanikhawar)

Copy Formatting keeps its formatting apart from the one-shot Format Painter brush, so a second
Mod+Shift+V pastes formatting again instead of text, and Mod+Shift+C no longer arms the brush.
After Mod+Shift+V pastes formatting, the browser's paste event for the same keystroke is ignored;
paste events read the modifiers held in event order. Only Mod+Shift+V itself falls back to Keep
Text Only.

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

* #1537: review — one format buffer, formatting-only copy, browser paste suppression only where it exists

- ignore_next_paste armed only for Mod+Shift+V on platforms that send a paste event after it (web); never for a rebound key
- the ignored paste is dropped before equation and picture-file handling
- Event::Paste takes paste_mods so they don't leak into later pastes
- Copy Formatting and Format Painter replace each other; a used-up brush no longer hands over to older copied formatting
- copied formatting carries no hyperlink or revision marks

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

* #1537: review — shared format buffer, no tracked paragraph changes, pointer press ends the paste wait

- picked_format strips ParaProps fmt_change/num_change
- Format Painter pick is stored in copied_format too; a used-up or cancelled brush leaves it
- a pointer press clears ignore_next_paste
- docs: repeat-until-replaced wording

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

* #1537: review — a caret Paste Formatting keeps the target's own link and tracked marks

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

* #1537: review — an unrelated key's modifiers can't steer a later paste event

A separate paste_event_mods is set by Mod changes and Mod+V's press, and cleared by any other key, a pointer press or focus change; the release path keeps paste_mods.

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

* #1537: review — the text-only paste test checks the destination's own formatting stays (CodeRabbit)

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

* #1537: review — the docs say a Format Painter pick counts as picked-up formatting too (CodeRabbit)

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

* #1537: review — a dropped paste uses up its modifiers; range Paste Formatting keeps the link (alehel)

- The browser paste event dropped after a formatting paste now clears paste_event_mods too, so a
  later menu-bar paste isn't read as Keep Text Only. Note the no-text clipboard case.
- Test that Paste Formatting over a selection keeps the target's hyperlink.
- session.rs: copied_format holds a Format Painter pick too.
- ROADMAP: entry moved up with the other 2026-11-04 entries; stray blank line dropped.

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

* #1537: review — the wait for Mod+Shift+V's browser paste ends after a second, so a later menu-bar paste isn't dropped (FredApps)

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

* #1537: review — an expired paste wait drops the chord's noted Mod+Shift too (CodeRabbit)

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

* #1537: review — dropping the paired paste uses up its modifiers; range Paste Formatting keeps the target's link

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

* #1537: review — restore ui-parity status line; add Paste Formatting row to typing-parity

docs/ui-parity.md: the rebase had replaced main's status line with an older one;
restore it and prepend this PR's entry. docs/typing-parity.md: add the
Ctrl/Cmd+Shift+V row to the Paste section, bump status line and history.

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

* #1537: Ctrl/Cmd+Shift+V's V release never pastes a second time

On desktop the chord's key-down path pastes (text, or the copied formatting) but didn't mark the
paste as done, so releasing Shift before V left a plain Mod+V release that ran Paste again through
the clipboard-picture hook, inserting the text twice. The canvas's chord now marks the paste done;
the global-shortcut path (canvas unfocused, no release seen) doesn't, and a focus change clears
the mark so a lost release can't swallow a later Mod+V picture.
Docs: web text paste needs the browser to send its paired Paste event; with formatting copied that
event is dropped only within about a second of the key.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 09:59:47 +00:00
FredApps 1ed889c24c Merge pull request #6448 from batistalucasv/fix/control-server-reset-closed
Tests: a reset control connection counts as closed (Windows Print flake)
2026-11-16 10:23:29 +01:00
FredApps 6a7af0d679 Merge pull request #6731 from batistalucasv/fix/6722-font-combo-select-without-dropdown
UI: select font box text on click without opening dropdown (#6722)
2026-11-16 10:21:19 +01:00
ce6e4094d5 Dialogs: group settings in soft panels of dialogs to improve readability (#4038)
* Dialog sections: heading, space above, soft panel (#4035)

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

* Dialog sections: heading inside the panel, settings indented (#4035)

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

* Dialog sections: more dialogs, anonymous and nested panels, scroll on short screens (#4035)

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

* Format dialog accessibility updates

* Format reference dialog controls

* Replace deprecated egui IDs in dialogs

* Preserve stable IDs for dialog state

* Document dialog section parity update

* import layout test fixtures

* format merged code after fix

* Fix unused imports after dialog port

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-authored-by: Fluorine <joseph.anglada92@gmail.com>
2026-11-16 10:02:24 +01:00
FredApps 9088ed777d Merge pull request #6818 from storytold/extract/shared-engine-base64
Reuse shared Base64 encoding for engine payloads
2026-11-16 06:42:28 +01:00
Dylan M. Taylor cc90520b9d Merge pull request #5073 from AxylumRust/refactor/geom-clippy-pedantic
geom: satisfy Clippy pedantic lints (M14)
2026-11-15 16:49:58 -05:00
Dylan M. Taylor a95b065c2b M14: integrate current shared picture codecs and clarify refusals 2026-11-15 16:30:18 -05:00
FredApps 84026f98b2 Merge pull request #6817 from MMexicann/patch-45
M14: preserve existing PDF suffixes in web exports
2026-11-15 22:04:18 +01:00
Mex 5f228a0e24 M14: cover Unicode and misleading PDF filename suffixes
Added additional test cases for PDF file name handling in file dialogs.
2026-11-15 20:54:24 +01:00
Mex b354e0f870 M14: bound PDF suffix checks to four bytes 2026-11-15 20:53:49 +01:00
Mex 3e776e4c7d M14: cover PDF suffix case in web downloads
Assert exact delivered filenames and PDF bytes for lowercase, uppercase, mixed-case Unicode and missing suffixes.
2026-11-15 20:27:16 +01:00
Mex a9a1aa36a2 M14: preserve existing PDF suffixes in web exports
Recognize an existing PDF extension without changing its case or the requested filename.
2026-11-15 20:26:14 +01:00
RickiNanoandClaude Opus 5.5 d53a740be1 #6757: lay out a paragraph over many pages in linear time
Each page's piece of a paragraph walked every line of the paragraph in
place_objects to find the pictures and shapes to draw with it, skipping
all but its own lines and the late-float anchor lines. A paragraph over
many pages was quadratic in its lines. A later piece now walks only its
own lines and the late-float anchor lines, in the same order.

unequal_formats_lay_out_in_linear_time reads 8.0x for 8x the runs in a
debug build, down from 15.0x, so it no longer fails in the slower
SonarCloud coverage build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 10:25:09 +01:00
batistalucasv 7bff3b53e9 Test: assert egui popup state on font arrow toggle (#6722) 2026-11-14 18:35:40 -03:00
batistalucasv 0909b15eae UI: select font box text on click without opening dropdown (#6722) 2026-11-14 18:08:39 -03:00
Cédric Legrand 0aefd4d025 fix(geom): M14: adapt picture error mapping 2026-11-14 18:00:04 +01:00
Cédric Legrand 235a38c665 style(geom): M14: remove review churn 2026-11-14 17:55:18 +01:00
Cédric Legrand 3bf7a5dbbe docs(geom): M14: qualify truncated TIFF errors 2026-11-14 17:55:18 +01:00
Cédric Legrand e40199bf6f docs(geom): M14: clarify truncated TIFF errors 2026-11-14 17:55:18 +01:00
Cédric Legrand e2f94ecef9 refactor(geom): clean up Clippy pedantic diagnostics (M14) 2026-11-14 17:55:18 +01:00
batistalucasvandQwen-Coder bd188c19d8 Tests: only closure errors mean the control peer closed (#6448)
CodeRabbit pointed out that read_line returns InvalidData for bytes that are not UTF-8 while the socket stays open, and the helper treated every non-timeout error as a close. closed_by_peer() now accepts only ConnectionReset, ConnectionAborted, NotConnected and BrokenPipe, and the regression test pins InvalidData, TimedOut and WouldBlock as still open; the new assertion fails without the stricter match.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
2026-11-12 16:42:47 -03:00
batistalucasv 56a28f33b7 Merge remote-tracking branch 'upstream/main' into fix/control-server-reset-closed 2026-11-12 16:35:04 -03:00
batistalucasvandQwen-Coder cd4ab71552 Tests: a reset control connection counts as closed (Windows Print flake)
The Windows Print job on #6232 failed in a_silent_connection_is_closed: quiet.closed() only accepted end of stream, but Windows can deliver a close with nothing to read as a reset. The test binary finished in 0.81 s, so it was not the 5 s read timeout. closed_by_peer() now counts a reset, abort, not-connected or broken pipe as closed, and only a read timeout as still open; the new regression test fails before the fix with ConnectionReset. A loaded Windows runner can also take seconds to schedule the connection thread, so the silent test waits up to 20 s and still requires the close within 10 s (the production budget is 30 s).

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
2026-11-12 16:13:42 -03:00
65 changed files with 3032 additions and 826 deletions
+3
View File
@@ -18,4 +18,7 @@ jobs:
sonarcloud:
# Tracked at @main so org-wide CI improvements propagate without PR churn.
uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main
with:
# Same craft-fonts commit as ci.yml: the UI glyph tests need its CJK and Arabic fonts.
fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
secrets: inherit
Generated
+11 -1
View File
@@ -1248,7 +1248,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa
dependencies = [
"brotli-decompressor 6.3.1",
"chrono",
"craft-tiff",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c)",
"quick-xml 0.41.0",
"serde",
]
@@ -1401,6 +1401,15 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-tiff"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6ef2c053dfa758a9e292ff6ce4398bcd84aab1a1#6ef2c053dfa758a9e292ff6ce4398bcd84aab1a1"
dependencies = [
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-ui"
version = "0.1.0"
@@ -7407,6 +7416,7 @@ name = "wordcraft-geom"
version = "0.18.1"
dependencies = [
"craft-image-codecs",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6ef2c053dfa758a9e292ff6ce4398bcd84aab1a1)",
"image",
"serde",
]
+3
View File
@@ -68,6 +68,7 @@ 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 = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "6ef2c053dfa758a9e292ff6ce4398bcd84aab1a1", version = "=0.1.0" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", version = "=0.1.0", default-features = false, features = ["write"] }
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] }
@@ -122,6 +123,8 @@ arboard = { version = "3.7", default-features = false, features = ["wayland-data
[workspace.lints.rust]
unsafe_code = "forbid"
# cargo llvm-cov sets `--cfg coverage`; timing tests skip themselves under its instrumentation.
unexpected_cfgs = { level = "warn", check-cfg = ["cfg(coverage)"] }
[workspace.lints.clippy]
cognitive_complexity = "deny"
+6 -1
View File
File diff suppressed because one or more lines are too long
+40 -4
View File
@@ -369,8 +369,11 @@ mod tests {
impl Conn {
fn open(port: u16) -> Self {
Self::open_within(port, Duration::from_secs(5))
}
fn open_within(port: u16, read_timeout: Duration) -> Self {
let s = TcpStream::connect(("127.0.0.1", port)).unwrap();
s.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
s.set_read_timeout(Some(read_timeout)).unwrap();
Self(BufReader::new(s.try_clone().unwrap()), s)
}
fn send(&mut self, line: &str) {
@@ -388,7 +391,24 @@ mod tests {
/// The server closed the connection.
fn closed(&mut self) -> bool {
let mut r = String::new();
matches!(self.0.read_line(&mut r), Ok(0))
closed_by_peer(self.0.read_line(&mut r))
}
}
/// Whether a read means the peer closed the connection. End of stream does; so does a reset,
/// which is how Windows can deliver a close when the writer had nothing to read back (the
/// Windows Print job failed here). Any other error, such as `InvalidData` for bytes that are
/// not UTF-8, leaves the connection open.
fn closed_by_peer(read: std::io::Result<usize>) -> bool {
match read {
Ok(n) => n == 0,
Err(e) => matches!(
e.kind(),
std::io::ErrorKind::ConnectionReset
| std::io::ErrorKind::ConnectionAborted
| std::io::ErrorKind::NotConnected
| std::io::ErrorKind::BrokenPipe
),
}
}
@@ -473,13 +493,29 @@ mod tests {
assert!(rx.try_recv().is_err());
}
#[test]
fn only_closure_errors_mean_the_peer_closed() {
use std::io::{Error, ErrorKind};
assert!(closed_by_peer(Ok(0)), "end of stream");
for kind in [ErrorKind::ConnectionReset, ErrorKind::ConnectionAborted, ErrorKind::NotConnected, ErrorKind::BrokenPipe] {
assert!(closed_by_peer(Err(Error::new(kind, "closed"))), "{kind:?}");
}
assert!(!closed_by_peer(Ok(1)), "a reply arrived");
// Not UTF-8, a timeout or a would-block leave the socket open.
for kind in [ErrorKind::InvalidData, ErrorKind::TimedOut, ErrorKind::WouldBlock] {
assert!(!closed_by_peer(Err(Error::new(kind, "still open"))), "{kind:?}");
}
}
#[test]
fn a_silent_connection_is_closed() {
let (port, rx) = boot_with(Duration::from_millis(300));
let mut quiet = Conn::open(port);
// A loaded Windows CI runner can take seconds to schedule the connection thread. The
// production deadline is 30 s, so 10 s still proves the server's own budget fired.
let mut quiet = Conn::open_within(port, Duration::from_secs(20));
let t0 = Instant::now();
assert!(quiet.closed());
assert!(t0.elapsed() < Duration::from_secs(3));
assert!(t0.elapsed() < Duration::from_secs(10), "{:?}", t0.elapsed());
// After an authorised request the connection may stay idle.
let mut busy = Conn::open(port);
assert_eq!(busy.call(&format!(r#"{{"id":1,"method":"auth","key":"{KEY}"}}"#))["ok"], true);
+2 -2
View File
@@ -94,8 +94,8 @@ pub use settings::{
COMPAT_MODE_CURRENT, CoreProps, CustomProp, DEFAULT_GRID, DEFAULT_HYPHENATION_ZONE, LEGACY_COMPAT_MODE, OdfLayout, PagePicture, Settings, Source,
THEME_COLORS, Watermark, Zoom, ZoomFit,
};
pub(crate) use text_walk::{PARA_WALK_DEPTH, walk_between};
pub use text_walk::{count_chars, count_chars_no_spaces, count_words};
pub(crate) use text_walk::walk_between;
pub use text_walk::{PARA_WALK_DEPTH, count_chars, count_chars_no_spaces, count_words};
/// A document.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+1 -1
View File
@@ -48,7 +48,7 @@ pub fn count_chars_no_spaces(s: &str) -> usize {
}
/// How deep in nested tables [`Document::para_paths`] goes: cells below this are skipped.
pub(crate) const PARA_WALK_DEPTH: usize = 16;
pub const PARA_WALK_DEPTH: usize = 16;
/// The note and text box stories an object shows, for `Document::reachable`.
pub(crate) fn notes_and_boxes(o: &InlineObject) -> Vec<(u32, &'static [PartKind])> {
+25 -12
View File
@@ -172,7 +172,9 @@ pub fn specs() -> Vec<CommandSpec> {
.pure(),
CommandSpec::new("edit.formatPainter", "Format Painter", "Home › Clipboard", painter).params(r#"{"sticky"?: bool}"#).pure(),
CommandSpec::new("edit.copyFormat", "Copy Formatting", "Home › Clipboard", |s, _| {
painter_pick(s);
// One format buffer, as in Word: Copy Formatting replaces an armed Format Painter.
s.painter = None;
s.copied_format = Some(picked_format(s));
sel_result(s)
})
.key(copy_format_shortcut(cfg!(target_arch = "wasm32")))
@@ -832,11 +834,21 @@ fn goto(s: &mut Session, v: &Value) -> CmdResult {
sel_result(s)
}
fn painter_pick(s: &mut Session) {
/// The character and paragraph formatting at the start of the selection.
fn picked_format(s: &Session) -> (wordcraft_doc::props::CharProps, wordcraft_doc::props::ParaProps) {
let f = s.sel.ordered().0;
// A symbol's own font isn't formatting to paint onto text.
let chr = s.doc.para_at(&f).map(|p| p.props_of_char(f.off).clone().without_symbol()).unwrap_or_default();
let para = s.doc.para_at(&f).map(|p| p.props.clone()).unwrap_or_default();
// Formatting only: not the source's hyperlink or revision marks (#5616).
let chr = s.doc.para_at(&f).map(|p| p.props_of_char(f.off).clone().without_symbol().formatting()).unwrap_or_default();
let para = s.doc.para_at(&f).map(|p| p.props.clone().formatting()).unwrap_or_default();
(chr, para)
}
fn painter_pick(s: &mut Session) {
let (chr, para) = picked_format(s);
// One format buffer, as in Word: the pick is also what the next Paste Formatting applies,
// and stays after the brush is used up or cancelled.
s.copied_format = Some((chr.clone(), para.clone()));
s.painter = Some((chr, para, false));
}
@@ -852,9 +864,14 @@ fn painter(s: &mut Session, v: &Value) -> CmdResult {
Ok(json!({"active": true}))
}
/// Apply the format painter's formatting to the selection.
/// Apply the format painter's formatting to the selection, or else what Copy Formatting picked
/// up (which stays for the next Paste Formatting).
fn paste_format(s: &mut Session, _: &Value) -> CmdResult {
let Some((chr, para, sticky)) = s.painter.clone() else { return Err(CmdError::Failed("no formatting copied".into())) };
let (chr, para, sticky) = match (s.painter.clone(), s.copied_format.clone()) {
(Some(brush), _) => brush,
(None, Some((chr, para))) => (chr, para, true),
(None, None) => return Err(CmdError::Failed("no formatting copied".into())),
};
let (a, b) = s.sel.ordered();
if a == b {
// No selection: apply paragraph formatting (and word formatting like Word).
@@ -864,15 +881,11 @@ fn paste_format(s: &mut Session, _: &Value) -> CmdResult {
// Word selection includes trailing spaces; a painter click formats just the word,
// matching the ordinary collapsed-caret formatting target.
let word_end = pp.text.get(x..y).map(|word| x + word.trim_end().len()).unwrap_or(y);
s.doc.format_range(&Pos { off: x, ..f.clone() }, &Pos { off: word_end, ..f.clone() }, &|c| *c = chr.cleared().overlaid(&chr))?;
s.doc.format_range(&Pos { off: x, ..f.clone() }, &Pos { off: word_end, ..f.clone() }, &|c| *c = c.cleared().overlaid(&chr))?;
}
s.doc.format_paragraphs(&a, &b, &|p| *p = para.clone())?;
} else {
s.doc.format_range(&a, &b, &|c| {
let link = c.link.clone();
*c = c.cleared().overlaid(&chr);
c.link = link;
})?;
s.doc.format_range(&a, &b, &|c| *c = c.cleared().overlaid(&chr))?;
if a.path != b.path || a.off == 0 {
s.doc.format_paragraphs(&a, &b, &|p| *p = para.clone())?;
}
+3 -1
View File
@@ -431,7 +431,8 @@ enum HoleMode {
/// run formatting and paragraph formatting outside the ranges `author` may edit, in every story,
/// and the formatting of every table, row and cell that holds any of that protected content, and what
/// reaches the whole document: page setup, the document defaults and the existing styles
/// (applying a style may add one), the document's settings and its metadata.
/// (applying a style may add one), the glossary's building blocks, the document's settings and
/// its metadata.
pub(crate) fn outside_unchanged(before: &Document, after: &Document, author: &str) -> bool {
// Protection can't change mid-command (`protection_lifted` guards undo and redo).
let mode = if Some("forms") == before.settings.protection.as_deref() { HoleMode::Controls } else { HoleMode::Perms(author.into()) };
@@ -444,6 +445,7 @@ pub(crate) fn outside_unchanged(before: &Document, after: &Document, author: &st
&& before.settings == after.settings
&& before.core == after.core
&& before.custom_props == after.custom_props
&& before.glossary == after.glossary
&& comments_unchanged(before, after)
&& lists_unchanged(before, after)
&& sources_unchanged(before, after)
+17
View File
@@ -428,6 +428,23 @@ fn the_post_check_compares_the_settings_and_the_metadata() {
assert!(super::outside_unchanged(&before, &before.clone(), "someone"), "an unchanged document isn't unchanged");
}
/// The glossary's building blocks reach the whole document, so the post-check compares them.
#[test]
fn the_post_check_compares_the_glossary() {
use wordcraft_doc::{BuildingBlock, CharProps, Paragraph};
let mut before = Document::from_text("Some text.");
before.glossary.push(BuildingBlock {
name: "g".into(),
blocks: vec![wordcraft_doc::para_block(Paragraph::with_text("Block", Default::default()))],
..Default::default()
});
assert!(super::outside_unchanged(&before, &before.clone(), "someone"), "an unchanged glossary is unchanged");
let mut after = before.clone();
after.glossary[0].blocks[0] =
wordcraft_doc::para_block(Paragraph::with_text("Block", CharProps { lang: Some("fr-FR".into()), ..Default::default() }));
assert!(!super::outside_unchanged(&before, &after, "someone"), "a relanguaged building block is a change");
}
/// Read only, no exceptions: going to a header the document doesn't have doesn't create
/// one, and loading or filtering recipients doesn't rewrite the merge fields' shown results
/// (both used to change the document from a non-mutating command, #1327).
+86 -3
View File
@@ -1,4 +1,5 @@
use super::{Arc, CmdError, CmdResult, Document, Pos, Selection, Session, StoryRef, Value, delete_selection, json, p, sel_result};
use wordcraft_doc::CharProps;
/// Options › Language › Set as default: only the saved default proofing language (what future
/// blank documents are written in), as Word's Set as Preferred. A setting, like `file.options`: the
@@ -14,8 +15,19 @@ pub(super) fn preferred_language(s: &mut Session, v: &Value) -> CmdResult {
/// Set Proofing Language: the selection's language and "do not check spelling or grammar",
/// or (`default`) the document's default and the saved language for future blank documents;
/// `detect` is the per-user detection preference.
/// Nothing at all sets US English, as before.
/// Nothing at all sets US English, as before. `scope: "document"` sets it for every story.
pub(super) fn language(s: &mut Session, v: &Value) -> CmdResult {
// Checked first, so a bad scope changes nothing (not even the detect preference).
let whole_document = match v.get("scope") {
None | Some(Value::Null) => false,
Some(Value::String(t)) if t == "selection" => false,
Some(Value::String(t)) if t == "document" => true,
Some(other) => return Err(CmdError::Params(format!("`scope` must be \"selection\" or \"document\", not {other}"))),
};
// Protection leaves only its exceptions editable, so the whole document can't be one.
if whole_document && let Some(mode) = s.doc.settings.protection.as_deref() {
return Err(CmdError::Disabled(format!("review.language: stop protection ({mode}) before changing the whole document's proofing language")));
}
let lang = match p::str(v, "lang") {
Some(t) => Some(
wordcraft_proof::lang::normalize_tag(t)
@@ -45,20 +57,91 @@ pub(super) fn language(s: &mut Session, v: &Value) -> CmdResult {
if lang.is_none() && no_proof.is_none() {
return Ok(json!({"detect": s.prefs.detect_language}));
}
let result = crate::cmd::format::apply(s, &|c| {
let change = |c: &mut CharProps| {
if let Some(l) = &lang {
c.lang = Some(l.clone());
}
if let Some(np) = no_proof {
c.no_proof = Some(np);
}
})?;
};
let result = if whole_document {
let glossary_skipped = set_document_props(s, &change)?;
// The same caret/selection result as the selection path (the selection is untouched).
let mut r = sel_result(s)?;
if let Some(m) = r.as_object_mut() {
m.insert("scope".into(), json!("document"));
if glossary_skipped {
m.insert("glossarySkipped".into(), json!(true));
}
}
r
} else {
crate::cmd::format::apply(s, &change)?
};
if p::bool(v, "default") == Some(true) {
s.prefs.default_language = lang;
}
Ok(result)
}
/// Apply `f` to the character formatting of every story of the document (Language dialog, "Apply
/// to the whole document"): text and paragraph marks of the body, headers, footers, notes,
/// comments, text boxes (all `Document::parts`), table cells, and the glossary's building blocks.
/// The selection is untouched; formatting waiting for typing follows.
///
/// Glossary blocks are left alone while Track Changes and Track Formatting are both on: tracked
/// formatting (`fmt_revisions::record`) compares only the body and the parts, so a glossary change
/// would be an untracked edit. So those blocks keep their old language while tracking; the caller
/// reports it (`glossarySkipped`). Returns whether the glossary was skipped.
fn set_document_props(s: &mut Session, f: &dyn Fn(&mut CharProps)) -> Result<bool, CmdError> {
let stories: Vec<StoryRef> = std::iter::once(StoryRef::Body).chain(s.doc.parts.keys().map(|k| StoryRef::Part(*k))).collect();
for story in stories {
for path in s.doc.para_paths(story) {
let para = s.doc.para_mut(story, &path)?;
let len = para.len();
para.format(0, len, f)?;
f(&mut para.mark);
para.touch();
}
}
let skipped = s.doc.settings.track_changes && s.prefs.markup.track_formatting;
if !skipped {
for block in &mut s.doc.glossary {
format_blocks(&mut block.blocks, f, 0);
}
}
if let Some(pend) = s.pending.as_mut() {
f(pend);
}
Ok(skipped)
}
/// [`set_document_props`] for a block list outside any story (depth-limited like `para_paths`).
fn format_blocks(blocks: &mut wordcraft_doc::Blocks, f: &dyn Fn(&mut CharProps), depth: usize) {
if depth > wordcraft_doc::PARA_WALK_DEPTH {
return;
}
for blk in blocks.iter_mut() {
match Arc::make_mut(blk) {
wordcraft_doc::Block::Para(p) => {
let len = p.len();
// A range inside the paragraph can't fail; the mark is formatted regardless.
let _ = p.format(0, len, f);
f(&mut p.mark);
p.touch();
}
wordcraft_doc::Block::Table(t) => {
for row in &mut t.rows {
for cell in &mut row.cells {
format_blocks(&mut cell.blocks, f, depth + 1);
}
}
}
}
}
}
pub(super) fn macros(s: &mut Session, v: &Value) -> CmdResult {
if let Some(d) = v.get("define") {
let name = d.get("name").and_then(Value::as_str).unwrap_or("Macro").to_string();
+1 -1
View File
@@ -340,7 +340,7 @@ pub fn specs() -> Vec<CommandSpec> {
})
.params(r#"{"format": "decimal|upperRoman|lowerLetter…", "text"?: "%1.", "start"?: n}"#),
CommandSpec::new("review.language", "Language", "Review › Language", language).params(
r#"{"lang"?: "en-US|en-GB|pl-PL|fr-FR|…" (BCP 47; default en-US), "noProof"?: bool, "detect"?: bool (detect language automatically, a preference), "default"?: bool (also the document's default and the saved language for future blank documents)}"#,
r#"{"lang"?: "en-US|en-GB|pl-PL|fr-FR|…" (BCP 47; default en-US), "noProof"?: bool, "detect"?: bool (detect language automatically, a preference), "default"?: bool (also the document's default and the saved language for future blank documents), "scope"?: "selection" (default) | "document" (every run and paragraph mark of every story: body, headers, footers, notes, comments, text boxes, tables, glossary (skipped while Track Changes and Track Formatting are on); one undo step, selection unchanged; returns the caret, "scope":"document" and "glossarySkipped":true when the glossary was skipped)}"#,
),
CommandSpec::new("review.language.preferred", "Set as Default Language", "File › Options › Language", preferred_language)
.params(r#"{"lang": "en-US|en-GB|pl-PL|nl-NL|…" (BCP 47)} — only the saved default proofing language, what future blank documents are written in, as Options › Language › Set as default does; the open document, the selection and the undo history don't change. Returns {"preferred": tag}."#)
+147
View File
@@ -903,3 +903,150 @@ fn inspect_removals_work_when_the_document_does_not_track_changes() {
assert!(!text.contains("Hidden"), "the hidden text is still there: {text}");
assert!(text.contains("Visible text."), "{text}");
}
/// #3518: every run and paragraph mark of a story, as (story, path, lang, noProof) rows.
fn proofing_rows(s: &Session) -> Vec<(StoryRef, Option<String>, Option<bool>)> {
let stories = std::iter::once(StoryRef::Body).chain(s.doc.parts.keys().map(|k| StoryRef::Part(*k)));
let mut out = Vec::new();
for st in stories {
for path in s.doc.para_paths(st) {
let Some(p) = s.doc.para(st, &path) else { continue };
out.push((st, p.mark.lang.clone(), p.mark.no_proof));
out.extend(p.runs.iter().map(|r| (st, r.props.lang.clone(), r.props.no_proof)));
}
}
out
}
/// A document with its text in German in the body, a table cell, a header, a footnote, a comment
/// and a text box, as a Word DOCX keeps a `w:lang` on each run, plus a glossary entry.
fn multi_story_doc() -> Session {
use wordcraft_doc::{Block, BuildingBlock, CharProps, Paragraph, PartKind, Table};
let de = || CharProps { lang: Some("de-DE".into()), ..Default::default() };
let blk = |t: &str| Arc::new(Block::Para(Paragraph::with_text(t, de())));
let mut d = Document::from_text("Guten Tag");
d.body = vec![blk("Guten Tag")];
let mut t = Table::new(1, 2, 200.0);
if let Some(c) = t.rows.first_mut().and_then(|r| r.cells.first_mut()) {
c.blocks = vec![blk("Zelle")];
}
d.body.push(Arc::new(Block::Table(t)));
d.body.push(blk("Ende"));
for kind in [PartKind::Header, PartKind::Footnote, PartKind::Comment, PartKind::TextBox] {
d.add_part(kind, vec![blk("Teil")]);
}
d.glossary.push(BuildingBlock { name: "g".into(), blocks: vec![blk("Baustein")], ..Default::default() });
Session::new(d)
}
#[test]
fn language_scope_document_sets_every_story() {
let mut s = multi_story_doc();
s.run("select.text", &json!({"text": "Guten"})).unwrap();
let (sel, before) = (s.sel.clone(), s.doc.clone());
let rows = proofing_rows(&s);
assert!(rows.len() >= 10 && rows.iter().any(|r| r.1.as_deref() == Some("de-DE")));
s.run("review.language", &json!({"lang": "fr-FR", "scope": "document"})).unwrap();
// Runs that had their own language, the paragraph marks and the empty cell: all French.
let rows = proofing_rows(&s);
assert!(rows.iter().all(|r| r.1.as_deref() == Some("fr-FR")), "{rows:?}");
for kind_story in s.doc.parts.keys() {
assert!(rows.iter().any(|r| r.0 == StoryRef::Part(*kind_story)));
}
assert!(s.doc.plain_text(StoryRef::Body).contains("Zelle"));
let g = &s.doc.glossary[0].blocks;
assert_eq!(g[0].as_para().map(|p| p.runs[0].props.lang.clone()), Some(Some("fr-FR".into())));
assert_eq!(g[0].as_para().map(|p| p.mark.lang.clone()), Some(Some("fr-FR".into())));
// The selection stays; the document is modified.
assert_eq!(s.sel, sel);
assert!(s.doc != before);
// One undo restores everything.
s.run("edit.undo", &json!({})).unwrap();
assert!(s.doc == before);
assert_eq!(s.sel, sel);
}
#[test]
fn language_scope_document_no_proof_and_pending() {
let mut s = multi_story_doc();
s.run("review.language", &json!({"noProof": true, "scope": "document"})).unwrap();
assert!(proofing_rows(&s).iter().all(|r| r.2 == Some(true)));
// The language itself wasn't asked for and stays.
assert!(proofing_rows(&s).iter().any(|r| r.1.as_deref() == Some("de-DE")));
// Formatting waiting for typing follows.
s.run("format.bold", &json!({})).unwrap();
s.run("review.language", &json!({"lang": "pl-PL", "scope": "document"})).unwrap();
assert_eq!(s.pending.as_ref().and_then(|p| p.lang.as_deref()), Some("pl-PL"));
}
/// Document scope returns the caret/selection like the selection path, plus the scope.
#[test]
fn language_scope_document_returns_the_selection_result() {
let mut s = multi_story_doc();
s.run("select.text", &json!({"text": "Guten"})).unwrap();
let out = s.run("review.language", &json!({"lang": "fr-FR", "scope": "document"})).unwrap();
assert_eq!(out["scope"], "document");
assert_eq!(out["anchor"], crate::cmd::pos_json(&s.sel.anchor), "{out}");
assert_eq!(out["focus"], crate::cmd::pos_json(&s.sel.focus), "{out}");
}
/// Tracked formatting records only the body and parts, so while it is on the glossary (outside
/// any story) is left alone instead of changing untracked; with tracking off it changes.
#[test]
fn language_scope_document_skips_glossary_while_tracking_formatting() {
let gloss = |s: &Session| s.doc.glossary[0].blocks[0].as_para().map(|p| (p.runs[0].props.lang.clone(), p.mark.lang.clone()));
let mut s = multi_story_doc();
s.run("review.trackChanges", &json!({"value": true})).unwrap();
s.run("review.trackingOptions", &json!({"trackFormatting": true})).unwrap();
let out = s.run("review.language", &json!({"lang": "fr-FR", "scope": "document"})).unwrap();
assert_eq!(out["glossarySkipped"], true, "{out}");
assert_eq!(gloss(&s), Some((Some("de-DE".into()), Some("de-DE".into()))));
assert!(proofing_rows(&s).iter().all(|r| r.1.as_deref() == Some("fr-FR")));
assert!(s.doc.revisions.iter().any(|r| r.kind == wordcraft_doc::RevisionKind::Format), "the body change is tracked");
let mut s = multi_story_doc();
s.run("review.trackChanges", &json!({"value": true})).unwrap();
s.run("review.trackingOptions", &json!({"trackFormatting": false})).unwrap();
let out = s.run("review.language", &json!({"lang": "fr-FR", "scope": "document"})).unwrap();
assert!(out.get("glossarySkipped").is_none(), "{out}");
assert_eq!(gloss(&s), Some((Some("fr-FR".into()), Some("fr-FR".into()))));
}
#[test]
fn language_default_scope_is_selection_only() {
let mut s = multi_story_doc();
s.run("select.text", &json!({"text": "Guten"})).unwrap();
s.run("review.language", &json!({"lang": "fr-FR"})).unwrap();
let rows = proofing_rows(&s);
assert!(rows.iter().any(|r| r.1.as_deref() == Some("fr-FR")));
assert!(rows.iter().filter(|r| r.1.as_deref() == Some("fr-FR")).count() < rows.len() / 2);
let mut s = multi_story_doc();
s.run("select.text", &json!({"text": "Guten"})).unwrap();
s.run("review.language", &json!({"lang": "fr-FR", "scope": "selection"})).unwrap();
assert_eq!(proofing_rows(&s), rows);
}
#[test]
fn language_bad_scope_is_a_params_error() {
let mut s = multi_story_doc();
let before = s.doc.clone();
for bad in [json!("everything"), json!(1), json!(true), json!(["document"])] {
let e = s.run("review.language", &json!({"lang": "fr-FR", "detect": false, "scope": bad})).unwrap_err();
assert!(matches!(e, CmdError::Params(_)), "{e:?}");
}
assert!(s.doc == before);
assert!(s.prefs.detect_language);
}
/// Document scope is refused under editing protection, before anything changes.
#[test]
fn language_document_scope_is_refused_under_protection() {
for mode in ["readOnly", "comments", "forms"] {
let mut s = multi_story_doc();
s.doc.settings.protection = Some(mode.into());
let before = s.doc.clone();
let e = s.run("review.language", &json!({"lang": "fr-FR", "detect": false, "scope": "document"})).unwrap_err();
assert!(matches!(e, CmdError::Disabled(_)), "{mode}: {e:?}");
assert!(s.doc == before, "{mode}: nothing changed");
assert!(s.prefs.detect_language, "{mode}: the detect preference is untouched");
}
}
+4
View File
@@ -88,6 +88,10 @@ pub struct Session {
pub initials: String,
/// Format painter: copied formatting waiting to be applied (and whether it stays on).
pub painter: Option<(CharProps, wordcraft_doc::props::ParaProps, bool)>,
/// Formatting picked up by Copy Formatting (Mod+Shift+C): Paste Formatting applies it as often
/// as asked, as in Word, until the next Copy Formatting. A Format Painter pick is stored here
/// as well.
pub copied_format: Option<(CharProps, wordcraft_doc::props::ParaProps)>,
/// Last message for the status bar / agents.
pub status: String,
/// Headers/footers `insert.createHeader`/`insert.createFooter` made for a page that had none
+1
View File
@@ -259,6 +259,7 @@ impl Session {
author: _,
initials: _,
painter: _,
copied_format: _,
// What the drawn window knows of the others: its front end sets it as it draws.
windows: _,
status: _,
+1
View File
@@ -109,6 +109,7 @@ impl Session {
author: "WordCraft User".into(),
initials: String::new(),
painter: None,
copied_format: None,
status: String::new(),
new_header_parts,
hf_return,
+1
View File
@@ -92,6 +92,7 @@ impl Session {
author: _,
initials: _,
painter: _,
copied_format: _,
status: _,
// Headers just created to edit: closing checks they still exist and are empty.
new_header_parts: _,
+170
View File
@@ -13472,3 +13472,173 @@ fn resolving_away_an_empty_paragraph_with_a_section_break_keeps_the_next_paragra
assert_eq!(s.doc.last_section.margin_left, 72.0, "{cmd}: the following section's setup stays");
}
}
/// #5616: Copy Formatting's formatting stays for every Paste Formatting, as in Word; it doesn't
/// arm the one-shot Format Painter brush.
#[test]
fn copied_formatting_pastes_again_and_again() {
let mut s = s();
run(&mut s, "document.setText", json!({"text": "Bold one two"}));
run(&mut s, "select.text", json!({"text": "Bold"}));
run(&mut s, "format.bold", json!({}));
run(&mut s, "edit.copyFormat", json!({}));
assert!(s.painter.is_none());
for word in ["one", "two"] {
run(&mut s, "select.text", json!({"text": word}));
run(&mut s, "edit.pasteFormat", json!({}));
assert_eq!(s.run("format.state", &json!({})).unwrap()["bold"], json!(true), "{word}");
}
assert_eq!(s.doc.plain_text(wordcraft_doc::StoryRef::Body), "Bold one two");
}
/// #5616: Copy Formatting and the Format Painter share one format buffer: each replaces the other,
/// so a used-up brush never hands over to older copied formatting.
#[test]
fn copy_formatting_and_the_format_painter_replace_each_other() {
let mut s = s();
run(&mut s, "document.setText", json!({"text": "Bold one two"}));
run(&mut s, "select.text", json!({"text": "Bold"}));
run(&mut s, "format.bold", json!({}));
run(&mut s, "edit.formatPainter", json!({}));
assert!(s.painter.is_some());
run(&mut s, "edit.copyFormat", json!({}));
assert!(s.painter.is_none(), "Copy Formatting clears an armed brush");
assert!(s.copied_format.is_some());
run(&mut s, "edit.formatPainter", json!({}));
assert!(s.painter.is_some());
run(&mut s, "select.text", json!({"text": "one"}));
run(&mut s, "edit.pasteFormat", json!({}));
assert!(s.painter.is_none(), "a used-up brush is gone");
assert!(s.copied_format.is_some(), "its pick stays for Paste Formatting");
}
/// #5616: arming and cancelling the Format Painter leaves Copy Formatting's pick; a brush's pick
/// is what Paste Formatting applies next.
#[test]
fn cancelling_the_format_painter_keeps_the_copied_formatting() {
let mut s = s();
run(&mut s, "document.setText", json!({"text": "Bold one two"}));
run(&mut s, "select.text", json!({"text": "Bold"}));
run(&mut s, "format.bold", json!({}));
run(&mut s, "edit.copyFormat", json!({}));
run(&mut s, "edit.formatPainter", json!({}));
run(&mut s, "edit.formatPainter", json!({}));
assert!(s.painter.is_none());
run(&mut s, "select.text", json!({"text": "one"}));
run(&mut s, "edit.pasteFormat", json!({}));
assert_eq!(s.run("format.state", &json!({})).unwrap()["bold"], json!(true));
// A brush picked from plain text replaces the bold pick.
run(&mut s, "select.text", json!({"text": "two"}));
run(&mut s, "edit.formatPainter", json!({}));
run(&mut s, "select.text", json!({"text": "Bold"}));
run(&mut s, "edit.pasteFormat", json!({}));
assert_ne!(s.run("format.state", &json!({})).unwrap()["bold"], json!(true));
}
/// #5616: copied formatting carries no tracked paragraph formatting or numbering change.
#[test]
fn copied_paragraph_formatting_carries_no_tracked_changes() {
let mut s = s();
run(&mut s, "document.setText", json!({"text": "one\ntwo"}));
run(&mut s, "review.trackChanges", json!({"value": true}));
run(&mut s, "select.text", json!({"text": "one"}));
run(&mut s, "para.alignCenter", json!({}));
run(&mut s, "review.trackChanges", json!({"value": false}));
run(&mut s, "select.text", json!({"text": "one"}));
let f = s.sel.focus.clone();
assert!(s.doc.para_at(&f).unwrap().props.fmt_change.is_some(), "the source paragraph has a tracked formatting change");
run(&mut s, "edit.copyFormat", json!({}));
let (_, para) = s.copied_format.clone().unwrap();
assert!(para.fmt_change.is_none() && para.num_change.is_none());
run(&mut s, "select.text", json!({"text": "two"}));
run(&mut s, "edit.pasteFormat", json!({}));
let f = s.sel.focus.clone();
let p = s.doc.para_at(&f).unwrap().props.clone();
assert!(p.fmt_change.is_none() && p.num_change.is_none());
}
/// #5616: copied formatting carries no hyperlink or revision marks, even into a collapsed caret.
#[test]
fn copied_formatting_carries_no_hyperlink() {
let mut s = s();
run(&mut s, "document.setText", json!({"text": "source target"}));
run(&mut s, "select.text", json!({"text": "source"}));
run(&mut s, "format.bold", json!({}));
run(&mut s, "insert.link", json!({"url": "https://example.com/"}));
run(&mut s, "select.text", json!({"text": "so"}));
run(&mut s, "edit.copyFormat", json!({}));
let (chr, _) = s.copied_format.clone().unwrap();
assert_eq!(chr.bold, Some(true));
assert!(chr.link.is_none() && chr.ins.is_none() && chr.del.is_none() && chr.fmt_change.is_none());
run(&mut s, "select.text", json!({"text": "target"}));
run(&mut s, "select.collapse", json!({}));
run(&mut s, "caret.left", json!({}));
run(&mut s, "edit.pasteFormat", json!({}));
let f = s.sel.focus.clone();
let link = s.doc.para_at(&f).map(|p| p.props_of_char(f.off).link.clone());
assert_eq!(link, Some(None), "the target didn't become a link");
}
/// #5616: Paste Formatting at a bare caret keeps the word's own hyperlink and tracked insertion.
#[test]
fn a_caret_paste_formatting_keeps_the_targets_link_and_tracked_marks() {
let mut s = s();
run(&mut s, "document.setText", json!({"text": "source target"}));
run(&mut s, "select.text", json!({"text": "source"}));
run(&mut s, "format.bold", json!({}));
run(&mut s, "edit.copyFormat", json!({}));
run(&mut s, "select.text", json!({"text": "target"}));
run(&mut s, "insert.link", json!({"url": "https://example.com/"}));
run(&mut s, "select.collapse", json!({}));
run(&mut s, "caret.right", json!({}));
run(&mut s, "edit.pasteFormat", json!({}));
let at_caret = |s: &Session| {
let f = s.sel.focus.clone();
s.doc.para_at(&f).map(|p| p.props_of_char(f.off).clone()).unwrap_or_default()
};
let c = at_caret(&s);
assert!(c.link.is_some(), "the target kept its hyperlink");
assert_eq!(c.bold, Some(true));
// A tracked insertion stays tracked.
run(&mut s, "caret.docEnd", json!({}));
run(&mut s, "review.trackChanges", json!({"value": true}));
run(&mut s, "text.insert", json!({"text": " added"}));
run(&mut s, "review.trackChanges", json!({"value": false}));
run(&mut s, "caret.left", json!({}));
assert!(at_caret(&s).ins.is_some(), "the insertion is tracked before");
run(&mut s, "edit.pasteFormat", json!({}));
assert!(at_caret(&s).ins.is_some(), "Paste Formatting kept the insertion mark");
}
/// #5616: Paste Formatting over a selection keeps the target's hyperlink and tracked marks too.
#[test]
fn a_range_paste_formatting_keeps_the_targets_link_and_tracked_marks() {
let mut s = s();
run(&mut s, "document.setText", json!({"text": "source target"}));
run(&mut s, "select.text", json!({"text": "source"}));
run(&mut s, "format.bold", json!({}));
run(&mut s, "edit.copyFormat", json!({}));
run(&mut s, "select.text", json!({"text": "target"}));
run(&mut s, "insert.link", json!({"url": "https://example.com/"}));
run(&mut s, "select.text", json!({"text": "target"}));
run(&mut s, "edit.pasteFormat", json!({}));
let (a, _) = s.sel.ordered();
let c = s.doc.para_at(&a).map(|p| p.props_of_char(a.off).clone()).unwrap_or_default();
assert!(c.link.is_some(), "the target kept its hyperlink");
assert_eq!(c.bold, Some(true));
// A tracked insertion selected as a range stays tracked.
run(&mut s, "caret.docEnd", json!({}));
run(&mut s, "review.trackChanges", json!({"value": true}));
run(&mut s, "text.insert", json!({"text": " added"}));
run(&mut s, "review.trackChanges", json!({"value": false}));
run(&mut s, "select.text", json!({"text": "added"}));
let at_start = |s: &Session| {
let (a, _) = s.sel.ordered();
s.doc.para_at(&a).map(|p| p.props_of_char(a.off).clone()).unwrap_or_default()
};
assert!(at_start(&s).ins.is_some(), "the insertion is tracked before");
run(&mut s, "edit.pasteFormat", json!({}));
let c = at_start(&s);
assert!(c.ins.is_some(), "Paste Formatting kept the insertion mark");
assert_eq!(c.bold, Some(true));
}
+2 -1
View File
@@ -10,9 +10,10 @@ workspace = true
[features]
# Picture decoding within a memory budget (`picture`), for the crates that decode pictures.
image = ["dep:image", "dep:craft-image-codecs"]
image = ["dep:image", "dep:craft-image-codecs", "dep:craft-tiff"]
[dependencies]
craft-image-codecs = { workspace = true, optional = true }
craft-tiff = { workspace = true, optional = true }
image = { workspace = true, optional = true }
serde = { workspace = true }
+24 -20
View File
@@ -1,5 +1,4 @@
//! WordCraft geometry and units.
//!
//! Layout works in **points** (1/72 inch, `f32`). File formats use other units: OOXML uses
//! twentieths of a point (twips) for most lengths, half-points for font sizes, eighths of a point
//! for borders and English Metric Units (EMU, 914 400 per inch) for drawings. The conversions live
@@ -25,26 +24,32 @@ pub const EMU_PER_PT: f32 = 12_700.0;
pub const PT_PER_CM: f32 = 72.0 / 2.54;
/// Twips → points.
#[expect(clippy::cast_precision_loss, reason = "The f32 return type intentionally rounds i64 inputs to f32 precision.")]
pub fn twips(v: i64) -> f32 {
v as f32 / TWIPS_PER_PT
}
/// Points → twips (rounded).
#[expect(clippy::cast_possible_truncation, reason = "The value is rounded first; Rust's float-to-integer cast saturates outside the i64 range.")]
pub fn to_twips(pt: f32) -> i64 {
finite(pt * TWIPS_PER_PT).round() as i64
}
/// EMU → points.
#[expect(clippy::cast_precision_loss, reason = "The f32 return type intentionally rounds i64 inputs to f32 precision.")]
pub fn emu(v: i64) -> f32 {
v as f32 / EMU_PER_PT
}
/// Points → EMU (rounded).
#[expect(clippy::cast_possible_truncation, reason = "The value is rounded first; Rust's float-to-integer cast saturates outside the i64 range.")]
pub fn to_emu(pt: f32) -> i64 {
(finite(pt) as f64 * EMU_PER_PT as f64).round() as i64
(f64::from(finite(pt)) * f64::from(EMU_PER_PT)).round() as i64
}
/// Half-points (OOXML font sizes) → points.
#[expect(clippy::cast_precision_loss, reason = "The f32 return type intentionally rounds i64 inputs to f32 precision.")]
pub fn half_points(v: i64) -> f32 {
v as f32 / 2.0
}
/// Points → half-points (rounded).
#[expect(clippy::cast_possible_truncation, reason = "The value is rounded first; Rust's float-to-integer cast saturates outside the i64 range.")]
pub fn to_half_points(pt: f32) -> i64 {
(finite(pt) * 2.0).round() as i64
}
@@ -123,8 +128,7 @@ pub fn parse_measure(s: &str, default: Unit) -> Option<f32> {
"cm" => PT_PER_CM,
"mm" => PT_PER_CM / 10.0,
"pt" | "pts" | "point" | "points" => 1.0,
"pi" | "pc" | "pica" | "picas" => 12.0,
"li" | "line" | "lines" => 12.0,
"pi" | "pc" | "pica" | "picas" | "li" | "line" | "lines" => 12.0,
"px" => 0.75,
_ => return None,
};
@@ -198,7 +202,7 @@ pub fn normalize_degrees(deg: f32) -> f32 {
}
/// How a drawing is turned about its centre: mirrored first (`flip_h` left to right, `flip_v` top
/// to bottom), then rotated `deg` degrees clockwise (page space, y down), as DrawingML's `a:xfrm`
/// to bottom), then rotated `deg` degrees clockwise (page space, y down), as `DrawingML`'s `a:xfrm`
/// `flipH`, `flipV` and `rot` say (ECMA-376 §20.1.7.6).
#[derive(Clone, Copy, Debug, PartialEq, Default)]
pub struct Spin {
@@ -219,7 +223,7 @@ impl Spin {
}
/// The linear part (a, b, c, d: x' = a·x + c·y, y' = b·x + d·y).
fn linear(&self) -> [f32; 4] {
fn linear(self) -> [f32; 4] {
let r = normalize_degrees(self.deg).to_radians();
let (s, c) = r.sin_cos();
let fx = if self.flip_h { -1.0 } else { 1.0 };
@@ -237,17 +241,17 @@ impl Spin {
/// Where point (`x`, `y`) goes when turned about (`cx`, `cy`).
pub fn apply(&self, cx: f32, cy: f32, x: f32, y: f32) -> (f32, f32) {
let [a, b, c, d] = self.linear();
let (u, v) = (x - cx, y - cy);
(cx + a * u + c * v, cy + b * u + d * v)
let [x_from_x, y_from_x, x_from_y, y_from_y] = self.linear();
let (relative_x, relative_y) = (x - cx, y - cy);
(cx + x_from_x * relative_x + x_from_y * relative_y, cy + y_from_x * relative_x + y_from_y * relative_y)
}
/// The point that [`Spin::apply`] takes to (`x`, `y`).
pub fn unapply(&self, cx: f32, cy: f32, x: f32, y: f32) -> (f32, f32) {
// The linear part is orthogonal: its inverse is its transpose.
let [a, b, c, d] = self.linear();
let (u, v) = (x - cx, y - cy);
(cx + a * u + b * v, cy + c * u + d * v)
let [x_from_x, y_from_x, x_from_y, y_from_y] = self.linear();
let (relative_x, relative_y) = (x - cx, y - cy);
(cx + x_from_x * relative_x + y_from_x * relative_y, cy + x_from_y * relative_x + y_from_y * relative_y)
}
/// The axis-aligned box `r` covers once turned about its centre.
@@ -258,10 +262,10 @@ impl Spin {
/// The width and height of the box a `w` × `h` rectangle covers once turned.
pub fn extent(&self, w: f32, h: f32) -> (f32, f32) {
let (w, h) = (finite(w).abs(), finite(h).abs());
let r = normalize_degrees(self.deg).to_radians();
let (s, c) = (r.sin().abs(), r.cos().abs());
(w * c + h * s, w * s + h * c)
let (width, height) = (finite(w).abs(), finite(h).abs());
let radians = normalize_degrees(self.deg).to_radians();
let (sine, cosine) = (radians.sin().abs(), radians.cos().abs());
(width * cosine + height * sine, width * sine + height * cosine)
}
/// This spin applied inside `outer` (a group member's own spin within its group's): the one
@@ -343,11 +347,11 @@ mod tests {
#[test]
fn unit_round_trips() {
assert_eq!(twips(1440), 72.0);
assert_eq!(twips(1440).to_bits(), 72.0f32.to_bits());
assert_eq!(to_twips(72.0), 1440);
assert_eq!(emu(914_400), 72.0);
assert_eq!(emu(914_400).to_bits(), 72.0f32.to_bits());
assert_eq!(to_emu(72.0), 914_400);
assert_eq!(half_points(24), 12.0);
assert_eq!(half_points(24).to_bits(), 12.0f32.to_bits());
assert_eq!(to_half_points(10.5), 21);
assert_eq!(to_twips(f32::NAN), 0);
}
@@ -429,7 +433,7 @@ mod tests {
assert!(a.intersects(&b));
assert_eq!(a.union(&b), Rect::new(0.0, 0.0, 15.0, 15.0));
assert!(a.contains(Point::new(5.0, 5.0)));
assert_eq!(Rect::new(0.0, 0.0, -5.0, f32::NAN).w, 0.0);
assert_eq!(Rect::new(0.0, 0.0, -5.0, f32::NAN).w.to_bits(), 0.0f32.to_bits());
assert_eq!(a.inset(1.0, 2.0, 3.0, 4.0), Rect::new(1.0, 2.0, 6.0, 4.0));
}
+29 -33
View File
@@ -20,9 +20,9 @@ pub enum Refusal {
NotAPicture,
/// A kind of picture that is never decoded, because its decoder can't be held to a budget.
Unsupported(&'static str),
/// Decoding it would take more memory than the budget.
/// Decoding would exceed the memory budget or size arithmetic overflowed.
TooLarge { width: u32, height: u32 },
/// The header or the data is damaged.
/// The header or data is damaged, or the decoder rejects the input.
Broken(String),
}
@@ -179,11 +179,19 @@ pub struct Probe<'a> {
}
/// TIFF compressions decoded within the caller's limits: none, CCITT Group 4, LZW, Deflate (both
/// codes) and PackBits. The `tiff` crate decodes a JPEG strip (7) with a decoder of its own and
/// codes) and `PackBits`. The `tiff` crate decodes a JPEG strip (7) with a decoder of its own and
/// default limits, whatever size the TIFF declares, so such a TIFF is not decoded (#3645).
const TIFF_COMPRESSIONS: [u16; 6] = [1, 4, 5, 8, 32946, 32773];
/// Read a picture's header: PNG, JPEG, GIF, WebP, BMP or TIFF.
///
/// # Errors
///
/// Returns `Refusal::NotAPicture` for an unsupported format, `Refusal::Unsupported` for a TIFF
/// whose compression cannot be read or budgeted (including truncation that prevents reading
/// its compression metadata), `Refusal::TooLarge`
/// on size arithmetic overflow, and `Refusal::Broken` for other header or inspection errors,
/// including TIFF errors after compression metadata is accepted.
pub fn probe(bytes: &[u8]) -> Result<Probe<'_>, Refusal> {
let codec_fmt = detect(bytes).ok_or(Refusal::NotAPicture)?;
let format = from_codec_format(codec_fmt).ok_or(Refusal::NotAPicture)?;
@@ -287,6 +295,11 @@ fn dib_to_bmp(dib: &[u8]) -> Vec<u8> {
/// Read a DIB's header: a BMP without its 14-byte file header, as the Windows clipboard holds
/// one (`CF_DIB`, `CF_DIBV5`). Its layout is first made the one the decoder reads (see
/// [`dib_layout`]).
///
/// # Errors
///
/// Returns `Refusal::Broken` for an invalid DIB header and `Refusal::TooLarge` on size arithmetic
/// overflow.
pub fn probe_dib(dib: Vec<u8>) -> Result<Probe<'static>, Refusal> {
let dib = dib_layout(dib);
let bmp = dib_to_bmp(&dib);
@@ -349,6 +362,12 @@ impl Probe<'_> {
/// Decode, refused before anything is allocated when the peak would pass `budget` bytes. The
/// decoder is held to the header's size and to `budget` as well.
///
/// # Errors
///
/// Returns `Refusal::TooLarge` when the picture does not fit `budget` or the decoder
/// exceeds its limits, `Refusal::NotAPicture` for an unsupported format, and
/// `Refusal::Broken` for other decoding or pixel-conversion errors.
pub fn decode(&self, budget: u64) -> Result<DynamicImage, Refusal> {
if !self.fits(budget) {
return Err(Refusal::TooLarge { width: self.width, height: self.height });
@@ -364,6 +383,10 @@ impl Probe<'_> {
}
/// [`probe`], then [`Probe::decode`] within `budget` bytes.
///
/// # Errors
///
/// Returns the probing or decoding `Refusal`; see [`probe`] and [`Probe::decode`].
pub fn decode(bytes: &[u8], budget: u64) -> Result<DynamicImage, Refusal> {
probe(bytes)?.decode(budget)
}
@@ -516,36 +539,7 @@ fn worst_coefficients(bytes: &[u8]) -> u64 {
/// tag is missing. None when the header can't be read, or when the tag appears more than once:
/// the decoder keeps the last copy, so a harmless first one must not hide a JPEG one after it.
fn tiff_compression(bytes: &[u8]) -> Option<u16> {
let le = match bytes.get(..4)? {
b"II*\0" => true,
b"MM\0*" => false,
_ => return None,
};
let u16_at = |at: usize| -> Option<u16> {
let b = [*bytes.get(at)?, *bytes.get(at.checked_add(1)?)?];
Some(if le { u16::from_le_bytes(b) } else { u16::from_be_bytes(b) })
};
let u32_at = |at: usize| -> Option<u32> {
let b: [u8; 4] = bytes.get(at..at.checked_add(4)?)?.try_into().ok()?;
Some(if le { u32::from_le_bytes(b) } else { u32::from_be_bytes(b) })
};
let ifd = usize::try_from(u32_at(4)?).ok()?;
let mut found = None;
for i in 0..usize::from(u16_at(ifd)?) {
let entry = ifd.checked_add(2)?.checked_add(i.checked_mul(12)?)?;
if u16_at(entry)? != 259 {
continue;
}
if found.is_some() || u32_at(entry.checked_add(4)?)? != 1 {
return None;
}
found = Some(match u16_at(entry.checked_add(2)?)? {
3 => u16_at(entry.checked_add(8)?)?,
4 => u16::try_from(u32_at(entry.checked_add(8)?)?).ok()?,
_ => return None,
});
}
Some(found.unwrap_or(1))
craft_tiff::probe::first_image_compression(bytes)
}
/// A DIB with a V4 or V5 header in the layout the decoder reads. A 32-bit one whose alpha mask
@@ -722,6 +716,7 @@ mod tests {
let mut s = vec![8];
s.extend(h.to_be_bytes());
s.extend(w.to_be_bytes());
#[expect(clippy::cast_possible_truncation, reason = "These fixtures contain at most four three-byte component records.")]
s.push((comps.len() / 3) as u8);
s.extend(comps);
s
@@ -736,6 +731,7 @@ mod tests {
// A marker walk over SOI, an APP0 segment, SOF2, then the scan.
let mut jpeg = vec![0xFF, 0xD8, 0xFF, 0xE0, 0, 4, 0, 0, 0xFF, 0xC2];
let f = sof(64, 64, &[1, 0x11, 0]);
#[expect(clippy::cast_possible_truncation, reason = "This fixture's nine-byte frame header and length field fit u16.")]
jpeg.extend(((f.len() + 2) as u16).to_be_bytes());
jpeg.extend(&f);
jpeg.extend([0xFF, 0xDA]);
+22 -10
View File
@@ -9,7 +9,7 @@ pub const MAX_RASTER_PIXELS: u64 = 100_000_000;
/// Bytes of a `w`×`h` RGBA8 raster, None on overflow.
pub fn rgba_bytes(w: u32, h: u32) -> Option<u64> {
(w as u64).checked_mul(h as u64)?.checked_mul(4)
u64::from(w).checked_mul(u64::from(h))?.checked_mul(4)
}
/// Whether a `w`×`h` RGBA8 raster fits `budget` bytes.
@@ -29,22 +29,34 @@ pub fn decode_fits(w: u32, h: u32, budget: u64) -> bool {
/// premultiplied copy, so the peak is the larger of `native + 4` and `8` bytes a pixel.
pub fn decode_peak_fits(w: u32, h: u32, native: u64, budget: u64) -> bool {
let per_pixel = native.saturating_add(4).max(8);
w > 0 && h > 0 && (w as u64).checked_mul(h as u64).and_then(|p| p.checked_mul(per_pixel)).is_some_and(|b| b <= budget)
w > 0 && h > 0 && u64::from(w).checked_mul(u64::from(h)).and_then(|p| p.checked_mul(per_pixel)).is_some_and(|b| b <= budget)
}
/// `w`×`h` shrunk (aspect kept, each side at least 1) until it holds at most `max_pixels`.
pub fn fit_pixels(w: u32, h: u32, max_pixels: u64) -> (u32, u32) {
let (w, h) = (w.max(1), h.max(1));
let max_pixels = max_pixels.max(1);
let area = w as u64 * h as u64;
let area = u64::from(w) * u64::from(h);
if area <= max_pixels {
return (w, h);
}
let f = (max_pixels as f64 / area as f64).sqrt();
let nh = ((h as f64 * f) as u64).clamp(1, h as u64);
let nw = ((w as f64 * f) as u64).clamp(1, w as u64).min(max_pixels / nh).max(1);
let nh = nh.min(max_pixels / nw).max(1);
(nw as u32, nh as u32)
#[expect(clippy::cast_precision_loss, reason = "Floating point only approximates the scale; the integer clamps below enforce every bound.")]
let scale = (max_pixels as f64 / area as f64).sqrt();
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "The scale is finite and within 0..=1; truncation floors a positive dimension before clamping."
)]
let new_height = ((f64::from(h) * scale) as u64).clamp(1, u64::from(h));
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "The scale is finite and within 0..=1; truncation floors a positive dimension before clamping."
)]
let new_width = ((f64::from(w) * scale) as u64).clamp(1, u64::from(w)).min(max_pixels / new_height).max(1);
let new_height = new_height.min(max_pixels / new_width).max(1);
#[expect(clippy::cast_possible_truncation, reason = "Both dimensions are clamped to their original u32 values above.")]
(new_width as u32, new_height as u32)
}
#[cfg(test)]
@@ -78,9 +90,9 @@ mod tests {
fn fit_pixels_keeps_normal_sizes_and_shrinks_huge_ones() {
assert_eq!(fit_pixels(612, 792, MAX_RASTER_PIXELS), (612, 792));
let (w, h) = fit_pixels(16_000, 16_000, 1_000_000);
assert!(w as u64 * h as u64 <= 1_000_000 && w >= 900, "{w}x{h}");
assert!(u64::from(w) * u64::from(h) <= 1_000_000 && w >= 900, "{w}x{h}");
let (w, h) = fit_pixels(16_000, 1, 100);
assert!(w as u64 * h as u64 <= 100 && h == 1, "{w}x{h}");
assert!(u64::from(w) * u64::from(h) <= 100 && h == 1, "{w}x{h}");
assert_eq!(fit_pixels(0, 5, 10).0, 1);
}
}
+11 -5
View File
@@ -718,12 +718,18 @@ pub(crate) fn place_objects(ctx: &mut Ctx, req: &ObjectPlacement) -> (Vec<Placed
// (#4250). Inline objects go with their own line.
let first = l0 == 0;
let late = at.late.filter(|l| !l.placed.is_empty());
let late_lines = late.map(LateFloats::lines_here).unwrap_or_default();
for li in 0..pl.lines.len() {
// A later piece looks only at its own lines and those holding the anchors of the late floats
// it draws, in order: walking every line of the paragraph for each piece made a paragraph of
// many pages quadratic (#6757).
let (piece, mut late_lines) =
if first { (0..pl.lines.len(), Vec::new()) } else { (l0..l1.min(pl.lines.len()), late.map(LateFloats::lines_here).unwrap_or_default()) };
late_lines.retain(|li| !piece.contains(li));
late_lines.sort_unstable();
late_lines.dedup();
let (before, after) = late_lines.split_at(late_lines.partition_point(|li| *li < piece.start));
for li in before.iter().copied().chain(piece).chain(after.iter().copied()) {
crate::work::steps(1);
let in_piece = (l0..l1).contains(&li);
if !in_piece && !first && !late_lines.contains(&li) {
continue;
}
let Some(line) = pl.lines.get(li) else { continue };
for k in line.c0..line.c1 {
let Some(c) = pl.clusters.get(k) else { continue };
+7 -3
View File
@@ -292,9 +292,13 @@ fn hf_text_at(p: &Page, id: u32, x: f32, y: f32) -> bool {
_ => None,
})
.any(|(para, l0, l1, lx, ly)| {
let (Some(first), Some(last)) = (para.lines.get(*l0), para.lines.get(l1.checked_sub(1).unwrap_or(0))) else { return false };
let bottom = ly + last.top + last.height - first.top;
y >= *ly - 2.0 && y <= bottom + 2.0 && x >= *lx - 40.0 && x <= lx + last.right + 40.0
let Some(first) = para.lines.get(*l0) else { return false };
// Each line has its own band and extent: lines beside a float are shorter than the
// ones above them, and a click on a long line past a short one's end is still text.
(*l0..*l1).filter_map(|li| para.lines.get(li)).any(|l| {
let top = ly + l.top - first.top;
y >= top - 2.0 && y <= top + l.height + 2.0 && x >= lx + l.left - 40.0 && x <= lx + l.right + 40.0
})
})
}
+88
View File
@@ -914,6 +914,7 @@ fn long_word_beside_a_float(n: usize) -> Document {
/// A word with no break opportunity in it: measuring the word for every line it takes scanned
/// the whole paragraph each time, so the layout was quadratic in the word's length.
#[test]
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the time ratio")]
fn a_long_unbreakable_word_lays_out_in_linear_time() {
let (t1, tk, ratio) = layout_time_ratio(long_word_beside_a_float, 50_000, &LayoutOptions::default());
eprintln!("t(n) {t1:.4} s, t(8n) {tk:.4} s, ratio {ratio:.1}");
@@ -1134,6 +1135,7 @@ fn long_word_with_alternating_advances_beside_a_float(n: usize) -> Document {
/// A word whose advances alternate in sign lays out in linear time: the measurement that asks
/// whether it would fit the full line must not walk the word again for every line it takes.
#[test]
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the time ratio")]
fn a_word_with_alternating_advances_lays_out_in_linear_time() {
let (t1, tk, ratio) = layout_time_ratio(long_word_with_alternating_advances_beside_a_float, 50_000, &LayoutOptions::default());
eprintln!("t(n) {t1:.4} s, t(8n) {tk:.4} s, ratio {ratio:.1}");
@@ -7839,6 +7841,7 @@ fn a_no_break_space_before_a_slash_still_holds() {
}
#[test]
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the time ratio")]
fn unequal_formats_lay_out_in_linear_time() {
crate::test_fonts();
// Runs whose formats never compare equal (NaN spacing from a hostile file) each get a style;
@@ -15444,3 +15447,88 @@ fn turned_cell_float_keeps_its_along_text_offset() {
assert!((confined.y - reference.y).abs() < 0.01, "{direction:?}: {confined:?} vs {reference:?}");
}
}
/// A header paragraph beside a Square float on its last lines only: those lines are shorter than
/// the first. A click on the first line past the short last line's end is still on the header's
/// text, so a Behind Text picture under it is not grabbed there (#5601 review).
#[test]
fn header_text_covers_the_whole_width_of_a_wrapped_first_line() {
use wordcraft_doc::para::{Anchor, Float, Wrap};
let text = "Header words that wrap across the whole line and carry on over several lines of the header \
paragraph so there are three lines here and the last one is cut short by the float beside it";
let mut d = Document::new();
let id =
d.add_part(wordcraft_doc::PartKind::Header, vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text(text, Default::default()))]);
d.last_section.headers.default = Some(id);
let at = |off| Pos::new(wordcraft_doc::StoryRef::Part(id), wordcraft_doc::Path(vec![0]), off);
// The Square float narrows the lines below the first two, on the right.
let square = Float { wrap: Wrap::Square, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, x: 300.0, y: 30.0, ..Default::default() };
d.insert_object(&at(0), rect_shape(160.0, 80.0, square), &Default::default()).unwrap();
// The Behind Text picture lies under the first line, past where the last line ends.
let behind = Float { wrap: Wrap::BehindText, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, x: 340.0, y: 0.0, ..Default::default() };
d.insert_object(&at(0), rect_shape(120.0, 20.0, behind), &Default::default()).unwrap();
let l = lay(&d);
let page = &l.pages[0];
let lines: Vec<_> = page
.header
.iter()
.filter_map(|it| match it {
Placed::Lines { para, l0, l1, x, y, .. } => {
Some((*x, *y, (*l0..*l1).filter_map(|i| para.lines.get(i)).map(|l| (l.top, l.height, l.right)).collect::<Vec<_>>()))
}
_ => None,
})
.collect();
let (x, y, ls) = lines.first().expect("header lines").clone();
let (first, last) = (ls.first().expect("first"), ls.last().expect("last"));
assert!(last.2 + 40.0 < first.2 - 20.0, "the last line is shorter than the first: {ls:?}");
let (px, py) = (x + first.2 - 15.0, y + first.0 + first.1 / 2.0);
assert!(l.object_at_in(0, px, py, 0.0, wordcraft_doc::StoryRef::Part(id)).is_none(), "on the first line's text, not the picture: {lines:?}");
}
/// `Line::left`/`right` are the edges available to a line, not where its ink sits: a centred or
/// right-aligned header line covers the Behind Text picture across its whole band, so a click in
/// the empty space beside its text is still on the header text. Beyond the band (an indent, or
/// beside a float) and 40pt of slack the picture is hit (#5601 review).
#[test]
fn header_text_covers_the_whole_band_of_centred_and_right_lines() {
use wordcraft_doc::Align;
use wordcraft_doc::para::{Anchor, Float, Wrap};
for align in [Align::Center, Align::Right] {
let mut d = Document::new();
let mut p = wordcraft_doc::Paragraph::with_text("Header", Default::default());
p.props.align = Some(align);
p.props.indent_left = Some(150.0);
let id = d.add_part(wordcraft_doc::PartKind::Header, vec![wordcraft_doc::para_block(p)]);
d.last_section.headers.default = Some(id);
let story = wordcraft_doc::StoryRef::Part(id);
let at = Pos::new(story, wordcraft_doc::Path(vec![0]), 0);
// A Behind Text picture across the whole text width, level with the header line.
let behind = Float { wrap: Wrap::BehindText, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, x: 0.0, y: 0.0, ..Default::default() };
d.insert_object(&at, rect_shape(460.0, 20.0, behind), &Default::default()).unwrap();
let l = lay(&d);
let (x, y, left, right, height, ink0) = l.pages[0]
.header
.iter()
.find_map(|it| match it {
Placed::Lines { para, l0, x, y, .. } => {
para.lines.get(*l0).and_then(|ln| Some((*x, *y, ln.left, ln.right, ln.height, *ln.xs.first()?)))
}
_ => None,
})
.expect("header line");
// `left`/`right` are the band edges available to the line, not the ink extent.
assert!((left - 150.0).abs() < 0.5, "{align:?}: the band's left edge is the indent: {left}");
assert!(ink0 > left + 100.0, "{align:?}: the ink starts well inside the band: ink {ink0}, band left {left}");
let ym = y + height / 2.0;
let hit = |px: f32| l.object_at_in(0, px, ym, 0.0, story).is_some();
// Inside the band, wherever the centred or right-aligned ink sits: header text.
assert!(!hit(x + left + 5.0), "{align:?}: the band's left end is text");
assert!(!hit(x + (left + right) / 2.0), "{align:?}: the band's middle is text");
// Between the indent and the ink is still the text band, not the picture.
assert!(!hit(x + left + 160.0), "{align:?}: between the indent and the ink is text");
// Within 40pt of the band's left end is still text; further left the picture is hit.
assert!(!hit(x + left - 30.0), "{align:?}: within 40pt left of the band is text");
assert!(hit(x + left - 60.0), "{align:?}: beyond 40pt left of the band the picture is hit");
}
}
+16
View File
@@ -223,6 +223,22 @@ fn selecting_a_long_endnote_takes_linear_time() {
assert_linear_steps("endnote selection", 20, laid, |(d, l, (a, b))| drop(std::hint::black_box(l.selection_rects(d, a, b, 0))));
}
/// One paragraph of `n` lines (a line break after each word), so it runs over many pages.
fn many_lines(n: usize) -> Document {
let mut d = Document::from_text("");
d.body = vec![wordcraft_doc::para_block(Paragraph::with_text(&"x\n".repeat(n), CharProps::default()))];
d
}
/// The piece of a long paragraph on each page looked through every line of the paragraph for the
/// pictures and shapes to draw with it (#6757).
#[test]
fn a_paragraph_over_many_pages_lays_out_in_linear_time() {
let pages = lay(&many_lines(SCALE * 400), &LayoutOptions::default()).pages.len();
assert!(pages > 40, "the paragraph runs over many pages: {pages}");
assert_layout_linear("a paragraph over many pages", 400, many_lines, &LayoutOptions::default());
}
/// A table of `n` rows of 60 cells, each row exactly half a point high, so every cell clips its
/// (empty) paragraph and the whole table fits on the first page.
fn clipped_table(n: usize) -> Document {
+6
View File
@@ -58,7 +58,9 @@ impl WordApp {
seen_full_screen,
escape_free,
status_counts,
print_memo,
missing_fonts,
export_error,
last_autosave,
equation_prev_tab,
smart_art_item,
@@ -104,6 +106,7 @@ impl WordApp {
clipboard_published: false,
printing: Default::default(),
print_feedback_seen: None,
print_gen: 0,
integrated_titlebar: false,
mac_titlebar: chrome::MacTitleBar::default(),
updates_rt: updates_ui::Runtime::default(),
@@ -178,7 +181,9 @@ impl WordApp {
seen_full_screen,
escape_free,
status_counts,
print_memo,
missing_fonts,
export_error,
last_autosave,
equation_prev_tab,
smart_art_item,
@@ -497,6 +502,7 @@ impl WordApp {
if !self.ui.backstage {
backstage::forget_open_error(&ctx);
backstage::forget_save_as_error(&ctx);
self.export_error.clear();
}
self.paint_window(ui, &ctx, t);
if !moved(self) {
+4 -2
View File
@@ -145,7 +145,9 @@ impl WordApp {
// Web: saving and exporting become downloads.
if self.services.download.is_some() && matches!(id, "file.save" | "file.saveAs" | "file.exportPdf" | "file.exportPng") {
let name = params.get("path").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| self.web_save_name(id));
let name = if id == "file.exportPdf" && !name.ends_with(".pdf") { format!("{name}.pdf") } else { name };
// Inspect only the suffix bytes: no full-name allocation or UTF-8 slicing.
let has_pdf_suffix = name.as_bytes().last_chunk::<4>().is_some_and(|suffix| suffix.eq_ignore_ascii_case(b".pdf"));
let name = if id == "file.exportPdf" && !has_pdf_suffix { format!("{name}.pdf") } else { name };
// A save with a password encrypts this and later saves (`file.save`'s `password`).
if matches!(id, "file.save" | "file.saveAs")
&& let Some(pw) = params.get("password").filter(|v| !v.is_null())
@@ -775,7 +777,7 @@ impl WordApp {
json!({"dir": dir})
}
// The built-in file browser (#576), for when the system's file dialog doesn't show up
// (desktop only): `purpose` is document (default), picture, recipients or save. A system
// (desktop only): `purpose` is document (default), picture, recipients, save or export. A system
// dialog still waiting for an answer is given up as cancelled.
#[cfg(not(target_arch = "wasm32"))]
"ui.fileBrowser" => {
+7
View File
@@ -320,6 +320,8 @@ impl WordApp {
return;
}
self.print_feedback_seen = self.printing.message.clone();
// A new message: what any window said before no longer stands for it.
self.print_gen = self.print_gen.wrapping_add(1);
let Some(message @ (printing::Feedback::Submitted(_) | printing::Feedback::Failed(_) | printing::Feedback::WorkerStopped)) =
self.printing.message.clone()
else {
@@ -334,6 +336,11 @@ impl WordApp {
self.ui.backstage = false;
self.canvas.want_focus = true;
}
// Said only where the status bar is drawn: not under File's other pages, and a failure on
// the Print page is the page's to show.
if !self.ui.backstage {
self.print_memo.said = Some(self.print_gen);
}
}
/// Files dropped on the native window. Raw input is taken only in the first UI pass: a
+5
View File
@@ -759,6 +759,11 @@ fn save_as_page(app: &mut WordApp, ui: &mut Ui) {
if ui.button(egui::RichText::new(tl!("Browse…")).font(medium(14.0))).clicked() {
app.save_as_dialog();
}
// Linux and the BSDs (#3535): WordCraft's own browser when the system dialog doesn't appear.
#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))]
if ui.button(egui::RichText::new(tl!("Browse in WordCraft…")).font(medium(14.0))).clicked() {
let _ = app.run("ui.fileBrowser", json!({"purpose": "save"}));
}
// A Word template in the user templates folder, which File › New lists under Personal (#2852).
ui.add_space(8.0);
if ui
+174
View File
@@ -859,6 +859,77 @@ fn save_as_page_shows_browse_and_no_open_list() {
assert!(h.query_by_label("Recent").is_none(), "Save As has no list that opens documents");
}
/// #3467, #3535: a system dialog that never shows up doesn't leave Save As stuck: Browse in
/// WordCraft… gives it up and saves through WordCraft's own browser.
#[test]
#[cfg(all(unix, not(target_os = "macos")))]
fn save_as_saves_in_wordcraft_when_the_system_dialog_never_shows() {
// A host that takes every request and never answers, like a portal that shows nothing.
let senders: std::rc::Rc<std::cell::RefCell<Vec<std::sync::mpsc::Sender<crate::FileDialogAnswer>>>> = Default::default();
let keep = senders.clone();
let services = Services {
file_dialog: Some(Box::new(move |_| {
let (tx, rx) = std::sync::mpsc::channel();
keep.borrow_mut().push(tx);
rx
})),
..Default::default()
};
let dir = std::env::temp_dir().join(format!("wordcraft-backstage-builtin-save-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), services);
a.run("text.insert", json!({"text": "Saved past a silent portal"})).unwrap();
a.run("ui.backstage", json!({"value": true, "page": "saveAs"})).unwrap();
let mut h = egui_kittest::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);
h.get_by_label("Browse…").click();
h.run_steps(4);
assert!(h.state().file_dialog.is_some(), "the system dialog was asked for and never answered");
h.get_by_label("Browse in WordCraft…").click();
h.run_steps(4);
let a = h.state_mut();
assert!(a.file_dialog.is_none(), "the silent system dialog is given up");
let b = a.file_browser.open.as_mut().expect("WordCraft's own browser is open");
b.navigate(dir.clone());
b.name = "kept".into();
let crate::file_browser::Step::Pick(path) = b.accept() else { panic!("picked") };
a.close_file_browser(Some(path));
let saved = dir.join("kept.docx");
assert_eq!(a.session.path.as_deref(), Some(saved.as_path()));
let back = wordcraft_engine::io::open_path(&saved).unwrap();
assert!(back.plain_text(wordcraft_doc::StoryRef::Body).contains("Saved past a silent portal"));
let _ = std::fs::remove_dir_all(&dir);
}
/// #3535: File › Export offers WordCraft's own browser as well, for its formats.
#[test]
#[cfg(all(unix, not(target_os = "macos")))]
fn export_page_offers_wordcrafts_own_browser() {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Services::default());
a.run("ui.backstage", json!({"value": true, "page": "export"})).unwrap();
let mut h = egui_kittest::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);
h.get_by_label("Browse in WordCraft…").click();
h.run_steps(4);
let b = h.state().file_browser.open.as_ref().expect("WordCraft's own browser is open");
assert!(matches!(&b.after, crate::file_dialogs::AfterPick::Export { ext } if ext == "pdf"));
}
#[test]
fn backstage_save_navigates_to_save_as_when_unnamed() {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Services::default());
@@ -1292,3 +1363,106 @@ fn rtl_template_titles_are_right_aligned() {
wide_text_right,
);
}
/// A refused Word XML export (the typed name's `.xml` twin already exists) is said on the Export
/// page itself: Backstage hides the status bar, so the person would otherwise see nothing.
#[test]
fn export_refusal_shows_on_the_export_page() {
let dir = std::env::temp_dir().join(format!("wordcraft-backstage-export-error-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("letter.xml"), "taken").unwrap();
let bare = dir.join("letter").to_string_lossy().into_owned();
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Services::default());
a.run("text.insert", json!({"text": "Dear reader"})).unwrap();
a.run("ui.backstage", json!({"value": true, "page": "export"})).unwrap();
let mut h = egui_kittest::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);
let err = h.state_mut().finish_pick(crate::file_dialogs::AfterPick::Export { ext: "xml".into() }, Some(bare)).unwrap_err();
h.run_steps(4);
assert!(h.state().ui.backstage, "still on the Export page");
assert!(err.contains("letter.xml already exists"), "{err}");
h.get_by_label(err.as_str());
assert_eq!(std::fs::read_to_string(dir.join("letter.xml")).unwrap(), "taken", "nothing replaced");
let _ = std::fs::remove_dir_all(&dir);
}
/// A refused Word XML export (the typed name's `.xml` twin already exists) is said on the Export
/// page itself: Backstage hides the status bar, so the person would otherwise see nothing.
#[test]
fn export_refusal_shows_on_the_print_page() {
let dir = std::env::temp_dir().join(format!("wordcraft-backstage-print-export-error-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("letter.xml"), "taken").unwrap();
let bare = dir.join("letter").to_string_lossy().into_owned();
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Services::default());
a.run("text.insert", json!({"text": "Dear reader"})).unwrap();
a.run("ui.backstage", json!({"value": true, "page": "print"})).unwrap();
let mut h = egui_kittest::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);
let err = h.state_mut().finish_pick(crate::file_dialogs::AfterPick::Export { ext: "xml".into() }, Some(bare)).unwrap_err();
h.run_steps(4);
assert!(h.state().ui.backstage, "still on the Print page");
assert!(err.contains("letter.xml already exists"), "{err}");
h.get_by_label(err.as_str());
assert_eq!(std::fs::read_to_string(dir.join("letter.xml")).unwrap(), "taken", "nothing replaced");
let _ = std::fs::remove_dir_all(&dir);
}
/// A cancelled export dialog drops an earlier refusal: it is not news any more.
#[test]
fn cancelling_an_export_clears_its_page_error() {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Services::default());
a.export_error = "old refusal".into();
a.finish_pick(crate::file_dialogs::AfterPick::Export { ext: "xml".into() }, None).unwrap();
assert!(a.export_error.is_empty());
}
/// The export error belongs to the window that refused the export: another window running a
/// frame outside Backstage must not erase it while this one still shows the Export page.
#[test]
fn export_error_belongs_to_its_window() {
let dir = std::env::temp_dir().join(format!("wordcraft-backstage-export-two-windows-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("letter.xml"), "taken").unwrap();
let bare = dir.join("letter").to_string_lossy().into_owned();
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Services::default());
a.run("text.insert", json!({"text": "Dear reader"})).unwrap();
a.run("ui.backstage", json!({"value": true, "page": "export"})).unwrap();
// Window A (this one) is refused; window B is another window's state, outside Backstage.
let mut b = crate::window_ui::WindowUi::new(a.session.document_id());
let err = a.finish_pick(crate::file_dialogs::AfterPick::Export { ext: "xml".into() }, Some(bare)).unwrap_err();
assert_eq!(a.export_error, err);
// B's frame: swap its state in, run frames outside Backstage, swap back.
a.swap_window(&mut b);
assert!(!a.ui.backstage && a.export_error.is_empty(), "B has its own, empty, error");
let mut h = egui_kittest::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);
h.state_mut().swap_window(&mut b);
assert!(h.state().ui.backstage, "A is still on the Export page");
assert_eq!(h.state().export_error, err, "B's frames left A's message alone");
let _ = std::fs::remove_dir_all(&dir);
}
+16
View File
@@ -253,6 +253,18 @@ pub struct CanvasState {
pub(crate) v_pressed: bool,
/// The modifiers last held with Mod, for a Mod+V whose Mod is released before V.
pub(crate) paste_mods: Option<egui::Modifiers>,
/// The modifiers a paste event is read with: those of Mod+V's press or a Mod change, until an
/// unrelated key, a pointer press or a focus change. (`paste_mods` also serves the release path.)
pub(crate) paste_event_mods: Option<egui::Modifiers>,
/// On the web, Mod+Shift+V pasted formatting from its key press: the browser's paste event
/// that follows is the same keystroke and pastes nothing (#5616). Any other key press clears it.
pub(crate) ignore_next_paste: bool,
/// When `ignore_next_paste` was set (input time, seconds): the browser's paired paste comes
/// with the key, so the wait ends after `PASTE_WAIT` and a later paste isn't dropped.
pub(crate) paste_wait_since: Option<f64>,
/// The platform sends a paste event after Mod+Shift+V's key (a browser does; a desktop shell
/// doesn't). Only then does the key leave a paste event to ignore or to let paste text.
pub(crate) paste_event_follows_chord: bool,
/// Draw Table or Eraser is on (`table_pen`): presses draw instead of moving the caret.
pub table_tool: Option<crate::table_pen::TableTool>,
/// The Draw Table stroke (or eraser press) in progress.
@@ -436,6 +448,10 @@ impl Default for CanvasState {
pasted: false,
v_pressed: false,
paste_mods: None,
paste_event_mods: None,
ignore_next_paste: false,
paste_wait_since: None,
paste_event_follows_chord: cfg!(target_arch = "wasm32"),
swallow_text: false,
ime_join_text: None,
ime_reset: false,
+215 -48
View File
@@ -635,12 +635,12 @@ fn multi_click_drag_extends_by_units() {
for _ in 0..6 {
h.step();
}
let screen = |h: &mut egui_kittest::Harness<'_, WordApp>, pos: Pos| {
let screen = |h: &mut H, pos: Pos| {
let c = h.state_mut().session.layout().caret(&pos).expect("caret");
page_to_screen(h.state_mut(), c.page, c.x + 1.0, c.top + c.height / 2.0).expect("on screen")
};
let button = |at: Pos2, pressed: bool| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() };
let multi_drag = |h: &mut egui_kittest::Harness<'_, WordApp>, from: Pos2, to: Pos2, clicks: usize| {
let multi_drag = |h: &mut H, from: Pos2, to: Pos2, clicks: usize| {
h.event(Event::PointerMoved(from));
for i in 0..clicks {
h.event(button(from, true));
@@ -871,7 +871,7 @@ fn clicking_vertical_scrollbar_track_advances_one_screen() {
let button = |at: Pos2, pressed: bool| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() };
let click = |h: &mut egui_kittest::Harness<'_, WordApp>, at: Pos2| {
let click = |h: &mut H, at: Pos2| {
h.event(Event::PointerMoved(at));
h.step();
h.event(button(at, true));
@@ -939,7 +939,7 @@ fn clicking_vertical_scrollbar_track_advances_one_screen_in_rtl() {
let button = |at: Pos2, pressed: bool| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() };
let click = |h: &mut egui_kittest::Harness<'_, WordApp>, at: Pos2| {
let click = |h: &mut H, at: Pos2| {
h.event(Event::PointerMoved(at));
h.step();
h.event(button(at, true));
@@ -1002,7 +1002,7 @@ fn clicking_thin_vertical_scrollbar_track_advances_one_screen() {
let button = |at: Pos2, pressed: bool| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() };
let click = |h: &mut egui_kittest::Harness<'_, WordApp>, at: Pos2| {
let click = |h: &mut H, at: Pos2| {
h.event(Event::PointerMoved(at));
h.step();
h.event(button(at, true));
@@ -1195,11 +1195,11 @@ fn ctrl_drag_copies_an_object() {
for _ in 0..6 {
h.step();
}
let objects = |h: &mut egui_kittest::Harness<'_, WordApp>| {
let objects = |h: &mut H| {
let doc = &h.state().session.doc;
doc.para(wordcraft_doc::StoryRef::Body, &wordcraft_doc::Path::top(0)).map_or(0, |p| p.objects.len())
};
let xs = |h: &mut egui_kittest::Harness<'_, WordApp>| {
let xs = |h: &mut H| {
let mut v: Vec<i32> = Vec::new();
for x in (0..600).step_by(50) {
if h.state_mut().session.layout().find_object(0, |o| (o.rect.x - x as f32).abs() < 0.5).is_some() {
@@ -1208,7 +1208,7 @@ fn ctrl_drag_copies_an_object() {
}
v
};
let drag = |h: &mut egui_kittest::Harness<'_, WordApp>, mods: Modifiers| {
let drag = |h: &mut H, mods: Modifiers| {
let from = page_to_screen(h.state_mut(), 0, 250.0, 330.0).expect("on screen");
let to = page_to_screen(h.state_mut(), 0, 400.0, 330.0).expect("on screen");
h.event(Event::ModifiersChanged(mods));
@@ -1257,19 +1257,19 @@ fn selection_bar_clicks_select_lines() {
h.step();
}
// A point in the left margin beside the line `li` lines below the one holding `pos`.
let margin = |h: &mut egui_kittest::Harness<'_, WordApp>, pos: Pos, li: f32| {
let margin = |h: &mut H, pos: Pos, li: f32| {
let c = h.state_mut().session.layout().caret(&pos).expect("caret");
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 egui_kittest::Harness<'_, WordApp>, at: Pos2| {
let line_start = |h: &mut H, at: Pos2| {
let (rects, scale) = (h.state().canvas.page_rects.clone(), h.state().canvas.scale);
let layout = h.state_mut().session.layout();
let (pg, x, y) = page_at(&rects, &layout, scale, at).expect("page");
layout.selection_bar_at(pg, x, y).expect("in the selection bar")
};
let span = |h: &mut egui_kittest::Harness<'_, WordApp>, pos: &Pos| h.state_mut().session.layout().line_span(pos, 0).expect("line");
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 egui_kittest::Harness<'_, WordApp>, from: Pos2, to: Pos2, clicks: usize| {
let clicks_drag = |h: &mut H, from: Pos2, to: Pos2, clicks: usize| {
h.event(Event::PointerMoved(from));
for i in 0..clicks {
h.event(button(from, true));
@@ -1288,7 +1288,7 @@ fn selection_bar_clicks_select_lines() {
h.step();
}
};
let pause = |h: &mut egui_kittest::Harness<'_, WordApp>| {
let pause = |h: &mut H| {
for _ in 0..40 {
h.step();
}
@@ -1361,7 +1361,7 @@ fn selection_bar_of_a_right_to_left_paragraph_is_on_the_right() {
let y = c.top + c.height / 2.0;
let right = page_to_screen(h.state_mut(), c.page, (body_x + page_w) / 2.0, y).expect("on screen");
let left = page_to_screen(h.state_mut(), c.page, 30.0, y).expect("on screen");
let click = |h: &mut egui_kittest::Harness<'_, WordApp>, at: Pos2| {
let click = |h: &mut H, at: Pos2| {
h.event(Event::PointerMoved(at));
h.step();
h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: Default::default() });
@@ -1408,7 +1408,7 @@ fn an_armed_format_painter_changes_the_pointer() {
let c = h.state_mut().session.layout().caret(&Pos::body(0, 6)).expect("caret");
let over_text = page_to_screen(h.state_mut(), c.page, c.x, c.top + c.height / 2.0).expect("on screen");
let over_bar = page_to_screen(h.state_mut(), c.page, 30.0, c.top + c.height / 2.0).expect("on screen");
let pointer_after = |h: &mut egui_kittest::Harness<'_, WordApp>, cmd: Option<&str>| {
let pointer_after = |h: &mut H, cmd: Option<&str>| {
if let Some(cmd) = cmd {
h.state_mut().run(cmd, json!({})).unwrap();
}
@@ -1493,7 +1493,7 @@ fn an_empty_comment_balloon_deletes() {
for _ in 0..6 {
h.step();
}
let click = |h: &mut egui_kittest::Harness<'_, WordApp>, at: egui::Pos2| {
let click = |h: &mut H, at: egui::Pos2| {
h.event(egui::Event::PointerMoved(at));
h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() });
h.step();
@@ -2137,7 +2137,7 @@ fn double_click_margin_creates_header_and_footer() {
for _ in 0..6 {
h.step();
}
let double_click = |h: &mut egui_kittest::Harness<'_, WordApp>, at: Pos2| {
let double_click = |h: &mut H, at: Pos2| {
h.event(Event::PointerMoved(at));
for _ in 0..2 {
h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: Default::default() });
@@ -2150,7 +2150,7 @@ fn double_click_margin_creates_header_and_footer() {
h.step();
}
};
let kind = |h: &egui_kittest::Harness<'_, WordApp>| part_kind(h.state(), h.state().session.sel.focus.story);
let kind = |h: &H| part_kind(h.state(), h.state().session.sel.focus.story);
let page = h.state_mut().session.layout().pages[0].clone();
assert!(page.header_story.is_none() && page.footer_story.is_none());
let (x, top, bottom) = (page.body.x + 20.0, page.body.y / 2.0, (page.body.bottom() + page.h) / 2.0);
@@ -2250,7 +2250,7 @@ fn double_click_switches_between_header_and_footer() {
for _ in 0..6 {
h.step();
}
let double_click = |h: &mut egui_kittest::Harness<'_, WordApp>, at: Pos2| {
let double_click = |h: &mut H, at: Pos2| {
h.event(Event::PointerMoved(at));
for _ in 0..2 {
h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: Default::default() });
@@ -2262,7 +2262,7 @@ fn double_click_switches_between_header_and_footer() {
h.step();
}
};
let kind = |h: &egui_kittest::Harness<'_, WordApp>| part_kind(h.state(), h.state().session.sel.focus.story);
let kind = |h: &H| part_kind(h.state(), h.state().session.sel.focus.story);
let page = h.state_mut().session.layout().pages[0].clone();
let (x, top, bottom) = (page.body.x + 20.0, page.body.y / 2.0, (page.body.bottom() + page.h) / 2.0);
let head_at = page_to_screen(h.state_mut(), 0, x, top).expect("top margin on screen");
@@ -2885,7 +2885,7 @@ fn control_click_on_macos_opens_the_context_menu() {
h.step();
let ctrl = egui::Modifiers { ctrl: true, ..Default::default() };
// The events winit delivers for a Control-click, through the app's input hook as eframe runs it.
let send = |h: &mut egui_kittest::Harness<'_, WordApp>, events: Vec<egui::Event>| {
let send = |h: &mut H, events: Vec<egui::Event>| {
let mut raw = egui::RawInput { events, ..Default::default() };
let ctx = h.ctx.clone();
h.state_mut().raw_input_hook(&ctx, &mut raw);
@@ -2973,7 +2973,10 @@ fn drag_floating_picture(wrap: &str, header: bool, preselect: bool) {
for _ in 0..3 {
h.step();
}
assert!(wordcraft_engine::cmd::objects::object_selection(&h.state().session).is_none(), "a click still selects text");
// In the header the picture lies over the body area, clear of the header's own text, so a
// click on it selects it (Word); in the body a click still reaches the text behind it.
let picked = wordcraft_engine::cmd::objects::object_selection(&h.state().session).is_some();
assert_eq!(picked, header, "a click selects the header's picture, but only edits the body's text");
if preselect {
let end = Pos { off: pos.off + wordcraft_doc::para::OBJ.len_utf8(), ..pos.clone() };
h.state_mut().run("select.range", json!({"anchor": pos, "focus": end})).unwrap();
@@ -3138,7 +3141,7 @@ fn right_clicking_a_link_hides_the_hover_tooltip() {
let at = screen(&mut h, c.x, c.top + c.height / 2.0);
h.event(egui::Event::PointerMoved(at));
steps(&mut h, 2);
let tips = |h: &egui_kittest::Harness<'_, WordApp>| h.query_all_by_label_contains("Click to follow link").count();
let tips = |h: &H| h.query_all_by_label_contains("Click to follow link").count();
assert!(tips(&h) > 0, "hovering the link shows its target");
for pressed in [true, false] {
h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed, modifiers: Default::default() });
@@ -3171,7 +3174,7 @@ fn a_handled_press_skips_the_link_tooltip() {
let at = screen(&mut h, c.x, c.top + c.height / 2.0);
h.event(Event::PointerMoved(at));
steps(&mut h, 2);
let tips = |h: &egui_kittest::Harness<'_, WordApp>| h.query_all_by_label_contains("Click to follow link").count();
let tips = |h: &H| h.query_all_by_label_contains("Click to follow link").count();
assert!(tips(&h) > 0, "hovering the link shows its target");
h.event(Event::ModifiersChanged(Modifiers::COMMAND));
h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::COMMAND });
@@ -4029,13 +4032,13 @@ fn ruler_tab_gestures_are_primary_only_and_cancellable() {
h.step();
}
let area = h.state().canvas.canvas_rect.expect("the canvas is laid out");
let ruler_x = |h: &mut egui_kittest::Harness<'_, WordApp>, d: f32| {
let ruler_x = |h: &mut H, d: f32| {
let body_x = h.state_mut().session.layout().pages[0].body.x;
page_to_screen(h.state_mut(), 0, body_x + d, 0.0).expect("on screen").x
};
let on_ruler = |h: &mut egui_kittest::Harness<'_, WordApp>, d: f32| pos2(ruler_x(h, d), area.min.y - 7.0);
let on_ruler = |h: &mut H, d: f32| pos2(ruler_x(h, d), area.min.y - 7.0);
let button = |at: Pos2, b: PointerButton, pressed: bool| Event::PointerButton { pos: at, button: b, pressed, modifiers: Default::default() };
let drag_events = |h: &mut egui_kittest::Harness<'_, WordApp>, from: Pos2, to: Pos2, b: PointerButton| {
let drag_events = |h: &mut H, from: Pos2, to: Pos2, b: PointerButton| {
h.event(Event::PointerMoved(from));
h.event(button(from, b, true));
h.step();
@@ -4048,7 +4051,7 @@ fn ruler_tab_gestures_are_primary_only_and_cancellable() {
h.step();
}
};
let stops_of = |h: &egui_kittest::Harness<'_, WordApp>, block: usize| {
let stops_of = |h: &H, block: usize| {
let s = &h.state().session;
let para = s.doc.para_at(&Pos::body(block, 0)).expect("a paragraph");
s.doc.styles.resolve_para(&para.props).tabs.iter().map(|t| (t.pos, t.align)).collect::<Vec<_>>()
@@ -4134,13 +4137,13 @@ fn ruler_tab_stops_are_set_moved_and_cleared_with_the_pointer() {
}
let area = h.state().canvas.canvas_rect.expect("the canvas is laid out");
// The middle of the ruler's strip, over a point `d` points from the paragraph's start.
let on_ruler = |h: &mut egui_kittest::Harness<'_, WordApp>, d: f32| {
let on_ruler = |h: &mut H, d: f32| {
let body_x = h.state_mut().session.layout().pages[0].body.x;
let x = page_to_screen(h.state_mut(), 0, body_x + d, 0.0).expect("on screen").x;
pos2(x, area.min.y - 7.0)
};
let button = |at: Pos2, pressed: bool| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() };
let click = |h: &mut egui_kittest::Harness<'_, WordApp>, at: Pos2| {
let click = |h: &mut H, at: Pos2| {
h.event(Event::PointerMoved(at));
h.event(button(at, true));
h.step();
@@ -4153,7 +4156,7 @@ fn ruler_tab_stops_are_set_moved_and_cleared_with_the_pointer() {
h.step();
}
};
let drag = |h: &mut egui_kittest::Harness<'_, WordApp>, from: Pos2, to: Pos2| {
let drag = |h: &mut H, from: Pos2, to: Pos2| {
h.event(Event::PointerMoved(from));
h.event(button(from, true));
h.step();
@@ -4166,7 +4169,7 @@ fn ruler_tab_stops_are_set_moved_and_cleared_with_the_pointer() {
h.step();
}
};
let stops = |h: &egui_kittest::Harness<'_, WordApp>| {
let stops = |h: &H| {
let s = &h.state().session;
let para = s.doc.para_at(&s.sel.focus).expect("a paragraph");
s.doc.styles.resolve_para(&para.props).tabs.iter().map(|t| (t.pos, t.align)).collect::<Vec<_>>()
@@ -4253,8 +4256,7 @@ fn space_and_enter_on_the_canvas_do_not_interrupt_ime() {
}
assert!(h.state().canvas.focused, "the canvas takes focus when the window opens");
let key = |key| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
let ime_interrupted =
|h: &egui_kittest::Harness<'_, WordApp>| h.output().platform_output.ime.as_ref().map(|ime| ime.should_interrupt_composition);
let ime_interrupted = |h: &H| h.output().platform_output.ime.as_ref().map(|ime| ime.should_interrupt_composition);
h.event(key(egui::Key::Space));
h.event(egui::Event::Text(" ".into()));
h.step();
@@ -4340,7 +4342,7 @@ fn the_caret_follows_the_input_method_cursor_in_the_composition() {
for _ in 0..8 {
h.step();
}
let ime_x = |h: &egui_kittest::Harness<'_, WordApp>| h.output().platform_output.ime.as_ref().map(|ime| ime.cursor_rect.min.x);
let ime_x = |h: &H| h.output().platform_output.ime.as_ref().map(|ime| ime.cursor_rect.min.x);
let start = ime_x(&h).expect("the canvas places the candidate window");
let mut compose = |range: Option<std::ops::Range<usize>>| {
h.event(egui::Event::Ime(egui::ImeEvent::Preedit { text: "にほん".into(), active_range_chars: range }));
@@ -4386,10 +4388,8 @@ fn ime_descriptor_reports_visible_logical_text_and_exact_cause() {
}
h.state_mut().session.sel = wordcraft_engine::Selection::caret(wordcraft_doc::Pos::body(0, 2));
h.step();
let text = |h: &egui_kittest::Harness<'_, WordApp>| {
h.output().platform_output.ime.as_ref().and_then(|i| i.surrounding_text.available()).map(|p| p.text.clone())
};
let cause = |h: &egui_kittest::Harness<'_, WordApp>| h.output().platform_output.ime.as_ref().map(|i| i.change_cause);
let text = |h: &H| h.output().platform_output.ime.as_ref().and_then(|i| i.surrounding_text.available()).map(|p| p.text.clone());
let cause = |h: &H| h.output().platform_output.ime.as_ref().map(|i| i.change_cause);
assert_eq!(text(&h), Some("ab".into()), "the committed text is available");
h.event(egui::Event::Ime(egui::ImeEvent::Preedit { text: "に".into(), active_range_chars: None }));
h.step();
@@ -4433,8 +4433,7 @@ fn ime_descriptor_hides_tracked_deletions_and_preserves_reversed_selection() {
}
h.state_mut().session.sel = wordcraft_engine::Selection { anchor: wordcraft_doc::Pos::body(0, 2), focus: wordcraft_doc::Pos::body(0, 7) };
h.step();
let payload =
|h: &egui_kittest::Harness<'_, WordApp>| h.output().platform_output.ime.as_ref().and_then(|i| i.surrounding_text.available()).cloned();
let payload = |h: &H| h.output().platform_output.ime.as_ref().and_then(|i| i.surrounding_text.available()).cloned();
let p = payload(&h).expect("the visible text is available");
assert_eq!(p.text, "abcd");
assert_eq!(p.cursor, 4);
@@ -4460,10 +4459,10 @@ fn ime_byte_deletion_preserves_the_selection_and_earns_input_method() {
}
h.state_mut().session.sel = wordcraft_engine::Selection { anchor: wordcraft_doc::Pos::body(0, 3), focus: wordcraft_doc::Pos::body(0, 1) };
h.step();
let cause = |h: &egui_kittest::Harness<'_, WordApp>| h.output().platform_output.ime.as_ref().map(|i| i.change_cause);
let cause = |h: &H| h.output().platform_output.ime.as_ref().map(|i| i.change_cause);
h.event(egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 1, after_bytes: 1 }));
h.step();
let body = |h: &egui_kittest::Harness<'_, WordApp>| h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body).trim_end().to_string();
let body = |h: &H| h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body).trim_end().to_string();
assert_eq!(body(&h), "bc", "the selected text is preserved");
assert_eq!(h.state().session.sel.anchor.off, 2, "the selection anchor moved with the erased prefix");
assert_eq!(h.state().session.sel.focus.off, 0);
@@ -4510,7 +4509,7 @@ fn ime_generation_changes_on_document_replacement_but_not_on_caret_motion() {
for _ in 0..8 {
h.step();
}
let generation = |h: &egui_kittest::Harness<'_, WordApp>| h.output().platform_output.ime.as_ref().map(|i| i.context_generation);
let generation = |h: &H| h.output().platform_output.ime.as_ref().map(|i| i.context_generation);
let first = generation(&h).expect("an IME context");
h.state_mut().run("caret.right", json!({})).unwrap();
h.step();
@@ -4715,7 +4714,7 @@ fn ime_generation_changes_on_undo_and_version_restore() {
for _ in 0..8 {
h.step();
}
let generation = |h: &egui_kittest::Harness<'_, WordApp>| h.output().platform_output.ime.as_ref().map(|i| i.context_generation);
let generation = |h: &H| h.output().platform_output.ime.as_ref().map(|i| i.context_generation);
let first = generation(&h).expect("an IME context");
h.state_mut().run("edit.undo", json!({})).unwrap();
h.step();
@@ -5014,9 +5013,7 @@ fn ime_equation_byte_delete_drops_only_its_immediate_replacement() {
for _ in 0..8 {
h.step();
}
let linear = |h: &mut egui_kittest::Harness<'_, WordApp>| {
h.state_mut().run("equation.get", json!({})).unwrap()["linear"].as_str().unwrap_or_default().to_string()
};
let linear = |h: &mut H| h.state_mut().run("equation.get", json!({})).unwrap()["linear"].as_str().unwrap_or_default().to_string();
// Harness::event steps each queued event in a separate frame. Insert the complete
// protocol replacement into RawInput to exercise a single native input batch.
h.input_mut().events.extend([
@@ -5388,6 +5385,176 @@ fn a_long_comment_balloon_paints_only_its_first_ten_rows() {
}
}
/// A Behind Text header picture: while editing the header a click on it selects it wherever no
/// header text covers it (far down over the body, or in the band clear of the text), as in Word;
/// over the header text the click edits the text. From the body a click there is body text.
#[test]
fn header_picture_clear_of_header_text_is_selected_while_editing_the_header() {
// Far down the page, over the body.
header_picture_click(false, 200.0, 400.0, Some((300.0, f32::MAX)), true);
// In the header band, below the header's text line.
header_picture_click(false, 300.0, 56.0, Some((50.0, 72.0)), true);
// Over the header's text, at its start: the click goes to the text.
header_picture_click(false, 72.0, 36.0, None, false);
}
/// The same for a footer, which is a `StoryRef::Part` like the header.
#[test]
fn footer_picture_clear_of_footer_text_is_selected_while_editing_the_footer() {
header_picture_click(true, 200.0, 400.0, Some((300.0, f32::MAX)), true);
}
/// Dragging a header picture that no header text covers moves it, rather than starting the
/// deferred drag-over-text path.
#[test]
fn dragging_a_header_picture_clear_of_header_text_moves_it() {
let (mut h, pos, rect) = header_picture_app(false, 200.0, 400.0, 1);
edit_story(&mut h, false, 0);
let at = picture_point(&h, 0, rect);
h.event(egui::Event::PointerMoved(at));
h.event(pointer_button(at, egui::PointerButton::Primary, true));
h.step();
let to = at + egui::vec2(60.0, 30.0);
for p in [at + egui::vec2(20.0, 10.0), to] {
h.event(egui::Event::PointerMoved(p));
h.step();
}
h.event(pointer_button(to, egui::PointerButton::Primary, false));
steps(&mut h, 3);
let moved = h.state_mut().session.layout().object(&pos, 0).unwrap().rect;
assert!(moved.x > rect.x + 10.0 && moved.y > rect.y + 5.0, "the picture moved with the drag: {rect:?} -> {moved:?}");
assert_eq!(wordcraft_engine::cmd::objects::object_selection(&h.state().session).map(|(p, _)| p), Some(pos), "and stays selected");
}
/// A right-click on the header picture repeated on page 2 while editing the header on page 1
/// selects that copy: the frame and handles belong on page 2, not the page last edited.
#[test]
fn right_clicking_a_repeated_header_picture_selects_it_on_its_own_page() {
let (mut h, pos, _) = header_picture_app(false, 200.0, 400.0, 2);
edit_story(&mut h, false, 0);
assert_eq!(h.state().session.page_hint, 0, "editing the header on page 1");
let rect = h.state_mut().session.layout().object(&pos, 1).unwrap().rect;
assert_eq!(h.state_mut().session.layout().object(&pos, 1).unwrap().page, 1, "the picture is repeated on page 2");
let at = picture_point(&h, 1, rect);
press(&mut h, at, egui::PointerButton::Secondary);
assert_eq!(wordcraft_engine::cmd::objects::object_selection(&h.state().session).map(|(p, _)| p), Some(pos), "the right-click selected it");
assert_eq!(h.state().session.page_hint, 1, "its frame is drawn on the page clicked");
}
/// The same for a left-click: it selects the page-2 copy and moves the frame there, not the copy
/// on page 1 that was being edited.
#[test]
fn left_clicking_a_repeated_header_picture_selects_it_on_its_own_page() {
let (mut h, pos, _) = header_picture_app(false, 200.0, 400.0, 2);
edit_story(&mut h, false, 0);
assert_eq!(h.state().session.page_hint, 0, "editing the header on page 1");
let rect = h.state_mut().session.layout().object(&pos, 1).unwrap().rect;
assert_eq!(h.state_mut().session.layout().object(&pos, 1).unwrap().page, 1, "the picture is repeated on page 2");
let at = picture_point(&h, 1, rect);
press(&mut h, at, egui::PointerButton::Primary);
assert_eq!(wordcraft_engine::cmd::objects::object_selection(&h.state().session).map(|(p, _)| p), Some(pos), "the left-click selected it");
assert_eq!(h.state().session.page_hint, 1, "its frame is drawn on the page clicked");
}
fn pointer_button(pos: egui::Pos2, button: egui::PointerButton, pressed: bool) -> egui::Event {
egui::Event::PointerButton { pos, button, pressed, modifiers: Default::default() }
}
/// Moves to `at`, presses and releases `button` there and lets the frames settle.
fn press(h: &mut H, at: egui::Pos2, button: egui::PointerButton) {
h.event(egui::Event::PointerMoved(at));
h.event(pointer_button(at, button, true));
h.step();
h.event(pointer_button(at, button, false));
steps(h, 3);
}
/// Near the top-left corner of the picture's `rect` on `page`: on the header text line when the
/// picture is placed over it.
fn picture_point(h: &H, page: usize, rect: wordcraft_geom::Rect) -> egui::Pos2 {
let scale = h.state().canvas.scale;
crate::frame::to_screen(h.state().canvas.page_rects[page], scale, rect).min + egui::vec2(10.0, 6.0) * scale
}
/// Starts editing the header (or footer) of `page` and lets the frames settle.
fn edit_story(h: &mut H, footer: bool, page: usize) {
let command = if footer { "insert.editFooter" } else { "insert.editHeader" };
h.state_mut().run(command, json!({"page": page})).unwrap();
// Entering the footer scrolls the page to it: wait until the page stops moving.
let (mut last, mut still) = (h.state().canvas.page_rects[0], 0);
for _ in 0..600 {
h.step();
let now = h.state().canvas.page_rects[0];
still = if now == last { still + 1 } else { 0 };
last = now;
if still >= 10 {
break;
}
}
}
/// A body-mode window on a document of `pages` pages whose header (or footer) holds text and a
/// 160pt Behind Text picture at (`x`, `y`) on the page. Returns it, the picture's position and
/// its first-page rectangle.
fn header_picture_app(footer: bool, x: f32, y: f32, pages: usize) -> (H, Pos, wordcraft_geom::Rect) {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
for _ in 1..pages {
a.run("insert.pageBreak", json!({})).unwrap();
}
a.run(if footer { "insert.editFooter" } else { "insert.editHeader" }, json!({})).unwrap();
a.run("text.insert", json!({"text": if footer { "Footer" } else { "Header" }})).unwrap();
let mut png = Vec::new();
let img = image::RgbaImage::from_pixel(40, 20, image::Rgba([200, 30, 30, 255]));
image::DynamicImage::ImageRgba8(img).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
a.run("insert.picture", json!({"data": wordcraft_engine::cmd::insert::base64_encode(&png), "width": 160})).unwrap();
let pos = wordcraft_engine::cmd::objects::selected(&a.session).unwrap().0;
a.run("arrange.bounds", json!({"x": x, "y": y})).unwrap();
a.run("arrange.wrap", json!({"wrap": "behindText"})).unwrap();
let rect = a.session.layout().object(&pos, 0).unwrap().rect;
a.run("insert.closeHeader", json!({})).unwrap();
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
a,
);
// Zoomed out so the whole page is on screen and entering the footer scrolls nothing.
h.state_mut().run("view.zoom", json!({"value": 40})).unwrap();
steps(&mut h, 20);
(h, pos, rect)
}
/// Puts a Behind Text header (or footer) picture at (`x`, `y`), checks its top lies within `band`
/// (when given), clicks near its top-left corner from the body and then while editing, and checks
/// the second click selects it (`selects`) or leaves the caret in the text; a right-click picks it
/// only where the click does, so the context menu (Reset Picture, Wrap Text) acts on it.
fn header_picture_click(footer: bool, x: f32, y: f32, band: Option<(f32, f32)>, selects: bool) {
let (mut h, pos, rect) = header_picture_app(footer, x, y, 1);
if let Some((lo, hi)) = band {
assert!(rect.y >= lo && rect.y < hi, "the picture sits where the case wants it: {rect:?}");
}
let at = picture_point(&h, 0, rect);
let picked = |h: &H| wordcraft_engine::cmd::objects::object_selection(&h.state().session).map(|(p, _)| p);
press(&mut h, at, egui::PointerButton::Primary);
assert!(picked(&h).is_none(), "from the body the picture isn't selectable");
assert_eq!(h.state().session.sel.focus.story, StoryRef::Body);
edit_story(&mut h, footer, 0);
press(&mut h, at, egui::PointerButton::Primary);
if selects {
assert_eq!(picked(&h), Some(pos.clone()), "while editing a click on its picture selects it ({x}, {y})");
} else {
assert_eq!(picked(&h), None, "over the text the click edits the text ({x}, {y})");
assert!(matches!(h.state().session.sel.focus.story, StoryRef::Part(_)), "still in the header or footer");
}
h.state_mut().session.sel = wordcraft_engine::Selection::caret(Pos { off: 0, ..pos.clone() });
press(&mut h, at, egui::PointerButton::Secondary);
assert_eq!(picked(&h), selects.then(|| pos.clone()), "a right-click picks the picture only where a click does ({x}, {y})");
h.event(egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() });
h.step();
}
/// #1961 review: what a picture draws must be in its page's fingerprint itself. Reset Picture on
/// one never edited keeps its media and clears only its corrections and crop, and undo puts them
/// back; the anchor paragraph's layout pointer also moves then, but only as long as the old
+15 -1
View File
@@ -225,7 +225,21 @@ pub fn show(app: &mut WordApp, ctx: &egui::Context) {
let held = (app.file_browser_open() || app.colors.is_some()).then(|| ctx.input_mut(|i| std::mem::take(&mut i.events)));
let shown = place_dialog(ctx, id, window).show(ctx, |ui| {
ui.set_min_width(340.0);
close = crate::rtl::root(ui, |ui| body(app, ui, &mut d));
// Scrolls only when the last frame's body was taller than the screen.
let room = (ui.ctx().content_rect().height() - 110.0).max(160.0);
let key = id.with("body_height");
let tall = ui.ctx().data(|data| data.get_temp::<f32>(key)).is_some_and(|h| h > room);
let mut content = |ui: &mut egui::Ui| {
let top = ui.cursor().min.y;
close = crate::rtl::root(ui, |ui| body(app, ui, &mut d));
let height = ui.min_rect().max.y - top;
ui.ctx().data_mut(|data| data.insert_temp(key, height));
};
if tall {
egui::ScrollArea::vertical().max_height(room).auto_shrink([true, true]).show(ui, content);
} else {
content(ui);
}
});
if let Some(events) = held {
ctx.input_mut(|i| i.events = events);
@@ -1,4 +1,4 @@
use super::{MeasureExt, Serialize, Ui, Value, WordApp, buttons, fit_size, heading, json, run, unit, vec2};
use super::{MeasureExt, Serialize, Ui, Value, WordApp, buttons, fit_size, json, run, unit, vec2};
// ---------------------------------------------------------------------------------------------
// Size
@@ -163,46 +163,49 @@ pub(super) fn size_ui(app: &mut WordApp, ui: &mut Ui, f: &mut SizeForm) -> bool
let changed = r.cell(|ui| ui.add(field.update_while_editing(false)).labelled_by(name.id).changed());
(changed && v != was).then_some(v)
};
heading(ui, "Size");
crate::rtl::Table::new("size_lengths").columns(4).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
if let Some(h) = length(r, "Height:", f.height) {
f.set_height(h);
}
if let Some(w) = length(r, "Width:", f.width) {
f.set_width(w);
}
crate::widgets::section(ui, tl!("Size"), |ui| {
crate::rtl::Table::new("size_lengths").columns(4).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
if let Some(h) = length(r, "Height:", f.height) {
f.set_height(h);
}
if let Some(w) = length(r, "Width:", f.width) {
f.set_width(w);
}
});
});
});
heading(ui, "Scale");
let (sw, sh) = f.scale();
crate::rtl::Table::new("size_scale").columns(4).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
if let Some(p) = percent(r, "Height:", sh) {
f.set_scale_height(p);
}
if let Some(w) = percent(r, "Width:", sw) {
f.set_scale_width(w);
}
crate::widgets::section(ui, tl!("Scale"), |ui| {
let (sw, sh) = f.scale();
crate::rtl::Table::new("size_scale").columns(4).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
if let Some(p) = percent(r, "Height:", sh) {
f.set_scale_height(p);
}
if let Some(w) = percent(r, "Width:", sw) {
f.set_scale_width(w);
}
});
});
ui.checkbox(&mut f.lock, tl!("Lock aspect ratio"));
ui.add_enabled_ui(f.original.is_some(), |ui| ui.checkbox(&mut f.relative, tl!("Relative to original picture size")));
});
ui.checkbox(&mut f.lock, tl!("Lock aspect ratio"));
ui.add_enabled_ui(f.original.is_some(), |ui| ui.checkbox(&mut f.relative, tl!("Relative to original picture size")));
if let Some((w, h)) = f.uncropped {
heading(ui, "Original size");
ui.horizontal(|ui| {
ui.label(format!("{} {}", tl!("Height:"), crate::options::length(h)));
ui.add_space(12.0);
ui.label(format!("{} {}", tl!("Width:"), crate::options::length(w)));
if let Some((pw, ph)) = f.pixels {
crate::widgets::section(ui, tl!("Original size"), |ui| {
ui.horizontal(|ui| {
ui.label(format!("{} {}", tl!("Height:"), crate::options::length(h)));
ui.add_space(12.0);
let (pw, ph) = (pw.to_string(), ph.to_string());
ui.weak(crate::i18n::fmt(tl!("{width} × {height} pixels"), &[("width", &pw), ("height", &ph)]));
}
ui.add_space(12.0);
if ui.button(tl!("Reset")).clicked() {
f.reset();
}
ui.label(format!("{} {}", tl!("Width:"), crate::options::length(w)));
if let Some((pw, ph)) = f.pixels {
ui.add_space(12.0);
let (pw, ph) = (pw.to_string(), ph.to_string());
ui.weak(crate::i18n::fmt(tl!("{width} × {height} pixels"), &[("width", &pw), ("height", &ph)]));
}
ui.add_space(12.0);
if ui.button(tl!("Reset")).clicked() {
f.reset();
}
});
});
}
let (ok, cancel) = buttons(ui, "OK", true);
@@ -268,11 +271,12 @@ pub(super) fn page_numbers_ui(app: &mut WordApp, ui: &mut Ui, f: &mut PageNumber
ui.selectable_value(&mut f.format, v.to_string(), l);
}
});
heading(ui, "Page numbering");
ui.radio_value(&mut f.cont, true, tl!("Continue from previous section"));
ui.horizontal(|ui| {
ui.radio_value(&mut f.cont, false, tl!("Start at:"));
ui.add_enabled(!f.cont, egui::DragValue::new(&mut f.start).range(1..=100_000));
crate::widgets::section(ui, tl!("Page numbering"), |ui| {
ui.radio_value(&mut f.cont, true, tl!("Continue from previous section"));
ui.horizontal(|ui| {
ui.radio_value(&mut f.cont, false, tl!("Start at:"));
ui.add_enabled(!f.cont, egui::DragValue::new(&mut f.start).range(1..=100_000));
});
});
let (ok, cancel) = buttons(ui, "OK", true);
if ok {
@@ -1,4 +1,4 @@
use super::{ENVELOPE_SIZES, LABEL_PRODUCTS, Serialize, Ui, Value, WordApp, buttons, heading, json, run};
use super::{ENVELOPE_SIZES, LABEL_PRODUCTS, Serialize, Ui, Value, WordApp, buttons, json, run};
// ---------------------------------------------------------------------------------------------
// Envelopes
@@ -163,15 +163,16 @@ pub(super) fn labels_ui(app: &mut WordApp, ui: &mut Ui, f: &mut LabelsForm) -> b
});
});
let (rows, cols) = LABEL_PRODUCTS.get(f.product).map_or((1, 1), |p| (p.rows, p.cols));
heading(ui, "Print");
ui.radio_value(&mut f.single, false, tl!("Full page of the same label"));
ui.horizontal(|ui| {
ui.radio_value(&mut f.single, true, tl!("Single label"));
ui.add_enabled_ui(f.single, |ui| {
ui.label(tl!("Row:"));
ui.add(egui::DragValue::new(&mut f.row).range(1..=rows));
ui.label(tl!("Column:"));
ui.add(egui::DragValue::new(&mut f.col).range(1..=cols));
crate::widgets::section(ui, tl!("Print"), |ui| {
ui.radio_value(&mut f.single, false, tl!("Full page of the same label"));
ui.horizontal(|ui| {
ui.radio_value(&mut f.single, true, tl!("Single label"));
ui.add_enabled_ui(f.single, |ui| {
ui.label(tl!("Row:"));
ui.add(egui::DragValue::new(&mut f.row).range(1..=rows));
ui.label(tl!("Column:"));
ui.add(egui::DragValue::new(&mut f.col).range(1..=cols));
});
});
});
f.row = f.row.clamp(1, rows.max(1));
@@ -118,23 +118,25 @@ impl SortForm {
}
pub(super) fn sort_ui(app: &mut WordApp, ui: &mut Ui, f: &mut SortForm) -> bool {
heading(ui, "Sort by");
ui.horizontal(|ui| {
craft_ui::ComboBox::from_id_salt("sort_column").selected_text(f.column_label(f.column)).width(180.0).show_ui(ui, |ui| {
for i in 0..f.headers.len() {
let label = f.column_label(i);
ui.selectable_value(&mut f.column, i, label);
}
});
crate::rtl::vertical(ui, |ui| {
ui.radio_value(&mut f.descending, false, tl!("Ascending"));
ui.radio_value(&mut f.descending, true, tl!("Descending"));
crate::widgets::section(ui, tl!("Sort by"), |ui| {
ui.horizontal(|ui| {
craft_ui::ComboBox::from_id_salt("sort_column").selected_text(f.column_label(f.column)).width(180.0).show_ui(ui, |ui| {
for i in 0..f.headers.len() {
let label = f.column_label(i);
ui.selectable_value(&mut f.column, i, label);
}
});
crate::rtl::vertical(ui, |ui| {
ui.radio_value(&mut f.descending, false, tl!("Ascending"));
ui.radio_value(&mut f.descending, true, tl!("Descending"));
});
});
});
heading(ui, "My list has");
ui.horizontal(|ui| {
ui.radio_value(&mut f.header, true, tl!("Header row"));
ui.radio_value(&mut f.header, false, tl!("No header row"));
crate::widgets::section(ui, tl!("My list has"), |ui| {
ui.horizontal(|ui| {
ui.radio_value(&mut f.header, true, tl!("Header row"));
ui.radio_value(&mut f.header, false, tl!("No header row"));
});
});
let (ok, cancel) = buttons(ui, "OK", true);
if ok {
@@ -380,39 +382,42 @@ impl TextToTableForm {
pub(super) fn text_to_table_ui(app: &mut WordApp, ui: &mut Ui, f: &mut TextToTableForm) -> bool {
let before = (f.separator.clone(), f.other_char.clone(), f.columns);
heading(ui, "Table size");
crate::rtl::Table::new("text_to_table").columns(2).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.label(tl!("Number of columns:")));
r.cell(|ui| ui.add(egui::DragValue::new(&mut f.columns).range(1..=63)));
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Number of rows:")));
r.cell(|ui| ui.label(f.rows.to_string()));
crate::widgets::section(ui, tl!("Table size"), |ui| {
crate::rtl::Table::new("text_to_table").columns(2).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.label(tl!("Number of columns:")));
r.cell(|ui| ui.add(egui::DragValue::new(&mut f.columns).range(1..=63)));
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Number of rows:")));
r.cell(|ui| ui.label(f.rows.to_string()));
});
});
});
heading(ui, "AutoFit behavior");
ui.horizontal(|ui| {
ui.radio_value(&mut f.autofit, "initial".to_string(), tl!("Initial column width:"));
ui.add_enabled(f.autofit == "initial", egui::TextEdit::singleline(&mut f.width).desired_width(72.0));
});
ui.radio_value(&mut f.autofit, "contents".to_string(), tl!("AutoFit to contents"));
ui.radio_value(&mut f.autofit, "window".to_string(), tl!("AutoFit to window"));
heading(ui, "Separate text at");
crate::rtl::Table::new("text_to_table_sep").columns(2).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.radio_value(&mut f.separator, "paragraph".to_string(), tl!("Paragraphs")));
r.cell(|ui| ui.radio_value(&mut f.separator, "comma".to_string(), tl!("Commas")));
crate::widgets::section(ui, tl!("AutoFit behavior"), |ui| {
ui.horizontal(|ui| {
ui.radio_value(&mut f.autofit, "initial".to_string(), tl!("Initial column width:"));
ui.add_enabled(f.autofit == "initial", egui::TextEdit::singleline(&mut f.width).desired_width(72.0));
});
t.row(|r| {
r.cell(|ui| ui.radio_value(&mut f.separator, "tab".to_string(), tl!("Tabs")));
r.cell(|ui| {
ui.horizontal(|ui| {
ui.radio_value(&mut f.separator, "other".to_string(), tl!("Other:"));
let edit = ui.add(egui::TextEdit::singleline(&mut f.other_char).char_limit(1).desired_width(24.0));
if edit.changed() {
f.separator = "other".into();
}
ui.radio_value(&mut f.autofit, "contents".to_string(), tl!("AutoFit to contents"));
ui.radio_value(&mut f.autofit, "window".to_string(), tl!("AutoFit to window"));
});
crate::widgets::section(ui, tl!("Separate text at"), |ui| {
crate::rtl::Table::new("text_to_table_sep").columns(2).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.radio_value(&mut f.separator, "paragraph".to_string(), tl!("Paragraphs")));
r.cell(|ui| ui.radio_value(&mut f.separator, "comma".to_string(), tl!("Commas")));
});
t.row(|r| {
r.cell(|ui| ui.radio_value(&mut f.separator, "tab".to_string(), tl!("Tabs")));
r.cell(|ui| {
ui.horizontal(|ui| {
ui.radio_value(&mut f.separator, "other".to_string(), tl!("Other:"));
let edit = ui.add(egui::TextEdit::singleline(&mut f.other_char).char_limit(1).desired_width(24.0));
if edit.changed() {
f.separator = "other".into();
}
});
});
});
});
@@ -208,7 +208,14 @@ fn language_dialog_default_survives_a_restart() {
use egui_kittest::kittest::Queryable;
let mut a = app();
a.ui.language = "en".into();
a.dialog = Some(Dialog::Layout(Box::new(LayoutDialog::Language(LanguageForm { lang: "fr-FR".into(), no_proof: false, detect: false }))));
a.dialog = Some(Dialog::Layout(Box::new(LayoutDialog::Language(LanguageForm {
lang: "fr-FR".into(),
no_proof: false,
detect: false,
whole_document: false,
initial: ("fr-FR".into(), false),
proof_touched: false,
}))));
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|ui, app: &mut WordApp| {
app.logic(&ui.ctx().clone());
@@ -232,6 +239,143 @@ fn language_dialog_default_survives_a_restart() {
assert_eq!(LanguageForm::read(&b).lang, "fr-FR");
}
/// #3518: ticking "Apply to the whole document" makes OK send `scope: "document"`; unticked sends none.
#[test]
fn language_dialog_whole_document_checkbox_sends_scope() {
use egui_kittest::kittest::Queryable;
let f = LanguageForm {
lang: "fr-FR".into(),
no_proof: false,
detect: false,
whole_document: false,
initial: ("fr-FR".into(), false),
proof_touched: false,
};
assert!(f.params().get("scope").is_none());
assert_eq!(LanguageForm { whole_document: true, ..f.clone() }.params()["scope"], "document");
let mut a = app();
a.ui.language = "en".into();
let para = wordcraft_doc::Paragraph::with_text("Header", Default::default());
let header = a.session.doc.add_part(wordcraft_doc::PartKind::Header, vec![Arc::new(wordcraft_doc::Block::Para(para))]);
a.dialog = Some(Dialog::Layout(Box::new(LayoutDialog::Language(f))));
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|ui, app: &mut WordApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
a,
);
h.run_steps(3);
h.get_by_label("Apply to the whole document").click();
h.run_steps(3);
h.get_by_label("OK").click();
h.run_steps(3);
// The header, which the caret isn't in, took the language.
let doc = &h.state().session.doc;
let hp = doc.para(wordcraft_doc::StoryRef::Part(header), &wordcraft_doc::Path::top(0)).unwrap();
assert_eq!(hp.runs.first().and_then(|r| r.props.lang.as_deref()), Some("fr-FR"));
}
/// "Plain text, then a Do-not-check run", the caret in the plain text.
fn proofing_mix_app() -> WordApp {
let mut a = app();
a.run("text.insert", json!({"text": "Plain code"})).unwrap();
a.run("select.text", json!({"text": "code"})).unwrap();
a.run("review.language", json!({"lang": "de-DE", "noProof": true})).unwrap();
a.run("select.text", json!({"text": "Plain"})).unwrap();
a.run("review.language", json!({"lang": "en-US", "noProof": false})).unwrap();
a.run("select.text", json!({"text": "Plain"})).unwrap();
a
}
fn run_proofing(a: &mut WordApp, text: &str) -> (Option<String>, Option<bool>) {
a.run("select.text", json!({"text": text})).unwrap();
let st = a.run("format.state", json!({})).unwrap();
(st["lang"].as_str().map(String::from), st["noProof"].as_bool())
}
/// #3518: whole-document OK sends only what the user changed.
#[test]
fn language_dialog_whole_document_sends_only_changes() {
// Changing only the language leaves the Do-not-check run alone.
let mut a = proofing_mix_app();
let mut f = LanguageForm::read(&a);
f.whole_document = true;
f.lang = "en-GB".into();
let p = f.params();
assert!(p.get("noProof").is_none());
a.run("review.language", p).unwrap();
assert_eq!(run_proofing(&mut a, "code"), (Some("en-GB".into()), Some(true)));
assert_eq!(run_proofing(&mut a, "Plain"), (Some("en-GB".into()), Some(false)));
// Changing only Do-not-check leaves each run's language alone.
let mut a = proofing_mix_app();
let mut f = LanguageForm::read(&a);
f.whole_document = true;
f.no_proof = true;
f.proof_touched = true;
let p = f.params();
assert!(p.get("lang").is_none());
a.run("review.language", p).unwrap();
assert_eq!(run_proofing(&mut a, "code"), (Some("de-DE".into()), Some(true)));
assert_eq!(run_proofing(&mut a, "Plain"), (Some("en-US".into()), Some(true)));
// No edits: the caret's language, no noProof (never the engine's en-US default).
let mut a = proofing_mix_app();
let mut f = LanguageForm::read(&a);
f.lang = "fr-FR".into();
f.initial.0 = "fr-FR".into();
f.whole_document = true;
let p = f.params();
assert_eq!(p["lang"], "fr-FR");
assert!(p.get("noProof").is_none());
a.run("review.language", p).unwrap();
assert_eq!(run_proofing(&mut a, "code"), (Some("fr-FR".into()), Some(true)));
// Selection mode is unchanged: both are sent.
f.whole_document = false;
assert_eq!(f.params()["noProof"], false);
}
/// #3518: a ticked Do-not-check box the user did not change (the caret sits in a no-proof run)
/// is not sent, so a language-only whole-document apply leaves other runs' proofing state alone.
#[test]
fn language_dialog_whole_document_unchanged_no_proof_is_not_sent() {
let mut a = proofing_mix_app();
a.run("select.text", json!({"text": "code"})).unwrap();
let mut f = LanguageForm::read(&a);
assert!(f.no_proof && f.initial.1);
f.whole_document = true;
f.lang = "en-GB".into();
let p = f.params();
assert!(p.get("noProof").is_none(), "{p}");
a.run("review.language", p).unwrap();
assert_eq!(run_proofing(&mut a, "code"), (Some("en-GB".into()), Some(true)));
assert_eq!(run_proofing(&mut a, "Plain"), (Some("en-GB".into()), Some(false)));
}
/// #3518: with the caret in a no-proof run, ticking the whole-document box and clicking Do not
/// check off and on again (ending ticked) still marks the whole document no-proof.
#[test]
fn language_dialog_whole_document_retoggled_no_proof_is_sent() {
let mut a = proofing_mix_app();
a.run("select.text", json!({"text": "code"})).unwrap();
let mut f = LanguageForm::read(&a);
assert!(f.no_proof && f.initial.1 && !f.proof_touched);
f.whole_document = true;
for _ in 0..2 {
f.no_proof = !f.no_proof;
f.proof_touched = true;
}
assert!(f.no_proof);
let p = f.params();
assert_eq!(p["noProof"], true, "{p}");
assert!(p.get("lang").is_none(), "{p}");
a.run("review.language", p).unwrap();
assert_eq!(run_proofing(&mut a, "Plain"), (Some("en-US".into()), Some(true)));
assert_eq!(run_proofing(&mut a, "code"), (Some("de-DE".into()), Some(true)));
}
/// #407: Envelopes starts from the selected address; Add to Document puts an envelope
/// section before the letter without asking to save (nothing is replaced).
#[test]
@@ -320,6 +320,16 @@ pub struct LanguageForm {
pub lang: String,
pub no_proof: bool,
pub detect: bool,
/// "Apply to the whole document": OK sends `scope: "document"` (every story), not the selection.
pub whole_document: bool,
/// The language and Do-not-check state the dialog opened with, to tell what the user changed.
#[serde(skip)]
pub initial: (String, bool),
/// The Do-not-check box was clicked (even back to where it started). A whole-document OK sends
/// `noProof` only then: the caret's value alone says nothing about runs that differ elsewhere,
/// but a click is a request to mark the whole document that way (#3518).
#[serde(skip)]
pub proof_touched: bool,
}
impl LanguageForm {
@@ -328,12 +338,36 @@ impl LanguageForm {
let style = s.doc.para_at(&s.sel.focus).and_then(|p| p.props.style.as_deref());
let here = s.doc.styles.resolve_char(style, &s.typing_props());
let lang = here.lang.unwrap_or_else(|| "en-US".into());
LanguageForm { lang, no_proof: here.no_proof, detect: s.prefs.detect_language }
LanguageForm {
initial: (lang.clone(), here.no_proof),
lang,
no_proof: here.no_proof,
detect: s.prefs.detect_language,
whole_document: false,
proof_touched: false,
}
}
/// `review.language` parameters for OK.
pub fn params(&self) -> Value {
json!({"lang": self.lang, "noProof": self.no_proof, "detect": self.detect})
if !self.whole_document {
return json!({"lang": self.lang, "noProof": self.no_proof, "detect": self.detect});
}
// Whole document: the caret's values must not flatten what differs elsewhere, so send only
// what was changed. With no edits at all the language goes (never the engine's en-US default).
let (lang_changed, proof_touched) = (self.lang != self.initial.0, self.proof_touched);
let mut v = json!({"scope": "document", "detect": self.detect});
if let Some(m) = v.as_object_mut() {
if lang_changed || !proof_touched {
m.insert("lang".into(), json!(self.lang));
}
// Only a clicked box is sent: the caret's value untouched says nothing about runs that
// differ elsewhere, and resending it would flatten them.
if proof_touched {
m.insert("noProof".into(), json!(self.no_proof));
}
}
v
}
}
@@ -343,7 +377,7 @@ pub(super) fn language_name(tag: &str) -> String {
}
pub(super) fn language_ui(app: &mut WordApp, ui: &mut Ui, f: &mut LanguageForm) -> bool {
ui.label(tl!("Mark selected text as:"));
ui.label(if f.whole_document { tl!("Mark the whole document as:") } else { tl!("Mark selected text as:") });
let list = crate::ribbon::language_list(&f.lang);
egui::Frame::NONE.stroke(egui::Stroke::new(1.0, crate::theme::Tokens::get(ui.ctx()).border_strong)).inner_margin(4.0).show(ui, |ui| {
egui::ScrollArea::vertical().max_height(220.0).min_scrolled_height(220.0).show(ui, |ui| {
@@ -358,8 +392,11 @@ pub(super) fn language_ui(app: &mut WordApp, ui: &mut Ui, f: &mut LanguageForm)
});
});
ui.add_space(4.0);
ui.checkbox(&mut f.no_proof, tl!("Do not check spelling or grammar"));
if ui.checkbox(&mut f.no_proof, tl!("Do not check spelling or grammar")).clicked() {
f.proof_touched = true;
}
ui.checkbox(&mut f.detect, tl!("Detect language automatically"));
ui.checkbox(&mut f.whole_document, tl!("Apply to the whole document"));
ui.add_space(4.0);
let set_default = ui.button(tl!("Set As Default")).clicked();
if set_default && run(app, "review.language", json!({"lang": f.lang, "default": true, "detect": f.detect})) {
+60 -59
View File
@@ -534,69 +534,70 @@ const MOVE_TO_MARKS: &[(&str, &str)] = &[
/// Track Changes Options. Returns true to close.
pub fn track_options(app: &mut WordApp, ui: &mut Ui, f: &mut TrackForm) -> bool {
let theme = app.session.doc.settings.theme_colors.clone();
let heading = |ui: &mut Ui, s: &str| {
ui.add_space(4.0);
ui.label(egui::RichText::new(tl!(s)).font(semibold(12.5)));
};
heading(ui, "Show");
crate::rtl::Table::new("tco_show").columns(2).spacing(vec2(16.0, 4.0)).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.checkbox(&mut f.comments, tl!("Comments")));
r.cell(|ui| ui.checkbox(&mut f.ink, tl!("Ink")));
});
t.row(|r| {
r.cell(|ui| ui.checkbox(&mut f.insertions_deletions, tl!("Insertions and Deletions")));
r.cell(|ui| ui.checkbox(&mut f.formatting, tl!("Formatting")));
});
});
heading(ui, "Balloons");
for (v, l) in [
("revisions", "Show revisions in balloons"),
("inline", "Show all revisions inline"),
("commentsAndFormatting", "Show only comments and formatting in balloons"),
] {
ui.radio_value(&mut f.balloons, v.to_string(), tl!(l));
}
heading(ui, "Comments");
for (v, l) in [("margin", "In the margin"), ("selected", "Only for the selected text")] {
ui.radio_value(&mut f.comment_display, v.to_string(), tl!(l));
}
heading(ui, "Advanced");
crate::rtl::Table::new("tco_advanced").columns(3).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.label(tl!("Insertions:")));
r.cell(|ui| choice(ui, "tco_ins", &mut f.insert_mark, INSERT_MARKS));
r.cell(|ui| color(ui, &theme, &mut f.insert_color, "By author", None));
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Deletions:")));
r.cell(|ui| choice(ui, "tco_del", &mut f.delete_mark, DELETE_MARKS));
r.cell(|ui| color(ui, &theme, &mut f.delete_color, "By author", None));
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Changed lines:")));
r.cell(|ui| {
choice(
ui,
"tco_bar",
&mut f.changed_lines,
&[("outside", "Outside border"), ("left", "Left border"), ("right", "Right border"), ("none", "None")],
)
crate::widgets::section(ui, tl!("Show"), |ui| {
crate::rtl::Table::new("tco_show").columns(2).spacing(vec2(16.0, 4.0)).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.checkbox(&mut f.comments, tl!("Comments")));
r.cell(|ui| ui.checkbox(&mut f.ink, tl!("Ink")));
});
t.row(|r| {
r.cell(|ui| ui.checkbox(&mut f.insertions_deletions, tl!("Insertions and Deletions")));
r.cell(|ui| ui.checkbox(&mut f.formatting, tl!("Formatting")));
});
r.cell(|ui| color(ui, &theme, &mut f.changed_lines_color, "Automatic", Some(wordcraft_layout::display::CHANGE_BAR)));
});
});
heading(ui, "Moves");
crate::rtl::Table::new("tco_moves").columns(3).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.label(tl!("Moved from:")));
r.cell(|ui| choice(ui, "tco_move_from", &mut f.move_from_mark, DELETE_MARKS));
r.cell(|ui| ui.push_id("tco_move_from_color", |ui| color(ui, &theme, &mut f.move_from_color, "By author", None)));
crate::widgets::section(ui, tl!("Balloons"), |ui| {
for (v, l) in [
("revisions", "Show revisions in balloons"),
("inline", "Show all revisions inline"),
("commentsAndFormatting", "Show only comments and formatting in balloons"),
] {
ui.radio_value(&mut f.balloons, v.to_string(), tl!(l));
}
});
crate::widgets::section(ui, tl!("Comments"), |ui| {
for (v, l) in [("margin", "In the margin"), ("selected", "Only for the selected text")] {
ui.radio_value(&mut f.comment_display, v.to_string(), tl!(l));
}
});
crate::widgets::section(ui, tl!("Advanced"), |ui| {
crate::rtl::Table::new("tco_advanced").columns(3).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.label(tl!("Insertions:")));
r.cell(|ui| choice(ui, "tco_ins", &mut f.insert_mark, INSERT_MARKS));
r.cell(|ui| color(ui, &theme, &mut f.insert_color, "By author", None));
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Deletions:")));
r.cell(|ui| choice(ui, "tco_del", &mut f.delete_mark, DELETE_MARKS));
r.cell(|ui| color(ui, &theme, &mut f.delete_color, "By author", None));
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Changed lines:")));
r.cell(|ui| {
choice(
ui,
"tco_bar",
&mut f.changed_lines,
&[("outside", "Outside border"), ("left", "Left border"), ("right", "Right border"), ("none", "None")],
)
});
r.cell(|ui| color(ui, &theme, &mut f.changed_lines_color, "Automatic", Some(wordcraft_layout::display::CHANGE_BAR)));
});
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Moved to:")));
r.cell(|ui| choice(ui, "tco_move_to", &mut f.move_to_mark, MOVE_TO_MARKS));
r.cell(|ui| ui.push_id("tco_move_to_color", |ui| color(ui, &theme, &mut f.move_to_color, "By author", None)));
});
crate::widgets::section(ui, tl!("Moves"), |ui| {
crate::rtl::Table::new("tco_moves").columns(3).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.label(tl!("Moved from:")));
r.cell(|ui| choice(ui, "tco_move_from", &mut f.move_from_mark, DELETE_MARKS));
r.cell(|ui| ui.push_id("tco_move_from_color", |ui| color(ui, &theme, &mut f.move_from_color, "By author", None)));
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Moved to:")));
r.cell(|ui| choice(ui, "tco_move_to", &mut f.move_to_mark, MOVE_TO_MARKS));
r.cell(|ui| ui.push_id("tco_move_to_color", |ui| color(ui, &theme, &mut f.move_to_color, "By author", None)));
});
});
});
ui.add_space(4.0);
+71 -73
View File
@@ -8,7 +8,6 @@ use serde::Serialize;
use serde_json::{Value, json};
use crate::WordApp;
use crate::theme::semibold;
/// Number formats notes offer: OOXML name and a sample (not translated). The Format Page Numbers
/// dialog offers the same list (#1113).
@@ -80,84 +79,83 @@ fn choice(ui: &mut Ui, id: &str, value: &mut String, options: &[(&str, &str)], t
/// Footnote and Endnote. Returns true to close.
pub fn note_options(app: &mut WordApp, ui: &mut Ui, f: &mut NoteForm) -> bool {
let heading = |ui: &mut Ui, s: &str| {
ui.add_space(4.0);
ui.label(egui::RichText::new(tl!(s)).font(semibold(12.5)));
};
heading(ui, "Location");
let mut convert = None;
crate::rtl::grid(ui, egui::Grid::new("notes_location").num_columns(2).spacing(vec2(10.0, 6.0)), |ui| {
ui.radio_value(&mut f.endnote, false, tl!("Footnotes"));
ui.add_enabled_ui(!f.endnote, |ui| {
choice(ui, "notes_fpos", &mut f.pos[0], &[("pageBottom", "Bottom of Page"), ("beneathText", "Below text")], true);
});
ui.end_row();
ui.radio_value(&mut f.endnote, true, tl!("Endnotes"));
ui.add_enabled_ui(f.endnote, |ui| {
choice(ui, "notes_epos", &mut f.pos[1], &[("sectEnd", "End of section"), ("docEnd", "End of document")], true);
});
ui.end_row();
ui.label("");
ui.menu_button(format!("{}…", tl!("Convert")), |ui| {
crate::rtl::root(ui, |ui| {
for (to, l) in [("endnote", "Footnotes to endnotes"), ("footnote", "Endnotes to footnotes"), ("swap", "Swap footnotes and endnotes")]
{
if ui.button(tl!(l)).clicked() {
convert = Some(to);
ui.close();
crate::widgets::section(ui, tl!("Location"), |ui| {
let mut convert = None;
crate::rtl::grid(ui, egui::Grid::new("notes_location").num_columns(2).spacing(vec2(10.0, 6.0)), |ui| {
ui.radio_value(&mut f.endnote, false, tl!("Footnotes"));
ui.add_enabled_ui(!f.endnote, |ui| {
choice(ui, "notes_fpos", &mut f.pos[0], &[("pageBottom", "Bottom of Page"), ("beneathText", "Below text")], true);
});
ui.end_row();
ui.radio_value(&mut f.endnote, true, tl!("Endnotes"));
ui.add_enabled_ui(f.endnote, |ui| {
choice(ui, "notes_epos", &mut f.pos[1], &[("sectEnd", "End of section"), ("docEnd", "End of document")], true);
});
ui.end_row();
ui.label("");
ui.menu_button(format!("{}…", tl!("Convert")), |ui| {
crate::rtl::root(ui, |ui| {
for (to, l) in
[("endnote", "Footnotes to endnotes"), ("footnote", "Endnotes to footnotes"), ("swap", "Swap footnotes and endnotes")]
{
if ui.button(tl!(l)).clicked() {
convert = Some(to);
ui.close();
}
}
}
})
})
});
ui.end_row();
});
ui.end_row();
if let Some(to) = convert
&& let Err(e) = app.run("references.convertNotes", json!({ "to": to }))
{
app.status(e);
}
});
if let Some(to) = convert
&& let Err(e) = app.run("references.convertNotes", json!({ "to": to }))
{
app.status(e);
}
heading(ui, "Format");
let k = usize::from(f.endnote);
crate::rtl::Table::new("notes_format").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.label(tl!("Number format")));
r.cell(|ui| {
if let Some(v) = f.fmt.get_mut(k) {
choice(ui, "notes_fmt", v, &FORMATS, false);
}
crate::widgets::section(ui, tl!("Format"), |ui| {
let k = usize::from(f.endnote);
crate::rtl::Table::new("notes_format").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.label(tl!("Number format")));
r.cell(|ui| {
if let Some(v) = f.fmt.get_mut(k) {
choice(ui, "notes_fmt", v, &FORMATS, false);
}
});
});
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Custom mark:")));
r.cell(|ui| ui.add(egui::TextEdit::singleline(&mut f.mark).desired_width(60.0).char_limit(10)));
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Start at:")));
r.cell(|ui| {
if let Some(v) = f.start.get_mut(k) {
ui.add(egui::DragValue::new(v).range(1..=32_767).speed(0.2));
}
t.row(|r| {
r.cell(|ui| ui.label(tl!("Custom mark:")));
r.cell(|ui| ui.add(egui::TextEdit::singleline(&mut f.mark).desired_width(60.0).char_limit(10)));
});
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Numbering")));
r.cell(|ui| {
if let Some(v) = f.restart.get_mut(k) {
let each_page: &[(&str, &str)] = if f.endnote { &[] } else { &[("eachPage", "Restart Each Page")] };
let options: Vec<(&str, &str)> = [("continuous", "Continuous numbering"), ("eachSect", "Restart Each Section")]
.into_iter()
.chain(each_page.iter().copied())
.collect();
choice(ui, "notes_restart", v, &options, true);
}
t.row(|r| {
r.cell(|ui| ui.label(tl!("Start at:")));
r.cell(|ui| {
if let Some(v) = f.start.get_mut(k) {
ui.add(egui::DragValue::new(v).range(1..=32_767).speed(0.2));
}
});
});
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Apply to:")));
r.cell(|ui| {
let mut scope = if f.whole { "document" } else { "section" }.to_string();
choice(ui, "notes_scope", &mut scope, &[("document", "Whole document"), ("section", "This section")], true);
f.whole = scope == "document";
t.row(|r| {
r.cell(|ui| ui.label(tl!("Numbering")));
r.cell(|ui| {
if let Some(v) = f.restart.get_mut(k) {
let each_page: &[(&str, &str)] = if f.endnote { &[] } else { &[("eachPage", "Restart Each Page")] };
let options: Vec<(&str, &str)> = [("continuous", "Continuous numbering"), ("eachSect", "Restart Each Section")]
.into_iter()
.chain(each_page.iter().copied())
.collect();
choice(ui, "notes_restart", v, &options, true);
}
});
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Apply to:")));
r.cell(|ui| {
let mut scope = if f.whole { "document" } else { "section" }.to_string();
choice(ui, "notes_scope", &mut scope, &[("document", "Whole document"), ("section", "This section")], true);
f.whole = scope == "document";
});
});
});
});
@@ -1,4 +1,4 @@
use super::common::{LEADERS, choice, heading, leader_char, sample};
use super::common::{LEADERS, choice, leader_char, sample};
use super::shell::{Next, go};
use super::{FieldCode, RefsDialog, Serialize, Ui, Value, WordApp, buttons, json, vec2};
@@ -161,40 +161,43 @@ impl MarkForm {
/// Draws the index-entry fields and page, cross-reference or bookmark-range options, with Mark
/// and Mark All running `references.markEntry`.
pub(super) fn mark_ui(app: &mut WordApp, ui: &mut Ui, f: &mut MarkForm) -> Next {
heading(ui, "Index");
crate::rtl::Table::new("xe").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
let entry_label = r.cell(|ui| ui.label(tl!("Main entry:")));
r.cell(|ui| ui.add(egui::TextEdit::singleline(&mut f.entry).desired_width(220.0)).labelled_by(entry_label.id));
});
t.row(|r| {
let subentry_label = r.cell(|ui| ui.label(tl!("Subentry:")));
r.cell(|ui| ui.add(egui::TextEdit::singleline(&mut f.subentry).desired_width(220.0)).labelled_by(subentry_label.id));
});
});
heading(ui, "Options");
ui.horizontal(|ui| {
let see_label = ui.radio_value(&mut f.option, "see".to_string(), tl!("Cross-reference:"));
ui.add_enabled(f.option == "see", egui::TextEdit::singleline(&mut f.see).desired_width(160.0)).labelled_by(see_label.id);
});
ui.radio_value(&mut f.option, "page".to_string(), tl!("This page"));
ui.horizontal(|ui| {
let bookmark_label =
ui.add_enabled_ui(!f.bookmarks.is_empty(), |ui| ui.radio_value(&mut f.option, "range".to_string(), tl!("Pages of bookmark:"))).inner;
ui.add_enabled_ui(f.option == "range", |ui| {
let opts: Vec<(String, &str)> = f.bookmarks.iter().map(|b| (b.clone(), b.as_str())).collect();
let combo = craft_ui::ComboBox::from_id_salt("xe_bm").selected_text(f.bookmark.clone()).width(140.0).show_ui(ui, |ui| {
for (v, l) in &opts {
ui.selectable_value(&mut f.bookmark, v.clone(), *l);
}
crate::widgets::section(ui, tl!("Index"), |ui| {
crate::rtl::Table::new("xe").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
let entry_label = r.cell(|ui| ui.label(tl!("Main entry:")));
r.cell(|ui| ui.add(egui::TextEdit::singleline(&mut f.entry).desired_width(220.0)).labelled_by(entry_label.id));
});
t.row(|r| {
let subentry_label = r.cell(|ui| ui.label(tl!("Subentry:")));
r.cell(|ui| ui.add(egui::TextEdit::singleline(&mut f.subentry).desired_width(220.0)).labelled_by(subentry_label.id));
});
combo.response.labelled_by(bookmark_label.id);
});
});
heading(ui, "Page number style");
ui.horizontal(|ui| {
ui.checkbox(&mut f.bold, tl!("Bold"));
ui.checkbox(&mut f.italic, tl!("Italic"));
crate::widgets::section(ui, tl!("Options"), |ui| {
ui.horizontal(|ui| {
let see_label = ui.radio_value(&mut f.option, "see".to_string(), tl!("Cross-reference:"));
ui.add_enabled(f.option == "see", egui::TextEdit::singleline(&mut f.see).desired_width(160.0)).labelled_by(see_label.id);
});
ui.radio_value(&mut f.option, "page".to_string(), tl!("This page"));
ui.horizontal(|ui| {
let bookmark_label =
ui.add_enabled_ui(!f.bookmarks.is_empty(), |ui| ui.radio_value(&mut f.option, "range".to_string(), tl!("Pages of bookmark:"))).inner;
ui.add_enabled_ui(f.option == "range", |ui| {
let opts: Vec<(String, &str)> = f.bookmarks.iter().map(|b| (b.clone(), b.as_str())).collect();
let combo = craft_ui::ComboBox::from_id_salt("xe_bm").selected_text(f.bookmark.clone()).width(140.0).show_ui(ui, |ui| {
for (v, l) in &opts {
ui.selectable_value(&mut f.bookmark, v.clone(), *l);
}
});
combo.response.labelled_by(bookmark_label.id);
});
});
});
crate::widgets::section(ui, tl!("Page number style"), |ui| {
ui.horizontal(|ui| {
ui.checkbox(&mut f.bold, tl!("Bold"));
ui.checkbox(&mut f.italic, tl!("Italic"));
});
});
if !f.message.is_empty() {
ui.label(egui::RichText::new(&f.message).small());
+229 -212
View File
@@ -122,128 +122,130 @@ fn font_dialog(app: &mut WordApp, ui: &mut Ui, d: &mut Dialog) -> bool {
};
let sample_props =
font_sample_props(app, sample_paper(app), font, size, color, (*bold, *italic, *underline, *strike), (*small_caps, *caps, *hidden), *spacing);
crate::rtl::Table::new("fontdlg").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
// Word's two font boxes when East Asian text is in use: the Latin text font and
// the Asian text font, each with its own list (type to find a font).
let prev = app.previews.font_preview_fn();
if *asian {
crate::widgets::section(ui, "", |ui| {
crate::rtl::Table::new("fontdlg").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
// Word's two font boxes when East Asian text is in use: the Latin text font and
// the Asian text font, each with its own list (type to find a font).
let prev = app.previews.font_preview_fn();
if *asian {
t.row(|r| {
r.cell(|ui| ui.label(tl!("Asian text font:")));
r.cell(|ui| {
let fams = app.previews.east_asian_families();
let stored = app.previews.font_stored(font_ea);
let latin = app.previews.font_stored(font);
let warning = app.east_asian_font_box_warning(&stored, &latin);
if let Some(f) = font_box(ui, ("fontdlg_asian", font_ea.as_str()), &fams, &*prev, warning.as_deref()) {
if f == crate::widgets::ADD_FONT {
let _ = app.run("font.add", json!({}));
} else if f == crate::widgets::LOAD_SYSTEM_FONTS {
let _ = app.run("font.loadSystem", json!({}));
} else {
*font_ea = f;
}
}
});
});
}
t.row(|r| {
r.cell(|ui| ui.label(tl!("Asian text font:")));
r.cell(|ui| ui.label(if *asian { tl!("Latin text font:") } else { tl!("Font:") }));
r.cell(|ui| {
let fams = app.previews.east_asian_families();
let stored = app.previews.font_stored(font_ea);
let latin = app.previews.font_stored(font);
let warning = app.east_asian_font_box_warning(&stored, &latin);
if let Some(f) = font_box(ui, ("fontdlg_asian", font_ea.as_str()), &fams, &*prev, warning.as_deref()) {
let fams = app.previews.families();
let stored = app.previews.font_stored(font);
let warning = app.font_dialog_warning(&stored);
if let Some(f) = font_box(ui, ("fontdlg_font", font.as_str()), &fams, &*prev, warning.as_deref()) {
if f == crate::widgets::ADD_FONT {
let _ = app.run("font.add", json!({}));
} else if f == crate::widgets::LOAD_SYSTEM_FONTS {
let _ = app.run("font.loadSystem", json!({}));
} else {
*font_ea = f;
*font = f;
}
}
});
});
}
t.row(|r| {
r.cell(|ui| ui.label(if *asian { tl!("Latin text font:") } else { tl!("Font:") }));
r.cell(|ui| {
let fams = app.previews.families();
let stored = app.previews.font_stored(font);
let warning = app.font_dialog_warning(&stored);
if let Some(f) = font_box(ui, ("fontdlg_font", font.as_str()), &fams, &*prev, warning.as_deref()) {
if f == crate::widgets::ADD_FONT {
let _ = app.run("font.add", json!({}));
} else if f == crate::widgets::LOAD_SYSTEM_FONTS {
let _ = app.run("font.loadSystem", json!({}));
} else {
*font = f;
}
}
t.row(|r| {
let size_label = r.cell(|ui| ui.label(tl!("Size:")));
r.cell(|ui| ui.text_edit_singleline(size).labelled_by(size_label.id));
});
});
t.row(|r| {
let size_label = r.cell(|ui| ui.label(tl!("Size:")));
r.cell(|ui| ui.text_edit_singleline(size).labelled_by(size_label.id));
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Font color:")));
r.cell(|ui| {
let theme = app.session.doc.settings.theme_colors.clone();
color_field(ui, &theme, color, "Automatic", "auto");
t.row(|r| {
r.cell(|ui| ui.label(tl!("Font color:")));
r.cell(|ui| {
let theme = app.session.doc.settings.theme_colors.clone();
color_field(ui, &theme, color, "Automatic", "auto");
});
});
});
t.row(|r| {
let spacing_label = r.cell(|ui| ui.label(tl!("Spacing (pt):")));
r.cell(|ui| ui.add(egui::DragValue::new(spacing).speed(0.1).range(-20.0..=20.0)).labelled_by(spacing_label.id));
});
t.row(|r| {
let label = tl!("Kerning for fonts:");
r.cell(|ui| match kern {
Some(on) => {
ui.checkbox(on, label);
}
None => {
if ui.add(egui::Checkbox::new(&mut false, label).indeterminate(true)).clicked() {
*kern = Some(true);
}
}
t.row(|r| {
let spacing_label = r.cell(|ui| ui.label(tl!("Spacing (pt):")));
r.cell(|ui| ui.add(egui::DragValue::new(spacing).speed(0.1).range(-20.0..=20.0)).labelled_by(spacing_label.id));
});
r.cell(|ui| {
ui.horizontal(|ui| {
let enabled = *kern == Some(true);
let field = egui::DragValue::new(kern_at).speed(0.5).range(1.0..=1638.0).max_decimals(1);
// The number comes first in the reading order, then "points and above"; a left-to-right
// row in a right-to-left interface runs the other way, so there the label is first.
if crate::rtl::on() && !crate::rtl::flows(ui) {
let points_label = ui.label(tl!("Points and above"));
ui.add_enabled(enabled, field).labelled_by(points_label.id);
} else {
let points = ui.add_enabled(enabled, field);
let points_label = ui.label(tl!("Points and above"));
points.labelled_by(points_label.id);
t.row(|r| {
let label = tl!("Kerning for fonts:");
r.cell(|ui| match kern {
Some(on) => {
ui.checkbox(on, label);
}
None => {
if ui.add(egui::Checkbox::new(&mut false, label).indeterminate(true)).clicked() {
*kern = Some(true);
}
}
});
r.cell(|ui| {
ui.horizontal(|ui| {
let enabled = *kern == Some(true);
let field = egui::DragValue::new(kern_at).speed(0.5).range(1.0..=1638.0).max_decimals(1);
// The number comes first in the reading order, then "points and above"; a left-to-right
// row in a right-to-left interface runs the other way, so there the label is first.
if crate::rtl::on() && !crate::rtl::flows(ui) {
let points_label = ui.label(tl!("Points and above"));
ui.add_enabled(enabled, field).labelled_by(points_label.id);
} else {
let points = ui.add_enabled(enabled, field);
let points_label = ui.label(tl!("Points and above"));
points.labelled_by(points_label.id);
}
});
});
});
});
});
ui.separator();
ui.label(egui::RichText::new(tl!("Effects")).font(semibold(12.5)));
crate::rtl::Table::new("fx").columns(2).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.checkbox(bold, tl!("Bold")));
r.cell(|ui| ui.checkbox(italic, tl!("Italic")));
});
t.row(|r| {
r.cell(|ui| ui.checkbox(underline, tl!("Underline")));
r.cell(|ui| ui.checkbox(strike, tl!("Strikethrough")));
});
t.row(|r| {
// Superscript and Subscript exclude each other: the one just ticked wins.
let was_sup = *sup;
r.cell(|ui| ui.checkbox(sup, tl!("Superscript")));
r.cell(|ui| ui.checkbox(sub, tl!("Subscript")));
if *sup && *sub {
if was_sup {
*sup = false;
} else {
*sub = false;
crate::widgets::section(ui, tl!("Effects"), |ui| {
crate::rtl::Table::new("fx").columns(2).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.checkbox(bold, tl!("Bold")));
r.cell(|ui| ui.checkbox(italic, tl!("Italic")));
});
t.row(|r| {
r.cell(|ui| ui.checkbox(underline, tl!("Underline")));
r.cell(|ui| ui.checkbox(strike, tl!("Strikethrough")));
});
t.row(|r| {
// Superscript and Subscript exclude each other: the one just ticked wins.
let was_sup = *sup;
r.cell(|ui| ui.checkbox(sup, tl!("Superscript")));
r.cell(|ui| ui.checkbox(sub, tl!("Subscript")));
if *sup && *sub {
if was_sup {
*sup = false;
} else {
*sub = false;
}
}
}
});
t.row(|r| {
r.cell(|ui| ui.checkbox(small_caps, tl!("Small caps")));
r.cell(|ui| ui.checkbox(caps, tl!("All caps")));
});
t.row(|r| {
r.cell(|ui| ui.checkbox(hidden, tl!("Hidden")));
});
t.row(|r| {
r.cell(|ui| ui.checkbox(small_caps, tl!("Small caps")));
r.cell(|ui| ui.checkbox(caps, tl!("All caps")));
});
t.row(|r| {
r.cell(|ui| ui.checkbox(hidden, tl!("Hidden")));
});
});
});
// Live preview of the chosen font/size/colour/effects.
ui.separator();
ui.label(egui::RichText::new(tl!("Preview")).small().weak());
font_sample_box(app, ui, sample_paper(app), &sample_props, (*sup, *sub), *hidden);
crate::widgets::section(ui, tl!("Preview"), |ui| {
font_sample_box(app, ui, sample_paper(app), &sample_props, (*sup, *sub), *hidden);
});
let (ok, cancel) = buttons(ui, tl!("OK"));
if ok {
apply_font(app, d);
@@ -281,86 +283,92 @@ fn paragraph_dialog(app: &mut WordApp, ui: &mut Ui, d: &mut Dialog) -> bool {
ui.add_space(6.0);
match *tab {
0 => {
ui.label(egui::RichText::new(tl!("General")).font(semibold(12.5)));
ui.horizontal(|ui| {
ui.label(tl!("Direction:"));
// Neither while the selected paragraphs differ.
let blank = mixed.contains("bidi");
for (value, text) in [(true, tl!("Right-to-left")), (false, tl!("Left-to-right"))] {
if ui.radio(!blank && *rtl == value, text).clicked() {
*rtl = value;
mixed.remove("bidi");
}
}
});
const ALIGNS: [(&str, &str); 4] = [("left", "Left"), ("center", "Center"), ("right", "Right"), ("justify", "Justify")];
ui.horizontal(|ui| {
let align_label = ui.label(tl!("Alignment:"));
let shown =
if mixed.contains("align") { "" } else { ALIGNS.iter().find(|(v, _)| v == align).map_or(align.as_str(), |(_, l)| tl!(l)) };
let combo = craft_ui::ComboBox::from_id_salt("para_align").selected_text(shown).show_ui(ui, |ui| {
for (v, l) in ALIGNS {
if ui.selectable_value(align, v.to_string(), tl!(l)).clicked() {
mixed.remove("align");
crate::widgets::section(ui, tl!("General"), |ui| {
ui.horizontal(|ui| {
ui.label(tl!("Direction:"));
// Neither while the selected paragraphs differ.
let blank = mixed.contains("bidi");
for (value, text) in [(true, tl!("Right-to-left")), (false, tl!("Left-to-right"))] {
if ui.radio(!blank && *rtl == value, text).clicked() {
*rtl = value;
mixed.remove("bidi");
}
}
});
combo.response.labelled_by(align_label.id);
});
ui.label(egui::RichText::new(tl!("Indentation")).font(semibold(12.5)));
// Mirrored indents are the inside and outside ones (they swap on even pages).
let (l_label, r_label) = if opts[0] { ("Inside:", "Outside:") } else { ("Left:", "Right:") };
crate::rtl::Table::new("ind").columns(4).show(ui, |t| {
t.row(|r| {
let left_label = r.cell(|ui| ui.label(tl!(l_label)));
r.cell(|ui| para_number(ui, left, ParaNumber::Length, "left", mixed, &left_label));
let right_label = r.cell(|ui| ui.label(tl!(r_label)));
r.cell(|ui| para_number(ui, right, ParaNumber::Length, "right", mixed, &right_label));
});
t.row(|r| {
let first_label = r.cell(|ui| ui.label(tl!("First line:")));
r.cell(|ui| para_number(ui, first, ParaNumber::Length, "indentFirst", mixed, &first_label));
const ALIGNS: [(&str, &str); 4] = [("left", "Left"), ("center", "Center"), ("right", "Right"), ("justify", "Justify")];
ui.horizontal(|ui| {
let align_label = ui.label(tl!("Alignment:"));
let shown =
if mixed.contains("align") { "" } else { ALIGNS.iter().find(|(v, _)| v == align).map_or(align.as_str(), |(_, l)| tl!(l)) };
let combo = craft_ui::ComboBox::from_id_salt("para_align").selected_text(shown).show_ui(ui, |ui| {
for (v, l) in ALIGNS {
if ui.selectable_value(align, v.to_string(), tl!(l)).clicked() {
mixed.remove("align");
}
}
});
combo.response.labelled_by(align_label.id);
});
});
para_check(ui, &mut opts[0], tl!("Mirror indents"), "mirrorIndents", mixed);
ui.label(egui::RichText::new(tl!("Spacing")).font(semibold(12.5)));
crate::rtl::Table::new("sp").columns(4).show(ui, |t| {
t.row(|r| {
let before_label = r.cell(|ui| ui.label(tl!("Before:")));
r.cell(|ui| para_number(ui, before, ParaNumber::Points, "spaceBefore", mixed, &before_label));
let line_label = r.cell(|ui| ui.label(tl!("Line spacing:")));
r.cell(|ui| para_number(ui, line, ParaNumber::Lines, "lineSpacing", mixed, &line_label));
crate::widgets::section(ui, tl!("Indentation"), |ui| {
// Mirrored indents are the inside and outside ones (they swap on even pages).
let (l_label, r_label) = if opts[0] { ("Inside:", "Outside:") } else { ("Left:", "Right:") };
crate::rtl::Table::new("ind").columns(4).show(ui, |t| {
t.row(|r| {
let left_label = r.cell(|ui| ui.label(tl!(l_label)));
r.cell(|ui| para_number(ui, left, ParaNumber::Length, "left", mixed, &left_label));
let right_label = r.cell(|ui| ui.label(tl!(r_label)));
r.cell(|ui| para_number(ui, right, ParaNumber::Length, "right", mixed, &right_label));
});
t.row(|r| {
let first_label = r.cell(|ui| ui.label(tl!("First line:")));
r.cell(|ui| para_number(ui, first, ParaNumber::Length, "indentFirst", mixed, &first_label));
});
});
t.row(|r| {
let after_label = r.cell(|ui| ui.label(tl!("After:")));
r.cell(|ui| para_number(ui, after, ParaNumber::Points, "spaceAfter", mixed, &after_label));
para_check(ui, &mut opts[0], tl!("Mirror indents"), "mirrorIndents", mixed);
});
crate::widgets::section(ui, tl!("Spacing"), |ui| {
crate::rtl::Table::new("sp").columns(4).show(ui, |t| {
t.row(|r| {
let before_label = r.cell(|ui| ui.label(tl!("Before:")));
r.cell(|ui| para_number(ui, before, ParaNumber::Points, "spaceBefore", mixed, &before_label));
let line_label = r.cell(|ui| ui.label(tl!("Line spacing:")));
r.cell(|ui| para_number(ui, line, ParaNumber::Lines, "lineSpacing", mixed, &line_label));
});
t.row(|r| {
let after_label = r.cell(|ui| ui.label(tl!("After:")));
r.cell(|ui| para_number(ui, after, ParaNumber::Points, "spaceAfter", mixed, &after_label));
});
});
});
para_check(ui, &mut opts[1], tl!("Don't add space between paragraphs of the same style"), "contextualSpacing", mixed);
}
1 => {
ui.label(egui::RichText::new(tl!("Line and Page Breaks")).font(semibold(12.5)));
para_check(ui, widow, tl!("Widow/Orphan control"), "widowControl", mixed);
para_check(ui, keep_next, tl!("Keep with next"), "keepNext", mixed);
para_check(ui, keep_lines, tl!("Keep lines together"), "keepLines", mixed);
para_check(ui, page_break, tl!("Page break before"), "pageBreakBefore", mixed);
ui.label(egui::RichText::new(tl!("Formatting exceptions")).font(semibold(12.5)));
para_check(ui, &mut opts[2], tl!("Suppress line numbers"), "suppressLineNumbers", mixed);
para_check(ui, &mut opts[3], tl!("Don't hyphenate"), "suppressHyphens", mixed);
crate::widgets::section(ui, tl!("Line and Page Breaks"), |ui| {
para_check(ui, widow, tl!("Widow/Orphan control"), "widowControl", mixed);
para_check(ui, keep_next, tl!("Keep with next"), "keepNext", mixed);
para_check(ui, keep_lines, tl!("Keep lines together"), "keepLines", mixed);
para_check(ui, page_break, tl!("Page break before"), "pageBreakBefore", mixed);
});
crate::widgets::section(ui, tl!("Formatting exceptions"), |ui| {
para_check(ui, &mut opts[2], tl!("Suppress line numbers"), "suppressLineNumbers", mixed);
para_check(ui, &mut opts[3], tl!("Don't hyphenate"), "suppressHyphens", mixed);
});
}
_ => {
let [kinsoku, word_wrap, overflow, top_line, de, dn] = asian;
ui.label(egui::RichText::new(tl!("Line breaking")).font(semibold(12.5)));
para_check(ui, kinsoku, tl!("Apply Asian line-breaking rules (kinsoku)"), "kinsoku", mixed);
// The model's flag is "wrap whole words"; the box offers the opposite.
let mut mid_word = !*word_wrap;
para_check(ui, &mut mid_word, tl!("Allow Latin text to wrap in the middle of a word"), "wordWrap", mixed);
*word_wrap = !mid_word;
para_check(ui, overflow, tl!("Allow hanging punctuation"), "overflowPunct", mixed);
ui.label(egui::RichText::new(tl!("Character Spacing")).font(semibold(12.5)));
para_check(ui, top_line, tl!("Compress punctuation at the start of a line"), "topLinePunct", mixed);
para_check(ui, de, tl!("Add space between Asian and Latin text"), "autoSpaceDE", mixed);
para_check(ui, dn, tl!("Add space between Asian text and numbers"), "autoSpaceDN", mixed);
crate::widgets::section(ui, tl!("Line breaking"), |ui| {
para_check(ui, kinsoku, tl!("Apply Asian line-breaking rules (kinsoku)"), "kinsoku", mixed);
// The model's flag is "wrap whole words"; the box offers the opposite.
let mut mid_word = !*word_wrap;
para_check(ui, &mut mid_word, tl!("Allow Latin text to wrap in the middle of a word"), "wordWrap", mixed);
*word_wrap = !mid_word;
para_check(ui, overflow, tl!("Allow hanging punctuation"), "overflowPunct", mixed);
});
crate::widgets::section(ui, tl!("Character Spacing"), |ui| {
para_check(ui, top_line, tl!("Compress punctuation at the start of a line"), "topLinePunct", mixed);
para_check(ui, de, tl!("Add space between Asian and Latin text"), "autoSpaceDE", mixed);
para_check(ui, dn, tl!("Add space between Asian text and numbers"), "autoSpaceDN", mixed);
});
}
}
ui.add_space(6.0);
@@ -619,57 +627,66 @@ fn page_setup_dialog(app: &mut WordApp, ui: &mut Ui, d: &mut Dialog) -> bool {
else {
return false;
};
ui.label(egui::RichText::new(tl!("Margins")).font(semibold(12.5)));
crate::rtl::Table::new("ps").columns(4).show(ui, |t| {
t.row(|r| {
let top_label = r.cell(|ui| ui.label(tl!("Top:")));
r.cell(|ui| ui.add(margin(top)).labelled_by(top_label.id));
let bottom_label = r.cell(|ui| ui.label(tl!("Bottom:")));
r.cell(|ui| ui.add(margin(bottom)).labelled_by(bottom_label.id));
});
t.row(|r| {
let left_label = r.cell(|ui| ui.label(if *mirror { tl!("Inside:") } else { tl!("Left:") }));
r.cell(|ui| ui.add(margin(left)).labelled_by(left_label.id));
let right_label = r.cell(|ui| ui.label(if *mirror { tl!("Outside:") } else { tl!("Right:") }));
r.cell(|ui| ui.add(margin(right)).labelled_by(right_label.id));
crate::widgets::section(ui, tl!("Margins"), |ui| {
crate::rtl::Table::new("ps").columns(4).show(ui, |t| {
t.row(|r| {
let top_label = r.cell(|ui| ui.label(tl!("Top:")));
r.cell(|ui| ui.add(margin(top)).labelled_by(top_label.id));
let bottom_label = r.cell(|ui| ui.label(tl!("Bottom:")));
r.cell(|ui| ui.add(margin(bottom)).labelled_by(bottom_label.id));
});
t.row(|r| {
let left_label = r.cell(|ui| ui.label(if *mirror { tl!("Inside:") } else { tl!("Left:") }));
r.cell(|ui| ui.add(margin(left)).labelled_by(left_label.id));
let right_label = r.cell(|ui| ui.label(if *mirror { tl!("Outside:") } else { tl!("Right:") }));
r.cell(|ui| ui.add(margin(right)).labelled_by(right_label.id));
});
});
});
ui.label(egui::RichText::new(tl!("Orientation")).font(semibold(12.5)));
ui.horizontal(|ui| {
ui.radio_value(landscape, false, tl!("Portrait"));
ui.radio_value(landscape, true, tl!("Landscape"));
});
ui.label(egui::RichText::new(tl!("Pages")).font(semibold(12.5)));
ui.checkbox(mirror, tl!("Mirror margins"));
page_paper_group(ui, paper, landscape, paper_custom);
ui.label(egui::RichText::new(tl!("Document Grid")).font(semibold(12.5)));
ui.horizontal_wrapped(|ui| {
ui.radio_value(&mut grid.0, 0, tl!("No grid"));
ui.radio_value(&mut grid.0, 1, tl!("Lines only"));
ui.radio_value(&mut grid.0, 2, tl!("Lines and characters"));
ui.radio_value(&mut grid.0, 3, tl!("Text snaps to characters"));
});
crate::rtl::Table::new("ps_grid").columns(4).show(ui, |t| {
t.row(|r| {
let chars_label = r.cell(|ui| ui.add_enabled(grid.0 >= 2, egui::Label::new(tl!("Characters per line:"))));
r.cell(|ui| ui.add_enabled(grid.0 >= 2, egui::DragValue::new(&mut grid.2).range(1..=1000).clip_text(true)).labelled_by(chars_label.id));
let lines_label = r.cell(|ui| ui.add_enabled(grid.0 >= 1, egui::Label::new(tl!("Lines per page:"))));
r.cell(|ui| ui.add_enabled(grid.0 >= 1, egui::DragValue::new(&mut grid.1).range(1..=1000).clip_text(true)).labelled_by(lines_label.id));
crate::widgets::section(ui, tl!("Orientation"), |ui| {
ui.horizontal(|ui| {
ui.radio_value(landscape, false, tl!("Portrait"));
ui.radio_value(landscape, true, tl!("Landscape"));
});
});
ui.horizontal(|ui| {
ui.label(tl!("Section direction:"));
ui.radio_value(rtl, false, tl!("Left-to-right"));
ui.radio_value(rtl, true, tl!("Right-to-left"));
crate::widgets::section(ui, tl!("Pages"), |ui| {
ui.checkbox(mirror, tl!("Mirror margins"));
page_paper_group(ui, paper, landscape, paper_custom);
});
crate::widgets::section(ui, tl!("Document Grid"), |ui| {
ui.horizontal_wrapped(|ui| {
ui.radio_value(&mut grid.0, 0, tl!("No grid"));
ui.radio_value(&mut grid.0, 1, tl!("Lines only"));
ui.radio_value(&mut grid.0, 2, tl!("Lines and characters"));
ui.radio_value(&mut grid.0, 3, tl!("Text snaps to characters"));
});
crate::rtl::Table::new("ps_grid").columns(4).show(ui, |t| {
t.row(|r| {
let chars_label = r.cell(|ui| ui.add_enabled(grid.0 >= 2, egui::Label::new(tl!("Characters per line:"))));
r.cell(|ui| {
ui.add_enabled(grid.0 >= 2, egui::DragValue::new(&mut grid.2).range(1..=1000).clip_text(true)).labelled_by(chars_label.id)
});
let lines_label = r.cell(|ui| ui.add_enabled(grid.0 >= 1, egui::Label::new(tl!("Lines per page:"))));
r.cell(|ui| {
ui.add_enabled(grid.0 >= 1, egui::DragValue::new(&mut grid.1).range(1..=1000).clip_text(true)).labelled_by(lines_label.id)
});
});
});
ui.horizontal(|ui| {
ui.label(tl!("Section direction:"));
ui.radio_value(rtl, false, tl!("Left-to-right"));
ui.radio_value(rtl, true, tl!("Right-to-left"));
});
if !message.is_empty() {
ui.label(egui::RichText::new(message.as_str()).small().color(ui.visuals().error_fg_color));
}
page_valign_combo(ui, valign);
});
crate::widgets::section(ui, tl!("Headers and footers"), |ui| {
// Word's Page Setup › Layout: a title page without the page number (#1230).
ui.checkbox(odd_even, tl!("Different Odd & Even Pages"));
ui.checkbox(first_page, tl!("Different First Page"));
});
if !message.is_empty() {
ui.label(egui::RichText::new(message.as_str()).small().color(ui.visuals().error_fg_color));
}
page_valign_combo(ui, valign);
// Word's Page Setup › Layout: a title page without the page number (#1230).
ui.label(egui::RichText::new(tl!("Headers and footers")).font(semibold(12.5)));
ui.checkbox(odd_even, tl!("Different Odd & Even Pages"));
ui.checkbox(first_page, tl!("Different First Page"));
let (mut ok, cancel) = buttons(ui, tl!("OK"));
if ok {
// Everything OK changes is one undo step; a refused command applies nothing.
+72 -69
View File
@@ -1,5 +1,5 @@
use super::chrome::buttons;
use super::{MeasureExt, Sense, Serialize, Tokens, Ui, Value, WordApp, json, semibold, vec2};
use super::{MeasureExt, Sense, Serialize, Tokens, Ui, Value, WordApp, json, vec2};
/// The Custom tab of File › Info › Properties › Advanced Properties (#2982): the document's
/// custom properties, edited as a working copy. OK sends the whole difference from what the
@@ -385,85 +385,88 @@ pub(super) fn table_properties(ui: &mut Ui, f: &mut TableForm) {
fn len(v: &mut f32, lo: f32, unit: wordcraft_geom::Unit) -> egui::DragValue<'_> {
egui::DragValue::new(v).speed(0.01).range(lo..=22.0).measure(unit).max_decimals(2)
}
let heading = |ui: &mut Ui, s: &str| {
ui.add_space(4.0);
ui.label(egui::RichText::new(tl!(s)).font(semibold(12.5)));
};
heading(ui, "Table");
crate::rtl::Table::new("tp_table").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.checkbox(&mut f.width_on, tl!("Preferred width:")));
r.cell(|ui| ui.add_enabled(f.width_on, len(&mut f.width, 0.1, unit)));
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Alignment:")));
r.cell(|ui| {
ui.horizontal(|ui| {
for (v, l) in [("left", "Left"), ("center", "Center"), ("right", "Right")] {
ui.radio_value(&mut f.align, v.to_string(), tl!(l));
}
crate::widgets::section(ui, tl!("Table"), |ui| {
crate::rtl::Table::new("tp_table").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.checkbox(&mut f.width_on, tl!("Preferred width:")));
r.cell(|ui| ui.add_enabled(f.width_on, len(&mut f.width, 0.1, unit)));
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Alignment:")));
r.cell(|ui| {
ui.horizontal(|ui| {
for (v, l) in [("left", "Left"), ("center", "Center"), ("right", "Right")] {
ui.radio_value(&mut f.align, v.to_string(), tl!(l));
}
});
});
});
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Indent from left:")));
r.cell(|ui| {
ui.add_enabled(f.align == "left", egui::DragValue::new(&mut f.indent).speed(0.01).range(-11.0..=22.0).measure(unit).max_decimals(2))
});
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Table direction:")));
r.cell(|ui| {
ui.horizontal(|ui| {
ui.radio_value(&mut f.rtl, false, tl!("Left-to-right"));
ui.radio_value(&mut f.rtl, true, tl!("Right-to-left"));
t.row(|r| {
r.cell(|ui| ui.label(tl!("Indent from left:")));
r.cell(|ui| {
ui.add_enabled(
f.align == "left",
egui::DragValue::new(&mut f.indent).speed(0.01).range(-11.0..=22.0).measure(unit).max_decimals(2),
)
});
});
});
});
heading(ui, "Row");
crate::rtl::Table::new("tp_row").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
let specify = r.cell(|ui| ui.checkbox(&mut f.row_height_on, tl!("Specify height:")));
r.cell(|ui| {
ui.horizontal(|ui| {
ui.add_enabled(f.row_height_on, len(&mut f.row_height, 0.02, unit));
ui.add_enabled_ui(f.row_height_on, |ui| {
let rule = craft_ui::ComboBox::from_id_salt("tp_rule")
.selected_text(tl!(if f.row_exact { "Exactly" } else { "At least" }))
.show_ui(ui, |ui| {
ui.selectable_value(&mut f.row_exact, false, tl!("At least"));
ui.selectable_value(&mut f.row_exact, true, tl!("Exactly"));
});
// A screen reader names the rule by the box it belongs to.
rule.response.labelled_by(specify.id);
t.row(|r| {
r.cell(|ui| ui.label(tl!("Table direction:")));
r.cell(|ui| {
ui.horizontal(|ui| {
ui.radio_value(&mut f.rtl, false, tl!("Left-to-right"));
ui.radio_value(&mut f.rtl, true, tl!("Right-to-left"));
});
});
});
});
});
super::paragraph::para_check(ui, &mut f.allow_break, tl!("Allow row to break across pages"), "allowBreak", &mut f.mixed);
super::paragraph::para_check(ui, &mut f.header_row, tl!("Repeat as header row on each page"), "headerRow", &mut f.mixed);
heading(ui, "Column");
crate::rtl::Table::new("tp_col").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.label(tl!("Preferred width:")));
r.cell(|ui| ui.add(len(&mut f.column_width, 0.1, unit)));
crate::widgets::section(ui, tl!("Row"), |ui| {
crate::rtl::Table::new("tp_row").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
let specify = r.cell(|ui| ui.checkbox(&mut f.row_height_on, tl!("Specify height:")));
r.cell(|ui| {
ui.horizontal(|ui| {
ui.add_enabled(f.row_height_on, len(&mut f.row_height, 0.02, unit));
ui.add_enabled_ui(f.row_height_on, |ui| {
let rule = craft_ui::ComboBox::from_id_salt("tp_rule")
.selected_text(tl!(if f.row_exact { "Exactly" } else { "At least" }))
.show_ui(ui, |ui| {
ui.selectable_value(&mut f.row_exact, false, tl!("At least"));
ui.selectable_value(&mut f.row_exact, true, tl!("Exactly"));
});
// A screen reader names the rule by the box it belongs to.
rule.response.labelled_by(specify.id);
});
});
});
});
});
super::paragraph::para_check(ui, &mut f.allow_break, tl!("Allow row to break across pages"), "allowBreak", &mut f.mixed);
super::paragraph::para_check(ui, &mut f.header_row, tl!("Repeat as header row on each page"), "headerRow", &mut f.mixed);
});
crate::widgets::section(ui, tl!("Column"), |ui| {
crate::rtl::Table::new("tp_col").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.label(tl!("Preferred width:")));
r.cell(|ui| ui.add(len(&mut f.column_width, 0.1, unit)));
});
});
});
heading(ui, "Cell");
crate::rtl::Table::new("tp_cell").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.checkbox(&mut f.cell_width_on, tl!("Preferred width:")));
r.cell(|ui| ui.add_enabled(f.cell_width_on, len(&mut f.cell_width, 0.1, unit)));
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Vertical alignment:")));
r.cell(|ui| {
ui.horizontal(|ui| {
for (v, l) in [("top", "Top"), ("center", "Center"), ("bottom", "Bottom")] {
ui.radio_value(&mut f.valign, v.to_string(), tl!(l));
}
crate::widgets::section(ui, tl!("Cell"), |ui| {
crate::rtl::Table::new("tp_cell").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.checkbox(&mut f.cell_width_on, tl!("Preferred width:")));
r.cell(|ui| ui.add_enabled(f.cell_width_on, len(&mut f.cell_width, 0.1, unit)));
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Vertical alignment:")));
r.cell(|ui| {
ui.horizontal(|ui| {
for (v, l) in [("top", "Top"), ("center", "Center"), ("bottom", "Bottom")] {
ui.radio_value(&mut f.valign, v.to_string(), tl!(l));
}
});
});
});
});
+21
View File
@@ -1868,6 +1868,27 @@ fn the_custom_properties_dialog_leaves_imported_non_text_properties_alone() {
assert_eq!(kinds, [("Status", "lpwstr"), ("Count", "i4")], "Cancel leaves the imported property as it was");
}
/// A tall dialog on a short screen stays inside it and scrolls.
#[test]
fn a_tall_dialog_fits_a_short_screen() {
let mut app = app_with("Some text");
app.dialog = Dialog::open("pageSetup", &mut app);
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 360.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();
}
let id = egui::Id::unique(("dialog", "Page Setup"));
let rect = h.ctx.memory(|m| m.area_rect(id)).expect("the dialog is open");
assert!(rect.height() <= 360.5, "the dialog is {}pt tall on a 360pt screen", rect.height());
}
/// #3859: a dialog is modal, as in Word. While Font is open, typing (from the frame it opens),
/// Mod+O and a click on File reach nothing behind it, and the dialog itself still works. Find
/// and Replace is modeless: with it open, File still opens.
+193 -7
View File
@@ -12,6 +12,7 @@ use std::path::{Path, PathBuf};
use egui::{Align2, Rect, Sense, Ui, pos2, vec2};
use crate::file_dialogs::{AfterPick, FileDialogRequest, open_filters};
use crate::print_page::{EXPORT_FORMATS, export_file_ext, export_name, is_document_ext};
use crate::theme::{Tokens, regular};
use crate::{WordApp, icons};
@@ -138,6 +139,8 @@ pub(crate) struct FileBrowser {
/// The file types, as (label, extensions).
filters: Vec<(String, Vec<String>)>,
filter: usize,
/// Exporting: the format behind each type, which `after` follows; empty otherwise.
exports: Vec<String>,
listing: Result<Listing, String>,
/// The highlighted entry.
selected: Option<PathBuf>,
@@ -158,6 +161,15 @@ impl FileBrowser {
(name.clone(), f)
}
};
// Exporting (#3535): File › Export's formats are the types, starting on the one asked for.
let (filters, filter, exports) = match &after {
AfterPick::Export { ext } => (
EXPORT_FORMATS.iter().map(|&(l, f)| (l.to_string(), vec![export_file_ext(f).to_string()])).collect(),
EXPORT_FORMATS.iter().position(|&(_, f)| f == ext.as_str()).unwrap_or(0),
EXPORT_FORMATS.iter().map(|&(_, f)| f.to_string()).collect(),
),
_ => (filters, 0, Vec::new()),
};
let mut b = FileBrowser {
req,
after,
@@ -166,7 +178,8 @@ impl FileBrowser {
location: String::new(),
name,
filters,
filter: 0,
filter,
exports,
listing: Ok(Listing::default()),
selected: None,
note: Note::None,
@@ -189,6 +202,16 @@ impl FileBrowser {
self.note = Note::None;
}
/// A type was chosen: when exporting it is the format, and the name's export extension follows it.
fn type_changed(&mut self) {
let Some(format) = self.exports.get(self.filter).cloned() else { return };
// Only a known document extension is replaced; `notes.v2` keeps its `.v2`.
if Path::new(&self.name).extension().and_then(|e| e.to_str()).is_some_and(is_document_ext) {
self.name = export_name(&self.name, &format);
}
self.after = AfterPick::Export { ext: format };
}
fn up(&mut self) {
if let Some(parent) = self.dir.parent().map(Path::to_path_buf) {
self.navigate(parent);
@@ -196,8 +219,8 @@ impl FileBrowser {
}
/// OK: a highlighted folder, or a typed folder, is opened; otherwise the typed name is the
/// pick. Save adds the chosen type's extension to a name without one and asks once more
/// before replacing a file; Open wants a file that exists.
/// pick. Save adds the chosen type's extension to a name without one (an export replaces a
/// known document extension with the type's) and asks once more before replacing a file; Open wants a file that exists.
pub(crate) fn accept(&mut self) -> Step {
if let Some(dir) = self.selected.take().filter(|p| p.is_dir()) {
self.navigate(dir);
@@ -218,7 +241,11 @@ impl FileBrowser {
Step::Stay
}
FileDialogRequest::Save { .. } => {
if path.extension().is_none()
if let AfterPick::Export { ext } = &self.after {
// The chosen type is the format: its extension replaces a known document
// extension on the name, and is added to any other.
path = PathBuf::from(export_name(&path.to_string_lossy(), ext));
} else if path.extension().is_none()
&& let Some(ext) = self.exts().first().filter(|e| e.as_str() != "*")
{
path.set_extension(ext);
@@ -273,10 +300,11 @@ impl WordApp {
self.file_browser.open = Some(Box::new(FileBrowser::new(req, after, start, unavailable)));
}
/// `ui.fileBrowser`: the built-in browser for `purpose` (document, picture, recipients, save),
/// even when a system dialog was asked for and never showed up (it is given up as cancelled).
/// `ui.fileBrowser`: the built-in browser for `purpose` (document, picture, recipients, save,
/// export), even when a system dialog was asked for and never showed up (it is given up as cancelled).
pub(crate) fn browse_builtin(&mut self, purpose: &str) {
self.give_up_file_dialog();
// An export that was waiting on the system dialog keeps its format.
let pending = self.give_up_file_dialog();
if self.file_browser.open.is_some() {
return;
}
@@ -287,6 +315,11 @@ impl WordApp {
FileDialogRequest::Save { name: self.default_save_name(), dir: None },
AfterPick::SaveAs { after: crate::file_dialogs::AfterSave::Nothing, document: self.session.document_id() },
),
"export" => {
let ext = pending.unwrap_or_else(|| "pdf".into());
let name = format!("{}.{}", self.title_stem(), export_file_ext(&ext));
(FileDialogRequest::Save { name, dir: None }, AfterPick::Export { ext })
}
_ => (FileDialogRequest::Open { purpose: "document".into() }, AfterPick::OpenDocument { document: self.session.document_id() }),
};
self.show_file_browser(req, after, false);
@@ -471,6 +504,7 @@ fn body(ui: &mut Ui, b: &mut FileBrowser, t: &Tokens) -> Option<Option<PathBuf>>
refilter = b.filter != before;
});
if refilter {
b.type_changed();
b.navigate(b.dir.clone());
}
ui.add_space(8.0);
@@ -731,6 +765,158 @@ mod tests {
assert!(crate::keytips::suppressed(&a, &ctx));
}
/// #3535: exporting offers File › Export's formats as the types; the chosen one is the format,
/// the name's extension follows it, and the export writes that format.
#[test]
fn export_types_choose_the_format_and_the_extension() {
let dir = scratch("export");
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), Services::default());
a.run("text.insert", json!({"text": "Exported in WordCraft"})).unwrap();
a.run("ui.fileBrowser", json!({"purpose": "export"})).unwrap();
let b = a.file_browser.open.as_mut().expect("the built-in browser is open");
assert_eq!(b.filters.len(), EXPORT_FORMATS.len());
assert_eq!(b.filters[b.filter].0, "PDF document (*.pdf)");
assert!(b.name.ends_with(".pdf"), "{}", b.name);
b.filter = b.filters.iter().position(|(l, _)| l == "Plain text (*.txt)").unwrap();
b.type_changed();
assert!(b.name.ends_with(".txt"), "{}", b.name);
assert!(matches!(&b.after, AfterPick::Export { ext } if ext == "txt"));
b.navigate(dir.clone());
// A name typed afterwards with another document extension gets the chosen format's instead,
// and a name with an unknown one keeps it.
b.name = "notes.v2".into();
let Step::Pick(v2) = b.accept() else { panic!("picked") };
assert_eq!(v2.file_name().unwrap(), "notes.v2.txt");
b.name = "notes.docx".into();
let Step::Pick(path) = b.accept() else { panic!("picked") };
assert_eq!(path.file_name().unwrap(), "notes.txt");
for (typed, want) in [
("a.PDF", "a.txt"),
("a.htm", "a.txt"),
("a", "a.txt"),
("a.TXT", "a.TXT"),
("sub/a.rtf", "sub/a.txt"),
(".txt", ".txt.txt"),
(".docx", ".docx.txt"),
("sub/.docx", "sub/.docx.txt"),
("a.", "a.txt"),
("a..", "a.txt"),
] {
assert_eq!(crate::print_page::export_name(typed, "txt"), want);
}
a.close_file_browser(Some(path.clone()));
assert!(std::fs::read_to_string(&path).unwrap().contains("Exported in WordCraft"));
// Word 2003 XML starts on its own type, though Word XML writes .xml too.
let req = FileDialogRequest::Save { name: "x.xml".into(), dir: None };
let b = FileBrowser::new(req, AfterPick::Export { ext: crate::print_page::EXPORT_WORD_2003.into() }, dir.clone(), false);
assert_eq!(b.filters[b.filter].0, "Word 2003 XML Document (*.xml)");
let _ = std::fs::remove_dir_all(&dir);
}
/// The OpenDocument template and flat-XML exports are types of their own: the name gets
/// their extension, and the export saves by it.
#[test]
fn export_types_include_the_opendocument_template_and_flat_xml() {
let dir = scratch("export_ott");
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), Services::default());
a.run("text.insert", json!({"text": "Template text"})).unwrap();
for (label, ext) in [("OpenDocument Text Template (*.ott)", "ott"), ("Flat OpenDocument Text (*.fodt)", "fodt")] {
let req = FileDialogRequest::Save { name: "x.pdf".into(), dir: None };
let mut b = FileBrowser::new(req, AfterPick::Export { ext: "pdf".into() }, dir.clone(), false);
b.filter = b.filters.iter().position(|(l, _)| l == label).unwrap();
b.type_changed();
assert_eq!(b.name, format!("x.{ext}"));
b.navigate(dir.clone());
let Step::Pick(path) = b.accept() else { panic!("picked") };
assert_eq!(path, dir.join(format!("x.{ext}")));
a.finish_pick(AfterPick::Export { ext: ext.into() }, Some(path.to_string_lossy().into_owned())).unwrap();
assert!(path.is_file(), "{ext} written");
}
let _ = std::fs::remove_dir_all(&dir);
}
/// An export waiting on a system dialog that never showed up keeps its format when Browse
/// in WordCraft… takes over, instead of starting over on PDF.
#[test]
fn browse_in_wordcraft_keeps_a_pending_exports_format() {
let services = Services {
file_dialog: Some(Box::new(|_req| {
let (tx, rx) = channel();
// The system dialog never answers.
std::mem::forget(tx);
rx
})),
..Default::default()
};
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), services);
a.export_dialog("rtf");
assert!(a.file_dialog.is_some(), "waiting on the system dialog");
a.run("ui.fileBrowser", json!({"purpose": "export"})).unwrap();
assert!(a.file_dialog.is_none(), "the system dialog is given up");
let b = a.file_browser.open.as_ref().expect("the built-in browser is open");
assert!(matches!(&b.after, AfterPick::Export { ext } if ext == "rtf"));
assert_eq!(b.filters[b.filter].0, "Rich Text Format (*.rtf)");
assert!(b.name.ends_with(".rtf"), "{}", b.name);
}
/// Word XML chosen as the export type wins over a Word 2003 XML file already at that path,
/// whose format a save by path alone would keep.
#[test]
fn exporting_word_xml_over_a_word_2003_file_writes_word_xml() {
let dir = scratch("export_xml");
let path = dir.join("letter.xml").to_string_lossy().into_owned();
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), Services::default());
a.run("text.insert", json!({"text": "Dear reader"})).unwrap();
a.finish_pick(AfterPick::Export { ext: crate::print_page::EXPORT_WORD_2003.into() }, Some(path.clone())).unwrap();
assert!(std::fs::read_to_string(&path).unwrap().contains("w:wordDocument"));
a.finish_pick(AfterPick::Export { ext: "xml".into() }, Some(path.clone())).unwrap();
let xml = std::fs::read_to_string(&path).unwrap();
assert!(xml.contains("pkg:package") && !xml.contains("w:wordDocument"), "Word XML, not Word 2003 XML");
let _ = std::fs::remove_dir_all(&dir);
}
/// A system Save dialog lets the user type a name without `.xml`; Word XML export still
/// writes `<name>.xml` (as the built-in browser does) and won't silently replace an existing one.
#[test]
fn exporting_word_xml_to_a_name_without_xml_appends_the_extension() {
let dir = scratch("export_xml_ext");
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), Services::default());
a.run("text.insert", json!({"text": "Dear reader"})).unwrap();
let bare = dir.join("letter").to_string_lossy().into_owned();
a.finish_pick(AfterPick::Export { ext: "xml".into() }, Some(bare)).unwrap();
let xml = std::fs::read_to_string(dir.join("letter.xml")).unwrap();
assert!(xml.contains("pkg:package"), "Word XML written at letter.xml");
// A known document extension gives way to .xml; an unknown one stays.
let docx = dir.join("notes.docx").to_string_lossy().into_owned();
a.finish_pick(AfterPick::Export { ext: "xml".into() }, Some(docx)).unwrap();
assert!(dir.join("notes.xml").is_file());
let v2 = dir.join("notes.v2").to_string_lossy().into_owned();
a.finish_pick(AfterPick::Export { ext: "xml".into() }, Some(v2)).unwrap();
assert!(dir.join("notes.v2.xml").is_file());
// The resulting name already exists: the system dialog never confirmed it, so refuse.
let bare = dir.join("letter").to_string_lossy().into_owned();
assert!(a.finish_pick(AfterPick::Export { ext: "xml".into() }, Some(bare)).is_err());
let _ = std::fs::remove_dir_all(&dir);
}
/// A name that is only a known extension (`.docx`) is a stem for `Path::extension`, which the
/// engine's explicit-format guard reads too: exporting Word XML to it must name a real
/// `.xml` file and write it (a bare `.xml` would be refused, writing nothing).
#[test]
fn exporting_word_xml_to_a_dotfile_name_writes_the_file() {
let dir = scratch("export_xml_dotfile");
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), Services::default());
a.run("text.insert", json!({"text": "Dear reader"})).unwrap();
for format in ["xml", crate::print_page::EXPORT_WORD_2003] {
let typed = dir.join(".docx").to_string_lossy().into_owned();
a.finish_pick(AfterPick::Export { ext: format.into() }, Some(typed)).unwrap();
let written = dir.join(".docx.xml");
assert!(std::fs::read_to_string(&written).unwrap().contains(if format == "xml" { "pkg:package" } else { "w:wordDocument" }));
let _ = std::fs::remove_file(&written);
}
let _ = std::fs::remove_dir_all(&dir);
}
/// #3037: an empty folder (or a type filter that matches nothing) says so instead of a blank
/// box; a matching file replaces the hint.
#[test]
+50 -12
View File
@@ -171,15 +171,17 @@ impl WordApp {
}
}
/// Treat the system dialog the host is showing as cancelled, e.g. one that never showed up.
/// Treat the system dialog the host is showing as cancelled, e.g. one that never showed up;
/// returns the format of the export it was for, if any.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn give_up_file_dialog(&mut self) {
pub(crate) fn give_up_file_dialog(&mut self) -> Option<String> {
if let Some(cancel) = &self.services.cancel_file_dialog {
cancel();
}
if let Some(d) = self.file_dialog.take() {
let _ = self.finish_pick(d.after, None);
}
let d = self.file_dialog.take()?;
let export = if let AfterPick::Export { ext } = &d.after { Some(ext.clone()) } else { None };
let _ = self.finish_pick(d.after, None);
export
}
/// The host couldn't show a system dialog (#576): ask in the built-in browser instead, which
@@ -295,16 +297,40 @@ impl WordApp {
Ok(json!({"picked": true}))
}
AfterPick::Export { ext } => {
let Some(path) = picked else { return Ok(json!({"cancelled": true})) };
let Some(mut path) = picked else {
// Cancelled: an earlier refusal is not news any more.
self.clear_export_error();
return Ok(json!({"cancelled": true}));
};
let r = if ext == "png" {
self.run("file.exportPng", json!({"path": path}))
} else if ext == crate::print_page::EXPORT_WORD_2003 {
self.run("file.saveAs", json!({"path": path, "format": ext}))
} else if ext == "xml" || ext == crate::print_page::EXPORT_WORD_2003 {
// The engine takes an explicit format only for an .xml path, and a system Save
// dialog lets the user type any name: give it the extension, as the built-in
// browser does (`notes.docx` becomes `notes.xml`, `notes.v2` `notes.v2.xml`).
let named = crate::print_page::export_name(&path, "xml");
if named != path {
path = named;
// The dialog only confirmed the name it was given, not this one.
if std::path::Path::new(&path).exists() {
// Callers drop the result, so say it where the person sees it.
return Err(self.fail_export(format!("{path} already exists; choose another name")));
}
}
// Word XML even over a Word 2003 XML file, which a save by path would keep.
let format = if ext == "xml" { wordcraft_engine::cmd::file::FORMAT_FLAT_OPC } else { crate::print_page::EXPORT_WORD_2003 };
self.run("file.saveAs", json!({"path": path, "format": format}))
} else {
self.run("file.saveAs", json!({"path": path}))
};
if r.is_ok() {
self.status(crate::i18n::fmt(tl!("Exported {path}"), &[("path", &crate::i18n::isolate_path(&path))]));
match &r {
Ok(_) => {
self.clear_export_error();
self.status(crate::i18n::fmt(tl!("Exported {path}"), &[("path", &crate::i18n::isolate_path(&path))]));
}
Err(e) => {
self.fail_export(e.clone());
}
}
r
}
@@ -383,6 +409,18 @@ impl WordApp {
}
}
/// An export failed or was refused: say so on the status bar and, for the Export page,
/// there too, since Backstage's render loop skips the status bar (callers drop the result).
fn fail_export(&mut self, error: String) -> String {
self.status(error.clone());
self.export_error = error.clone();
error
}
fn clear_export_error(&mut self) {
self.export_error.clear();
}
/// Drop a Save As page error once a later attempt has actually saved.
fn clear_save_as_error(&mut self) {
if let Some(ctx) = self.ctx.clone() {
@@ -436,8 +474,8 @@ impl WordApp {
/// File › Export: ask where to save a copy in this format, then write it.
pub(crate) fn export_dialog(&mut self, ext: &str) {
let file_ext = if ext == crate::print_page::EXPORT_WORD_2003 { "xml" } else { ext };
let name = format!("{}.{file_ext}", self.title_stem());
let name = format!("{}.{}", self.title_stem(), crate::print_page::export_file_ext(ext));
// A refusal or failure is reported by `finish_pick` itself (Export page and status bar).
let _ = self.ask_file(FileDialogRequest::Save { name, dir: None }, AfterPick::Export { ext: ext.to_string() });
}
+33
View File
@@ -465,6 +465,39 @@ fn export_pdf_without_a_path_asks_where_to_save() {
let _ = std::fs::remove_dir_all(&dir);
}
/// An explicit web PDF export keeps an existing PDF suffix regardless of ASCII case.
#[test]
fn web_pdf_export_keeps_an_existing_suffix_in_any_case() {
let downloaded = Rc::new(RefCell::new(Vec::new()));
let captured = downloaded.clone();
let services = Services {
download: Some(Box::new(move |name, bytes| {
captured.borrow_mut().push((name.to_string(), bytes.starts_with(b"%PDF")));
Ok(())
})),
..Default::default()
};
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), services);
for (name, expected) in [
("Report.pdf", "Report.pdf"),
("Report.PDF", "Report.PDF"),
("Résumé.PdF", "Résumé.PdF"),
("😀.PDF", "😀.PDF"),
(".hidden.PDF", ".hidden.PDF"),
("Report..PDF", "Report..PDF"),
("é", "é.pdf"),
("😀", "😀.pdf"),
("Report.pdf.exe", "Report.pdf.exe.pdf"),
("Report.PDF", "Report.PDF.pdf"),
("Report.pdf.", "Report.pdf..pdf"),
("Report", "Report.pdf"),
] {
let result = a.execute("file.exportPdf", json!({"path": name})).unwrap();
assert_eq!(result["downloaded"], expected, "{name}");
assert_eq!(downloaded.borrow().last().cloned(), Some((expected.to_string(), true)), "{name}");
}
}
/// Open, Save As and Export PNG from the command search (no path) ask for a file the same way.
#[test]
fn file_commands_without_a_path_ask_for_one() {
+67 -4
View File
@@ -46,6 +46,8 @@ pub fn canvas_events(app: &mut WordApp, ctx: &egui::Context) {
interrupted_preedit: std::mem::take(&mut app.canvas.ime_interrupted_preedit),
interrupted_replacement: EquationReplacementDrop::None,
};
let now = ctx.input(|i| i.time);
expire_paste_wait(app, now);
let held = ctx.input(|i| i.modifiers);
if held.command {
app.canvas.paste_mods = Some(held);
@@ -60,7 +62,8 @@ pub fn canvas_events(app: &mut WordApp, ctx: &egui::Context) {
continue;
}
note_key_state(app, &e);
if drop_refused_replacement(app, &e, &mut batch)
if ignored_paste(app, &e)
|| drop_refused_replacement(app, &e, &mut batch)
|| prefilter(app, ctx, &e, alt_codes)
|| paste_release(app, &e)
|| equation_event(app, ctx, &e, &mut batch)
@@ -69,6 +72,27 @@ pub fn canvas_events(app: &mut WordApp, ctx: &egui::Context) {
}
handle_event(app, ctx, e);
}
if app.canvas.ignore_next_paste && app.canvas.paste_wait_since.is_none() {
app.canvas.paste_wait_since = Some(now);
}
}
/// How long the paste event paired with Mod+Shift+V is waited for. A browser sends it with the
/// key, in the same frame; with no text on the clipboard it sends none at all.
const PASTE_WAIT: f64 = 1.0;
/// Ends a wait for the paired paste event that never came, so a later paste (a browser menu's,
/// say) isn't dropped (#5616).
fn expire_paste_wait(app: &mut WordApp, now: f64) {
if !app.canvas.ignore_next_paste {
app.canvas.paste_wait_since = None;
} else if app.canvas.paste_wait_since.is_some_and(|t| now - t > PASTE_WAIT) {
app.canvas.ignore_next_paste = false;
app.canvas.paste_wait_since = None;
// No key came since the chord (any key ends the wait), so noted modifiers are the
// chord's: a later paste reads the modifiers held then.
app.canvas.paste_event_mods = None;
}
}
/// State carried across the events of one raw batch.
@@ -158,20 +182,54 @@ fn stale_composition(app: &mut WordApp, e: &egui::Event, b: &mut Batch) -> bool
fn note_key_state(app: &mut WordApp, e: &egui::Event) {
// Which presses reached the canvas, and the modifiers held with Mod, in event order: Mod
// can go down and up within one frame, leaving the frame's modifiers without it.
if matches!(e, egui::Event::Key { pressed: true, key, .. } if !is_modifier_key(*key))
|| matches!(e, egui::Event::WindowFocused(_) | egui::Event::PointerButton { pressed: true, .. })
{
app.canvas.ignore_next_paste = false;
}
match &e {
egui::Event::ModifiersChanged(m) if m.command => app.canvas.paste_mods = Some(*m),
egui::Event::Key { key: Key::V | Key::Paste, pressed: true, .. } => app.canvas.v_pressed = true,
egui::Event::ModifiersChanged(m) => {
app.canvas.paste_event_mods = m.command.then_some(*m);
if m.command {
app.canvas.paste_mods = Some(*m);
}
}
egui::Event::Key { key: Key::V | Key::Paste, pressed: true, modifiers, .. } => {
app.canvas.v_pressed = true;
app.canvas.paste_event_mods = modifiers.command.then_some(*modifiers);
}
egui::Event::Key { key, pressed: true, modifiers, .. } if !is_modifier_key(*key) => {
app.canvas.paste_mods = modifiers.command.then_some(*modifiers);
// An unrelated key's modifiers mustn't steer a later keyless paste.
app.canvas.paste_event_mods = None;
}
egui::Event::PointerButton { pressed: true, .. } => app.canvas.paste_event_mods = None,
egui::Event::WindowFocused(_) => {
app.canvas.v_pressed = false;
// A V release lost to a focus change must not swallow a later Mod+V's picture.
app.canvas.pasted = false;
app.canvas.paste_mods = None;
app.canvas.paste_event_mods = None;
}
_ => {}
}
}
/// The browser's paste event that follows a Mod+Shift+V that pasted formatting is the same
/// keystroke: ignored before an equation or a picture-file paste can take it (#5616).
/// With no text on the clipboard eframe sends no paste event, so the wait ends at the next key,
/// pointer press or focus change, or after `PASTE_WAIT`.
fn ignored_paste(app: &mut WordApp, e: &egui::Event) -> bool {
if matches!(e, egui::Event::Paste(_)) && std::mem::take(&mut app.canvas.ignore_next_paste) {
// Not a Mod+V with no text either: the release mustn't paste a picture.
app.canvas.pasted = true;
// Its Mod+Shift is used up too, or a later menu-bar paste would read as Keep Text Only.
app.canvas.paste_event_mods = None;
return true;
}
false
}
/// The replacement paired with a refused equation deletion is dropped.
fn drop_refused_replacement(app: &mut WordApp, e: &egui::Event, b: &mut Batch) -> bool {
// The replacement is the event immediately after the refused deletion: one `Commit`,
@@ -509,10 +567,15 @@ fn handle_event(app: &mut WordApp, ctx: &egui::Context, e: egui::Event) {
egui::Event::Ime(egui::ImeEvent::Commit(text)) => ime_commit(app, text),
egui::Event::Paste(t) => {
// Mod+Alt+V arrives as a paste too (the shell reads the clipboard): Paste Special.
let m = ctx.input(|i| i.modifiers);
// The modifiers held with Mod in event order: Shift may be up by the frame's end.
app.canvas.paste_mods = None;
let m = app.canvas.paste_event_mods.take().unwrap_or_else(|| ctx.input(|i| i.modifiers));
// A browser sends Mod+Shift+V as a paste too: Keep Text Only, as the key does on the
// desktop (#1537). (egui-winit sends that chord as a key, and Shift+Insert has no Mod.)
let id = match (m.alt, m.shift) {
(true, true) => "edit.pasteText",
(true, false) => "edit.pasteSpecial",
(false, true) if m.command => "edit.pasteText",
_ => "edit.paste",
};
let _ = app.run(id, json!({"text": t}));
+26 -1
View File
@@ -132,7 +132,32 @@ pub(super) fn dispatch(app: &mut WordApp, key: Key, m: Modifiers) -> bool {
if m.alt && !crate::widgets::enabled(app, spec.id) {
return false;
}
let _ = app.run(spec.id, json!({}));
// Mod+Shift+V pastes the formatting Mod+Shift+C (or the Format Painter) picked up; with
// none picked up it pastes the clipboard as text only, as Word for Windows does (#1537,
// #4943). Another key bound to Paste Formatting only pastes formatting.
let id = if spec.id == "edit.pasteFormat" {
let formatting = app.session.painter.is_some() || app.session.copied_format.is_some();
let chord = key == Key::V && m.command && m.shift && !m.alt;
// A browser sends a paste event after that chord (the desktop doesn't): after
// pasting formatting it's ignored; with none, it pastes the text there, once. A
// rebinding to another key makes no paste event.
let paste_follows = chord && app.canvas.paste_event_follows_chord;
app.canvas.ignore_next_paste = formatting && paste_follows;
// Handled from the canvas's key events: its V release (Shift may go up first, so the
// release reads as plain Mod+V) mustn't paste again through the picture hook. Not
// from `global_shortcuts` (canvas unfocused), where no release is ever seen.
if chord && app.canvas.focused {
app.canvas.pasted = true;
}
app.canvas.paste_wait_since = None;
if !formatting && paste_follows {
return true;
}
if !formatting && chord { "edit.pasteText" } else { spec.id }
} else {
spec.id
};
let _ = app.run(id, json!({}));
return true;
}
let Some(name) = name else { return false };
+259
View File
@@ -133,6 +133,124 @@ fn only_plain_paste_releases_paste_a_clipboard_picture() {
assert!(!is_paste_special_release(Key::V, m(true, true, true)) && !is_paste_special_release(Key::V, m(true, false, false)));
}
/// #1537: a browser sends Mod+Shift+V as a paste event; it pastes text only, in the destination's
/// formatting, though the clipboard also holds bold HTML. Plain Mod+V keeps the HTML's bold.
#[test]
fn a_mod_shift_paste_event_keeps_text_only() {
for (modifiers, bold) in [(Modifiers::COMMAND | Modifiers::SHIFT, false), (Modifiers::COMMAND, true)] {
let services = crate::Services { clipboard_html: Some(Box::new(|| Some("<p><b>external</b></p>".into()))), ..Default::default() };
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), services);
let ctx = egui::Context::default();
mods_frame(&ctx, &mut a, modifiers, vec![egui::Event::Paste("external".into())]);
assert_eq!(a.session.doc.plain_text(wordcraft_doc::StoryRef::Body), "external", "{modifiers:?}");
let state = a.session.run("format.state", &json!({})).unwrap();
assert_eq!(state.get("bold").and_then(serde_json::Value::as_bool) == Some(true), bold, "{modifiers:?}: {state}");
}
}
/// #5616: a browser sends Mod+Shift+V as its key and then a paste event. After Mod+Shift+C the
/// key pastes the formatting and the paste event that follows doesn't replace the text; a later
/// Mod+V still pastes.
#[test]
fn a_paste_event_after_mod_shift_v_pasted_formatting_is_ignored() {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
a.canvas.paste_event_follows_chord = true;
a.run("text.insert", json!({"text": "source target"})).unwrap();
a.run("select.text", json!({"text": "source"})).unwrap();
a.run("format.bold", json!({})).unwrap();
a.run("edit.copyFormat", json!({})).unwrap();
a.run("select.text", json!({"text": "target"})).unwrap();
let ctx = egui::Context::default();
let chord = Modifiers::COMMAND | Modifiers::SHIFT;
mods_frame(&ctx, &mut a, chord, vec![key_event(Key::V, true, chord), egui::Event::Paste("clipboard text".into())]);
let body = |a: &WordApp| a.session.doc.plain_text(wordcraft_doc::StoryRef::Body);
assert_eq!(body(&a), "source target", "the paste event didn't replace the formatted text");
let bold = a.session.run("format.state", &json!({})).unwrap().get("bold").and_then(serde_json::Value::as_bool);
assert_eq!(bold, Some(true), "the key pasted the formatting");
mods_frame(&ctx, &mut a, Modifiers::COMMAND, vec![key_event(Key::V, true, Modifiers::COMMAND), egui::Event::Paste("pasted".into())]);
assert_eq!(body(&a), "source pasted", "the next Mod+V pastes");
}
/// #5616: on a desktop, Mod+Shift+V with nothing copied pastes the text; releasing Shift before V
/// leaves the V release as plain Mod+V, which mustn't paste a second time through the picture hook.
/// Likewise after pasting copied formatting.
#[test]
fn mod_shift_v_released_shift_first_pastes_once() {
let chord = Modifiers { ctrl: true, command: true, shift: true, ..Default::default() };
let ctrl = Modifiers { shift: false, ..chord };
for formatting in [false, true] {
let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
let seen = calls.clone();
let services = crate::Services {
clipboard_picture: Some(Box::new(move || {
seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
None
})),
..Default::default()
};
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), services);
a.canvas.paste_event_follows_chord = false;
a.canvas.focused = true;
a.run("text.insert", json!({"text": "source target"})).unwrap();
if formatting {
a.run("select.text", json!({"text": "source"})).unwrap();
a.run("format.bold", json!({})).unwrap();
a.run("edit.copyFormat", json!({})).unwrap();
}
// The clipboard holds "source"; "target" is selected.
a.run("select.text", json!({"text": "source"})).unwrap();
a.run("edit.copy", json!({})).unwrap();
a.run("select.text", json!({"text": "target"})).unwrap();
let ctx = egui::Context::default();
mods_frame(&ctx, &mut a, chord, vec![key_event(Key::V, true, chord)]);
mods_frame(&ctx, &mut a, ctrl, vec![key_event(Key::ShiftLeft, false, ctrl)]);
mods_frame(&ctx, &mut a, ctrl, vec![key_event(Key::V, false, ctrl)]);
let body = a.session.doc.plain_text(wordcraft_doc::StoryRef::Body);
assert_eq!(body, if formatting { "source target" } else { "source source" }, "formatting={formatting}");
assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 0, "formatting={formatting}: the release asked for a picture");
// The release used it up: a later plain Mod+V release still pastes a picture.
assert!(!a.canvas.pasted);
}
}
/// #5616: Mod+Shift+V pressed with the canvas unfocused (after a ribbon click) runs through the
/// global shortcuts, and its V release never reaches the canvas: it mustn't leave a paste marked
/// done that swallows the clipboard picture of a later Mod+V.
#[test]
fn a_global_mod_shift_v_leaves_the_next_mod_v_picture_paste_alone() {
let ctx = egui::Context::default();
let mut a = picture_app();
a.canvas.paste_event_follows_chord = false;
a.canvas.focused = false;
let chord = Modifiers { ctrl: true, command: true, shift: true, ..Default::default() };
let events = vec![egui::Event::ModifiersChanged(chord), key_event(Key::V, true, chord)];
ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| super::shortcuts::global_shortcuts(&mut a, ui.ctx()))
.drop_without_applying_deltas();
assert!(!a.canvas.pasted, "no canvas release is coming to use the mark up");
a.canvas.focused = true;
let ctrl = Modifiers { shift: false, ..chord };
mods_frame(&ctx, &mut a, ctrl, vec![key_event(Key::V, false, ctrl)]);
assert_eq!(pictures(&mut a), 1);
}
/// #5616: Mod+Shift+V pressed, then focus leaves before V is released: the lost release mustn't
/// swallow a later Mod+V's picture.
#[test]
fn a_focus_change_clears_the_mod_shift_v_paste_mark() {
let ctx = egui::Context::default();
let mut a = picture_app();
a.canvas.paste_event_follows_chord = false;
a.canvas.focused = true;
let chord = Modifiers { ctrl: true, command: true, shift: true, ..Default::default() };
mods_frame(&ctx, &mut a, chord, vec![key_event(Key::V, true, chord)]);
assert!(a.canvas.pasted);
mods_frame(&ctx, &mut a, Modifiers::NONE, vec![egui::Event::WindowFocused(false)]);
mods_frame(&ctx, &mut a, Modifiers::NONE, vec![egui::Event::WindowFocused(true)]);
let ctrl = Modifiers { shift: false, ..chord };
mods_frame(&ctx, &mut a, ctrl, vec![key_event(Key::V, false, ctrl)]);
assert_eq!(pictures(&mut a), 1);
}
/// An empty document whose clipboard holds a 4 × 4 picture.
fn picture_app() -> WordApp {
use crate::paste_picture::ClipboardPicture;
@@ -154,6 +272,129 @@ fn mods_frame(ctx: &egui::Context, a: &mut WordApp, modifiers: Modifiers, events
ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| canvas_events(a, ui.ctx())).drop_without_applying_deltas();
}
/// A source word in bold with Copy Formatting picked up, and "target" selected.
fn copied_bold_app() -> WordApp {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
a.run("text.insert", json!({"text": "source target"})).unwrap();
a.run("select.text", json!({"text": "source"})).unwrap();
a.run("format.bold", json!({})).unwrap();
a.run("edit.copyFormat", json!({})).unwrap();
a.run("select.text", json!({"text": "target"})).unwrap();
a
}
/// #5616: on a desktop no paste event follows Mod+Shift+V's key, so none is swallowed: a later
/// paste (from a menu, say) pastes.
#[test]
fn a_desktop_paste_after_mod_shift_v_is_not_swallowed() {
let mut a = copied_bold_app();
assert!(!a.canvas.paste_event_follows_chord || cfg!(target_arch = "wasm32"));
a.canvas.paste_event_follows_chord = false;
let ctx = egui::Context::default();
let chord = Modifiers::COMMAND | Modifiers::SHIFT;
mods_frame(&ctx, &mut a, chord, vec![key_event(Key::V, true, chord)]);
assert!(!a.canvas.ignore_next_paste);
mods_frame(&ctx, &mut a, Modifiers::NONE, vec![egui::Event::Paste("later".into())]);
assert_eq!(a.session.doc.plain_text(wordcraft_doc::StoryRef::Body), "source later");
}
/// #5616: a pointer press ends the wait for the browser's paste event, so a later keyless paste
/// (context menu, touch) isn't swallowed.
#[test]
fn a_pointer_press_ends_the_wait_for_the_ignored_paste() {
let mut a = copied_bold_app();
a.canvas.ignore_next_paste = true;
let ctx = egui::Context::default();
let press =
egui::Event::PointerButton { pos: egui::pos2(5.0, 5.0), button: egui::PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE };
mods_frame(&ctx, &mut a, Modifiers::NONE, vec![press]);
assert!(!a.canvas.ignore_next_paste);
}
/// #5616: the modifiers noted for a paste are used up by it: a later paste with no Mod held
/// keeps the HTML's formatting instead of reading the stale Mod+Shift.
#[test]
fn a_paste_event_uses_up_the_noted_paste_modifiers() {
let services = crate::Services { clipboard_html: Some(Box::new(|| Some("<p><b>external</b></p>".into()))), ..Default::default() };
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), services);
let ctx = egui::Context::default();
mods_frame(&ctx, &mut a, Modifiers::COMMAND | Modifiers::SHIFT, vec![egui::Event::Paste("external".into())]);
assert!(a.canvas.paste_mods.is_none());
a.run("select.all", json!({})).unwrap();
mods_frame(&ctx, &mut a, Modifiers::NONE, vec![egui::Event::Paste("external".into())]);
let bold = a.session.run("format.state", &json!({})).unwrap().get("bold").and_then(serde_json::Value::as_bool);
assert_eq!(bold, Some(true), "the later paste was a plain paste");
}
/// #5616: the dropped browser paste uses up its Mod+Shift, so a later menu-bar paste with no key
/// or pointer press in between isn't read as Keep Text Only.
#[test]
fn the_ignored_paste_uses_up_its_paste_modifiers() {
let mut a = copied_bold_app();
a.canvas.paste_event_follows_chord = true;
let ctx = egui::Context::default();
let chord = Modifiers::COMMAND | Modifiers::SHIFT;
mods_frame(&ctx, &mut a, chord, vec![key_event(Key::V, true, chord), egui::Event::Paste("x".into())]);
assert!(!a.canvas.ignore_next_paste);
assert!(a.canvas.paste_event_mods.is_none());
}
/// #5616: with no text on the clipboard the browser sends no paste event after Mod+Shift+V; the
/// wait for it ends, so a later menu-bar paste with no key or pointer press in between pastes.
#[test]
fn a_menu_bar_paste_after_an_unpaired_mod_shift_v_pastes() {
let mut a = copied_bold_app();
a.canvas.paste_event_follows_chord = true;
let ctx = egui::Context::default();
let chord = Modifiers::COMMAND | Modifiers::SHIFT;
let frame = |a: &mut WordApp, time: f64, events: Vec<egui::Event>| {
ctx.run_ui(egui::RawInput { time: Some(time), events, ..Default::default() }, |ui| canvas_events(a, ui.ctx())).drop_without_applying_deltas();
};
frame(&mut a, 10.0, vec![egui::Event::ModifiersChanged(chord), key_event(Key::V, true, chord)]);
assert!(a.canvas.ignore_next_paste, "the key waits for its paired paste");
// No Mod release reaches the canvas (the menu bar takes it).
frame(&mut a, 10.5, vec![]);
assert!(a.canvas.ignore_next_paste, "still within the wait");
frame(&mut a, 12.0, vec![]);
assert!(!a.canvas.ignore_next_paste, "the wait is over");
assert!(a.canvas.paste_event_mods.is_none(), "the chord's Mod+Shift is used up");
frame(&mut a, 12.1, vec![egui::Event::Paste("menu".into())]);
assert_eq!(a.session.doc.plain_text(wordcraft_doc::StoryRef::Body), "source menu", "the menu-bar paste pasted");
}
/// #5616: the browser paste event after a formatting paste is dropped before an open equation
/// can type it.
#[test]
fn the_ignored_paste_event_never_reaches_an_open_equation() {
let mut a = copied_bold_app();
a.canvas.paste_event_follows_chord = true;
a.run("insert.equation", json!({"linear": "abc"})).unwrap();
a.canvas.ignore_next_paste = true;
let ctx = egui::Context::default();
let before = a.session.math.clone();
mods_frame(&ctx, &mut a, Modifiers::COMMAND, vec![egui::Event::Paste("zzz".into())]);
assert_eq!(a.session.math, before, "the ignored paste typed nothing into the equation");
assert!(!a.canvas.ignore_next_paste);
}
/// #5616: only Mod+Shift+V leaves a browser paste event; Paste Formatting on another key neither
/// arms the ignore flag nor waits for a paste.
#[test]
fn paste_formatting_on_another_key_leaves_no_paste_to_ignore() {
for formatting in [true, false] {
let mut a = if formatting {
copied_bold_app()
} else {
WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default())
};
a.canvas.paste_event_follows_chord = true;
a.session.keymap = wordcraft_engine::keymap::KeyMap::from_value(&json!({"assigned": {"Mod+Alt+P": "edit.pasteFormat"}}));
let m = Modifiers::COMMAND | Modifiers::ALT;
super::shortcuts::dispatch(&mut a, Key::P, m);
assert!(!a.canvas.ignore_next_paste, "formatting={formatting}");
}
}
/// A press or release of `key` with `modifiers`.
fn key_event(key: Key, pressed: bool, modifiers: Modifiers) -> egui::Event {
egui::Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers }
@@ -1336,6 +1577,24 @@ fn typing_with_smart_art_selected_types_into_an_item() {
assert_eq!(g.items[0].text, "Ada", "one undo step for the typing");
}
/// #5616: modifiers recorded for an unrelated key (Mod+Shift+C) don't steer a later keyless paste,
/// whether Mod was released or is still held with no change event.
#[test]
fn an_unrelated_keys_modifiers_do_not_steer_a_later_paste() {
for mod_still_held in [false, true] {
let services = crate::Services { clipboard_html: Some(Box::new(|| Some("<p><b>external</b></p>".into()))), ..Default::default() };
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), services);
let ctx = egui::Context::default();
let chord = Modifiers::COMMAND | Modifiers::SHIFT;
mods_frame(&ctx, &mut a, chord, vec![key_event(Key::C, true, chord)]);
// Shift released, Mod still held: Mod+C's chord isn't the paste's modifiers.
let after = if mod_still_held { Modifiers::COMMAND } else { Modifiers::NONE };
mods_frame(&ctx, &mut a, after, vec![egui::Event::Paste("external".into())]);
let bold = a.session.run("format.state", &json!({})).unwrap().get("bold").and_then(serde_json::Value::as_bool);
assert_eq!(bold, Some(true), "held={mod_still_held}: a plain paste keeps the HTML's bold");
}
}
#[test]
fn delete_previous_sentence_shortcut_dispatches_and_can_be_reassigned() {
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), crate::Services::default());
+8
View File
@@ -656,6 +656,9 @@ pub struct WordApp {
pub clipboard_published: bool,
pub printing: printing::State,
print_feedback_seen: Option<printing::Feedback>,
/// Which job message is current: bumped when a job starts and whenever the message changes,
/// so a window can tell a new result from one it already said even when the text is the same.
print_gen: u64,
pub canvas: canvas::CanvasState,
/// Content control frames, check boxes and lists on the page.
pub controls: content_controls::ControlUi,
@@ -783,8 +786,13 @@ pub struct WordApp {
/// The document's fonts that aren't installed, for the status bar and the font box, and the
/// layout they were read from.
pub missing_fonts: crate::chrome::MissingFontsMemo,
/// This window's refused or failed export, shown on its Export and Print pages; see [`WordApp::fail_export`].
pub export_error: String,
/// The document's [`StatusCounts`] and the key they were computed for; see [`WordApp::cached_status_counts`].
pub status_counts: (u64, StatusCounts),
/// What this window's Print page knows of the last job's message (the viewport and pass it was
/// last drawn in, and the generations of the result it said and holds back); per window.
print_memo: crate::print_page::Memo,
last_autosave: f64,
/// The tab shown before the Equation tab came up (restored when editing ends).
pub(crate) equation_prev_tab: Option<String>,
+16 -4
View File
@@ -407,7 +407,15 @@ pub fn pointer(app: &mut WordApp, ui: &Ui, resp: &egui::Response, pages: &[Rect]
let _ = app.run("select.addObject", json!({"pos": object.pos()}));
return true;
}
if pressed && grab == Grab::Move && object.behind() && behind_draggable(app, &object) {
// While editing a header/footer, a click on its Behind Text picture where no header/footer
// text covers it (the plain hit test picked it: down over the body, or clear of the text in
// the band) selects it, as in Word; only over text does the click defer to that text.
// ponytail: headers/footers only; body Behind Text pictures clear of text could do the same.
let clear_of_text = matches!(object.story, StoryRef::Part(_))
&& crate::canvas::page_at(pages, layout, scale, at)
.and_then(|(page, x, y)| layout.object_at_in(page, x, y, EDGE / scale.max(0.01), object.story))
.is_some_and(|o| o.pos() == object.pos());
if pressed && grab == Grab::Move && object.behind() && !clear_of_text && behind_draggable(app, &object) {
let (min, picture) = match app.session.doc.para_at(&object.pos()).and_then(|p| p.object_at(object.pos().off)) {
Some(o) => (wordcraft_engine::cmd::objects::min_size(o), matches!(o, InlineObject::Image { .. })),
None => return false,
@@ -431,6 +439,8 @@ pub fn pointer(app: &mut WordApp, ui: &Ui, resp: &egui::Response, pages: &[Rect]
let pos = object.pos();
let end = Pos { off: pos.off + OBJ.len_utf8(), ..pos.clone() };
let _ = app.run("select.range", json!({"anchor": pos, "focus": end}));
// A header/footer picture repeats on every page: select the copy clicked, as `select_at` does.
app.session.page_hint = object.page;
let (min, picture) = match selected(app) {
Some((_, o)) => (wordcraft_engine::cmd::objects::min_size(o), matches!(o, InlineObject::Image { .. })),
None => return true,
@@ -601,9 +611,8 @@ fn link_click(app: &mut WordApp, layout: &DocLayout, pages: &[Rect], scale: f32,
/// Right-click at `at`: the picture, shape or text box under it becomes the selection (as a click
/// would, without a drag), so the context menu acts on it. Returns whether there was one.
pub fn select_at(app: &mut WordApp, layout: &DocLayout, pages: &[Rect], scale: f32, at: Pos2) -> bool {
if crate::canvas::editing_header_footer(app, layout) {
return false;
}
// While editing a header/footer, `grab_at` looks at its own objects, so its picture is picked
// too and the menu's Reset Picture or Wrap Text acts on it.
let Some((object, _)) = grab_at(app, layout, pages, scale, at) else { return false };
let pos = object.pos();
// Already selected (alone or among several picked for Group): keep the selection.
@@ -611,6 +620,9 @@ pub fn select_at(app: &mut WordApp, layout: &DocLayout, pages: &[Rect], scale: f
let end = Pos { off: pos.off + OBJ.len_utf8(), ..pos.clone() };
let _ = app.run("select.range", json!({"anchor": pos, "focus": end}));
}
// A header/footer picture repeats on every page: its frame belongs on the page clicked, not
// the one last edited.
app.session.page_hint = object.page;
true
}
+95 -16
View File
@@ -170,6 +170,18 @@ fn return_prints(ctx: &egui::Context) -> bool {
})
}
/// Per window: what the Print page needs to know about the last job's message.
#[derive(Default)]
pub struct Memo {
/// The viewport and pass the page was last drawn in: a gap means it was just opened.
pass: Option<(egui::ViewportId, u64)>,
/// The generation (`WordApp::print_gen`) of the job result this window has already said, in
/// its status bar or on this page: a result of the same text from a later job is another one.
pub(crate) said: Option<u64>,
/// The generation of the result held back on this opening of the page.
hidden: Option<u64>,
}
/// The Print page: settings on the left, the preview on the right.
pub fn show(app: &mut WordApp, ui: &mut Ui) {
let t = Tokens::get(ui.ctx());
@@ -178,6 +190,30 @@ pub fn show(app: &mut WordApp, ui: &mut Ui) {
let total = lay.pages.len();
let current = app.session.current_pages(&lay);
app.ui.print.preview = app.ui.print.preview.min(total.saturating_sub(1));
// Opened afresh, the page doesn't repeat how the last job went when this window already said
// it (its status bar, or this page): `printing.message` itself stays, as `ui.printSettings`
// and other windows still report it. What the printers are doing (finding them, none found)
// always shows. Passes are counted per viewport, so the marker is per window.
let here = (ctx.viewport_id(), ctx.cumulative_pass_nr());
let opened = app.print_memo.pass.is_none_or(|(viewport, last)| viewport != here.0 || last.saturating_add(1) < here.1);
app.print_memo.pass = Some(here);
let result = |m: &Option<crate::printing::Feedback>| {
matches!(m, Some(crate::printing::Feedback::Submitted(_) | crate::printing::Feedback::Failed(_) | crate::printing::Feedback::WorkerStopped))
};
let message = app.printing.message.clone();
let generation = app.print_gen;
if opened {
app.print_memo.hidden = (result(&message) && app.print_memo.said == Some(generation)).then_some(generation);
}
// A later message (a job started again, then failed the same way) is shown afresh.
if app.print_memo.hidden != Some(generation) {
app.print_memo.hidden = None;
}
let hide_message = app.print_memo.hidden.is_some();
if !hide_message {
// Shown here, so the next opening needn't repeat it.
app.print_memo.said = result(&message).then_some(generation);
}
let settings = |app: &mut WordApp, ui: &mut Ui| {
{
@@ -206,7 +242,7 @@ pub fn show(app: &mut WordApp, ui: &mut Ui) {
}
if native {
if let Some(discover) = &app.services.printers {
crate::printing::show(&mut app.printing, ui, discover, |label| crate::i18n::t(label).to_owned());
crate::printing::show(&mut app.printing, ui, discover, hide_message, |label| crate::i18n::t(label).to_owned());
}
// A job can wait long on a sleeping printer's driver; Cancel frees the page.
if app.printing.busy() && app.services.cancel_print.is_some() && ui.button(tl!("Cancel printing")).clicked() {
@@ -454,28 +490,71 @@ fn preview(app: &mut WordApp, ui: &mut Ui, lay: &DocLayout) {
/// The export "format" of a Word 2003 XML Document: an `.xml` file saved with `format: "wordml2003"`.
pub(crate) const EXPORT_WORD_2003: &str = "wordml2003";
/// The "save a copy" formats as (label, format), also the built-in browser's types when exporting.
pub(crate) const EXPORT_FORMATS: &[(&str, &str)] = &[
("PDF document (*.pdf)", "pdf"),
("Word document (*.docx)", "docx"),
("Word XML Document (*.xml)", "xml"),
("Word 2003 XML Document (*.xml)", EXPORT_WORD_2003),
("OpenDocument Text (*.odt)", "odt"),
("OpenDocument Text Template (*.ott)", "ott"),
("Flat OpenDocument Text (*.fodt)", "fodt"),
("Rich Text Format (*.rtf)", "rtf"),
("Web page (*.html)", "html"),
("Markdown (*.md)", "md"),
("LaTeX (*.tex)", "tex"),
("Plain text (*.txt)", "txt"),
("Page image (*.png)", "png"),
];
/// The file extension an export format writes.
pub(crate) fn export_file_ext(format: &str) -> &str {
if format == EXPORT_WORD_2003 { "xml" } else { format }
}
/// Is `ext` an extension of a document or export type (the Export types, plus the older `.doc`
/// and `.htm`)? Such an extension on a typed name gives way to the chosen type's; any other
/// (`notes.v2`) is part of the name.
pub(crate) fn is_document_ext(ext: &str) -> bool {
["doc", "htm"].iter().any(|e| e.eq_ignore_ascii_case(ext)) || EXPORT_FORMATS.iter().any(|&(_, f)| export_file_ext(f).eq_ignore_ascii_case(ext))
}
/// The name an export to `format` is saved under: the chosen type's extension replaces a known
/// document extension (`notes.docx` as plain text is `notes.txt`) and is added to any other name.
pub(crate) fn export_name(name: &str, format: &str) -> String {
let want = export_file_ext(format);
let path = std::path::Path::new(name);
// A dotfile name (`.docx`) has no extension for `Path::extension`, which the engine's save also
// reads, so it is a stem and gets one (`.docx.xml`); a bare extension would be refused.
match path.extension().and_then(|e| e.to_str()) {
Some(e) if e.eq_ignore_ascii_case(want) => name.to_string(),
Some(e) if is_document_ext(e) => path.with_extension(want).to_string_lossy().into_owned(),
// `a.` has an empty extension: its dot is dropped before the type's is added.
_ => format!("{}.{want}", name.trim_end_matches('.')),
}
}
/// The "save a copy" formats (File › Export, and below the settings on the Print page).
pub fn export_formats(app: &mut WordApp, ui: &mut Ui) {
for (label, ext) in [
("PDF document (*.pdf)", "pdf"),
("Word document (*.docx)", "docx"),
("Word XML Document (*.xml)", "xml"),
("Word 2003 XML Document (*.xml)", EXPORT_WORD_2003),
("OpenDocument Text (*.odt)", "odt"),
("OpenDocument Text Template (*.ott)", "ott"),
("Flat OpenDocument Text (*.fodt)", "fodt"),
("Rich Text Format (*.rtf)", "rtf"),
("Web page (*.html)", "html"),
("Markdown (*.md)", "md"),
("LaTeX (*.tex)", "tex"),
("Plain text (*.txt)", "txt"),
("Page image (*.png)", "png"),
] {
// A refused or failed export, said here because Backstage hides the status bar (Export and Print pages both draw this).
if !app.export_error.is_empty() {
ui.label(egui::RichText::new(&app.export_error).color(ui.visuals().error_fg_color));
ui.add_space(6.0);
}
for &(label, ext) in EXPORT_FORMATS {
if ui.add(egui::Button::new(egui::RichText::new(tl!(label)).font(medium(13.5))).min_size(vec2(320.0, 34.0))).clicked() {
app.export_dialog(ext);
}
ui.add_space(4.0);
}
// Linux and the BSDs (#3535): WordCraft's own browser when the system dialog doesn't appear.
#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))]
{
ui.add_space(8.0);
if ui.add(egui::Button::new(egui::RichText::new(tl!("Browse in WordCraft…")).font(medium(13.5))).min_size(vec2(320.0, 34.0))).clicked() {
let _ = app.run("ui.fileBrowser", json!({"purpose": "export"}));
}
}
}
#[cfg(test)]
+4 -3
View File
@@ -23,8 +23,8 @@ pub fn commands(app: &crate::WordApp) -> Vec<serde_json::Value> {
}
/// Builds translated print labels, draws the shared print-settings panel, and shows the current
/// feedback message.
pub fn show(state: &mut State, ui: &mut egui::Ui, discover: &Discover, translate: impl Fn(&str) -> String) {
/// feedback message (unless `hide_message`: this window has already said it).
pub fn show(state: &mut State, ui: &mut egui::Ui, discover: &Discover, hide_message: bool, translate: impl Fn(&str) -> String) {
let labels = Labels {
printer: &translate("Printer"),
select_printer: &translate("Select a printer"),
@@ -38,7 +38,7 @@ pub fn show(state: &mut State, ui: &mut egui::Ui, discover: &Discover, translate
grayscale: &translate("Grayscale"),
};
state.show(ui, egui::Id::unique("wordcraft_print_settings"), discover, &labels);
if let Some(message) = &state.message {
if let Some(message) = state.message.as_ref().filter(|_| !hide_message) {
ui.label(feedback(message, translate));
}
}
@@ -243,6 +243,7 @@ pub fn submit(app: &mut crate::WordApp, params: &serde_json::Value) -> Result<se
}
app.printing.begin(submit(bytes, settings, collate, print_options)).map_err(|_| "A print job is already being submitted.".to_owned())?;
app.print_feedback_seen = None;
app.print_gen = app.print_gen.wrapping_add(1);
} else if let Some(print) = &app.services.print {
print(&bytes)?;
}
+181 -3
View File
@@ -3767,6 +3767,148 @@ fn the_print_button_shows_only_with_a_print_hook() {
}
}
/// A Print page with printers found (so it draws the job message), in English.
fn print_page_harness(message: Option<crate::printing::Feedback>) -> egui_kittest::Harness<'static, WordApp> {
let mut a = app();
a.ui.language = "en".into();
a.services.printers = Some(Box::new(|| {
let (sender, receiver) = std::sync::mpsc::channel();
let _ = sender.send(vec![printing::Printer { name: "Test queue".into(), label: String::new(), default: true }]);
receiver
}));
a.services.print_native = Some(Box::new(|_, _, _, _| std::sync::mpsc::channel().1));
let mut h = egui_kittest::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,
);
// The page's first drawing starts discovery, which replaces the message: draw it once, leave,
// and let the printers arrive.
let _ = h.state_mut().run("file.print", json!({}));
h.run_steps(4);
let _ = h.state_mut().run("ui.backstage", json!({"value": false}));
h.run_steps(3);
set_print_message(&mut h, message);
h.state_mut().print_memo = Default::default();
h
}
/// A job message that arrives without the app's own `print_feedback` acting on it (a submitted job
/// would close the Print page); what the window has said is set by the test.
fn set_print_message(h: &mut egui_kittest::Harness<'_, WordApp>, message: Option<crate::printing::Feedback>) {
h.state_mut().printing.message = message.clone();
h.state_mut().print_feedback_seen = message;
h.state_mut().print_gen += 1;
}
fn leave_and_reopen_print(h: &mut egui_kittest::Harness<'_, WordApp>) {
let _ = h.state_mut().run("ui.backstage", json!({"value": false}));
h.run_steps(2);
let _ = h.state_mut().run("file.print", json!({}));
h.run_steps(3);
}
/// Opened again, the Print page doesn't repeat how the last job went when the window already said
/// it (in its status bar), but a failure that comes in while it is open stays, and what the
/// printers are doing (none found) shows each time. The shared message is never cleared, so
/// `ui.printSettings` still reports it.
#[test]
fn the_print_page_opens_without_the_last_jobs_message() {
use crate::printing::Feedback;
use egui_kittest::kittest::Queryable;
let mut h = print_page_harness(Some(Feedback::Submitted("job 7".into())));
// A job went away earlier: its message was said in this window's status bar, and the page closed.
h.state_mut().print_memo.said = Some(h.state().print_gen);
let _ = h.state_mut().run("file.print", json!({}));
h.run_steps(4);
assert!(h.query_by_label_contains("job 7").is_none(), "the last job's message isn't repeated");
assert_eq!(h.state().printing.message, Some(Feedback::Submitted("job 7".into())), "but the shared message stays");
// A failure arrives while the page is open, said (by the status bar) in the very frame, so
// only the page being open keeps it showing: wrong reopen detection would hide it.
let failure = Some(Feedback::Failed("no paper".into()));
set_print_message(&mut h, failure.clone());
h.state_mut().print_memo.said = Some(h.state().print_gen);
h.run_steps(3);
assert!(h.query_by_label_contains("no paper").is_some(), "a failure on the open page stays");
leave_and_reopen_print(&mut h);
assert!(h.query_by_label_contains("no paper").is_none(), "reopened, the failure isn't repeated");
assert_eq!(h.state().printing.message, failure, "but it is still the shared message");
set_print_message(&mut h, Some(Feedback::NoPrinters));
leave_and_reopen_print(&mut h);
assert!(h.query_by_label_contains("No printers found").is_some(), "no printers still shows");
}
/// A retry that fails again with the very same text is a new result: it shows, though the window
/// said the same words for the job before.
#[test]
fn a_retry_that_fails_the_same_way_shows_again() {
use crate::printing::Feedback;
use egui_kittest::kittest::Queryable;
let mut h = print_page_harness(None);
// Every job is refused at once, with the same words.
h.state_mut().services.print_native = Some(Box::new(|_, _, _, _| {
let (sender, receiver) = std::sync::mpsc::channel();
let _ = sender.send(Err("no paper".to_owned()));
receiver
}));
let _ = h.state_mut().run("file.print", json!({}));
h.run_steps(3);
h.state_mut().run("ui.print", json!({})).unwrap();
h.run_steps(3);
assert_eq!(h.state().printing.message, Some(Feedback::Failed("no paper".into())));
assert!(h.query_by_label_contains("no paper").is_some(), "the first failure shows");
leave_and_reopen_print(&mut h);
assert!(h.query_by_label_contains("no paper").is_none(), "reopened, it isn't repeated");
h.state_mut().run("ui.print", json!({})).unwrap();
h.run_steps(3);
assert_eq!(h.state().printing.message, Some(Feedback::Failed("no paper".into())));
assert!(h.query_by_label_contains("no paper").is_some(), "the same failure of a new job shows");
}
/// A result nobody has said yet isn't dropped: a failure that arrived while File showed another
/// page (so no status bar was drawn) shows when Print opens.
#[test]
fn the_print_page_shows_a_result_that_was_never_said() {
use crate::printing::Feedback;
use egui_kittest::kittest::Queryable;
let mut h = print_page_harness(None);
h.state_mut().ui.backstage = true;
h.state_mut().ui.backstage_page = "home".into();
h.run_steps(2);
// Through the app's own `print_feedback` (run each frame), which says it in a status bar that isn't drawn.
h.state_mut().printing.message = Some(Feedback::Failed("no paper".into()));
h.run_steps(3);
assert_eq!(h.state().print_memo.said, None, "File's home page doesn't say it");
let _ = h.state_mut().run("file.print", json!({}));
h.run_steps(4);
assert!(h.query_by_label_contains("no paper").is_some());
}
/// Per window: what one window has said of the last job isn't another window's, and the shared
/// message is the same in both. (The harness draws one viewport, which re-enters a window of its
/// own, so the per-window state is checked where windows swap; `the_print_page_opens_without_the_last_jobs_message`
/// and `the_print_page_shows_a_result_that_was_never_said` show what each state does on the page.)
#[test]
fn the_print_pages_of_two_windows_decide_separately() {
use crate::printing::Feedback;
let failure = Some(Feedback::Failed("no paper".into()));
let mut a = app();
a.printing.message = failure.clone();
let first = a.windows.shown();
a.print_gen = 1;
a.print_memo.said = Some(a.print_gen);
a.new_window();
assert_ne!(first, a.windows.shown());
assert_eq!(a.print_memo.said, None, "the second window never said it, so its page shows it");
assert_eq!(a.printing.message, failure, "the message is shared, and still there");
assert!(a.enter_window(first));
assert_eq!(a.print_memo.said, Some(1), "the first window said it, so its page doesn't repeat it");
assert_eq!(a.printing.message, failure);
}
/// Return on the Print page prints, as in Word, where ⌘P opens on Print as the default
/// button; the document isn't typed into.
#[test]
@@ -4430,7 +4572,8 @@ fn ctrl_shift_c_and_v_copy_and_paste_formatting_not_text() {
let key = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers };
h.event(key(egui::Key::C, modifiers));
h.step();
assert!(h.state().session.painter.is_some(), "{modifiers:?}: Copy Formatting picked up the selection's formatting");
assert!(h.state().session.copied_format.is_some(), "{modifiers:?}: Copy Formatting picked up the selection's formatting");
assert!(h.state().session.painter.is_none(), "{modifiers:?}: Copy Formatting doesn't arm the Format Painter brush");
assert_eq!(h.state().session.clip_history.len(), clipboard_entries, "{modifiers:?}: Copy Formatting preserved clipboard history");
assert_eq!(h.state().session.clipboard_text, "plain", "{modifiers:?}: the existing clipboard text was preserved");
assert!(copied(&h).is_empty(), "{modifiers:?}: no text reached the system clipboard: {:?}", copied(&h));
@@ -4441,14 +4584,49 @@ fn ctrl_shift_c_and_v_copy_and_paste_formatting_not_text() {
h.event(key(egui::Key::V, modifiers));
h.step();
assert_eq!(bold(&mut h), Some(true), "{modifiers:?}: Paste Formatting made the target bold");
assert!(h.state().session.painter.is_none(), "{modifiers:?}: the non-sticky painter is used up");
assert_eq!(body_text(h.state()), "Bold plain", "{modifiers:?}: pasting formatting left the document text alone");
assert!(h.state().session.copied_format.is_some(), "{modifiers:?}: copied formatting stays for the next Paste Formatting");
// Pasted again, as in Word: formatting again, never the clipboard's text (#5616).
h.state_mut().run("caret.docEnd", json!({})).unwrap();
h.state_mut().run("text.insert", json!({"text": " more"})).unwrap();
h.state_mut().run("select.text", json!({"text": "more"})).unwrap();
// It types on in the pasted bold: make it plain first.
h.state_mut().run("format.bold", json!({})).unwrap();
assert_eq!(bold(&mut h), Some(false));
h.event(key(egui::Key::V, modifiers));
h.step();
assert_eq!(bold(&mut h), Some(true), "{modifiers:?}: a second Paste Formatting made the next target bold");
assert_eq!(body_text(h.state()), "Bold plain more", "{modifiers:?}: the second paste left the text alone");
assert_eq!(h.state().session.clip_history.len(), clipboard_entries, "{modifiers:?}: Paste Formatting preserved clipboard history");
assert_eq!(h.state().session.clipboard_text, "plain", "{modifiers:?}: Paste Formatting preserved the clipboard text");
assert!(copied(&h).is_empty(), "{modifiers:?}: pasting formatting put no text on the system clipboard: {:?}", copied(&h));
}
}
/// #1537/#4943: with no formatting picked up, Ctrl/Cmd+Shift+V pastes the clipboard as text
/// only (Word for Windows): the text arrives in the destination's formatting, not the source's.
#[test]
fn ctrl_shift_v_without_copied_formatting_pastes_text_only() {
let mut a = app();
a.run("text.insert", json!({"text": "Bold plain"})).unwrap();
a.run("select.text", json!({"text": "Bold"})).unwrap();
a.run("format.bold", json!({})).unwrap();
a.run("edit.copy", json!({})).unwrap();
a.run("select.text", json!({"text": "plain"})).unwrap();
// The destination has formatting of its own, so a paste that dropped it would show.
a.run("format.italic", json!({})).unwrap();
assert!(a.session.painter.is_none());
let mut h = harness(a);
h.run_steps(6);
let modifiers = egui::Modifiers::COMMAND | egui::Modifiers::SHIFT;
h.event(egui::Event::Key { key: egui::Key::V, physical_key: None, pressed: true, repeat: false, modifiers });
h.step();
assert_eq!(body_text(h.state()), "Bold Bold", "the clipboard text replaced the selection");
let bold = h.state_mut().run("format.state", json!({})).unwrap().get("bold").and_then(Value::as_bool);
assert_ne!(bold, Some(true), "the pasted text took the destination's formatting, not the copied bold");
let italic = h.state_mut().run("format.state", json!({})).unwrap().get("italic").and_then(Value::as_bool);
assert_eq!(italic, Some(true), "the pasted text kept the destination's italic");
}
/// #1669: with Shift held, Backspace still erases (#707) and Delete cuts the selection, doing
/// nothing without one, as in Word for Windows. (Windows sends Shift+Delete as a Cut; macOS and
/// Linux send the key, which reached no command.)
+1
View File
@@ -27,6 +27,7 @@ pub(crate) use combo::{current_pick, note_hover, set_current_pick, swatch, take_
pub use groups::{command_icon, command_menu, customize_menu_items, group, group_titled, row};
pub use icon_buttons::{
dialog_tabs, icon_button, icon_menu_item, icon_only_button, icon_text_button, icon_text_button_width, icon_text_menu_button, primary_button,
section,
};
#[cfg(test)]
use tooltip::show_hint;
+12 -20
View File
@@ -257,7 +257,7 @@ const ARROW_BORDER: f32 = 1.0;
/// A searching combo's state between frames.
#[derive(Clone, Default)]
struct ComboSearch {
/// The match list is showing (the user typed since focusing the field).
/// The match list is showing (opened via the arrow button or typing in the field).
open: bool,
/// Whether the user has typed or modified the search query.
typed: bool,
@@ -332,16 +332,16 @@ fn consume_arrow_steps(ui: &mut Ui, open: bool, has_focus: bool) -> i32 {
/// - `text`: the current text string in the edit field.
/// - `reveal`: set to `true` when opening or changing search query to scroll the list/highlight into view.
///
/// Clicking the text box (`resp.clicked()`) when the dropdown is closed sets `s.open = true`,
/// `s.typed = false`, `s.moved = false`, `*reveal = true`, and selects all text with [`select_all_text`].
/// Clicking while already open preserves caret positioning for partial edits without re-selecting all text.
/// Gaining focus alone (`resp.gained_focus()` when `!was_open`, such as on Tab navigation) selects all text
/// for typing without opening the 420px dropdown popup, while regaining focus when already open (e.g. after
/// interacting with the popup scrollbar) preserves query text and caret placement without re-selecting all.
/// Clicking the dropdown arrow (`aresp.clicked()`) toggles `s.open`; when opening, it requests focus on `te_id`,
/// resets `typed` and `moved`, sets `*reveal = true`, and selects all text.
/// Clicking the dropdown arrow (`aresp.clicked()`) toggles `s.open`; when opening, it requests focus
/// on `te_id`, resets `typed` and `moved`, sets `*reveal = true`, and selects all text with
/// [`select_all_text`].
/// Changing the text (`resp.changed()`) opens the dropdown with `s.typed = true`, clears `s.highlight`,
/// clears `s.moved`, and sets `*reveal = true`.
/// Gaining focus while closed (`resp.gained_focus() && !was_open`, from an initial click in the field
/// or Tab navigation) selects all text for immediate replacement typing without opening the 420px
/// dropdown popup; subsequent clicks inside the already-focused field and regaining focus while already
/// open (e.g. after interacting with the popup scrollbar) preserve caret placement and query text without
/// re-selecting all.
fn handle_search_interactions(
ui: &mut Ui,
s: &mut ComboSearch,
@@ -352,17 +352,7 @@ fn handle_search_interactions(
reveal: &mut bool,
) {
let was_open = s.open;
if resp.clicked() {
if !was_open {
s.open = true;
s.typed = false;
s.moved = false;
*reveal = true;
select_all_text(ui.ctx(), te_id, text);
}
} else if resp.gained_focus() && !was_open {
select_all_text(ui.ctx(), te_id, text);
} else if aresp.clicked() {
if aresp.clicked() {
if was_open {
s.open = false;
} else {
@@ -379,6 +369,8 @@ fn handle_search_interactions(
s.highlight = None;
s.moved = false;
*reveal = true;
} else if resp.gained_focus() && !was_open {
select_all_text(ui.ctx(), te_id, text);
}
}
@@ -108,6 +108,41 @@ pub fn icon_menu_item(ui: &mut Ui, icon: &str, text: &str, shortcut: &str, min_w
resp
}
/// A dialog section: space above, then a soft rounded panel. The panel
/// holds the heading and, indented under it, the settings. An empty title
/// gives a panel with no heading. A section inside another keeps the fill
/// of its parent and shows only the border.
pub fn section<R>(ui: &mut Ui, title: &str, add: impl FnOnce(&mut Ui) -> R) -> R {
let t = Tokens::get(ui.ctx());
let key = egui::Id::unique("dialog_section_fill");
let parent: Option<Color32> = ui.data(|d| d.get_temp(key));
let fill = parent.unwrap_or_else(|| ui.visuals().window_fill.lerp_to_gamma(t.text, 0.04));
ui.data_mut(|d| d.insert_temp(key, fill));
ui.add_space((f32::from(ui.spacing().window_margin.left) - ui.spacing().item_spacing.y).max(0.0));
let out = egui::Frame::new()
.fill(fill)
.stroke(Stroke::new(1.0, t.border.gamma_multiply(0.6)))
.corner_radius(CornerRadius::same(6))
.inner_margin(egui::Margin::symmetric(10, 8))
.show(ui, |ui| {
ui.set_width(ui.available_width());
if title.is_empty() {
return add(ui);
}
ui.label(egui::RichText::new(title).font(crate::theme::semibold(12.5)));
ui.add_space(2.0);
egui::Frame::new().inner_margin(egui::Margin { left: 12, ..egui::Margin::ZERO }).show(ui, add).inner
})
.inner;
ui.data_mut(|d| match parent {
Some(p) => {
d.insert_temp(key, p);
}
None => d.remove::<Color32>(key),
});
out
}
/// A strip of dialog tabs. The active tab joins the page below it.
/// Returns the index of the tab the user clicked.
pub fn dialog_tabs(ui: &mut Ui, labels: &[String], selected: usize) -> Option<usize> {
+85 -57
View File
@@ -428,106 +428,134 @@ fn clearing_a_font_query_keeps_the_recent_heading_visible() {
}
}
/// #5914: clicking on the font name or dropdown arrow opens the dropdown list with the other fonts
/// (Recently Used Fonts and All Fonts), focuses the field, and selects all text so typing immediately
/// replaces the font name to search for a font, like in Microsoft Word. Also verifies that focus alone
/// (such as on Tab navigation) does not open the 420px dropdown, subsequent clicks preserve cursor placement,
/// and clicking the arrow button toggles the dropdown open and closed.
#[test]
fn clicking_the_font_name_or_box_shows_other_fonts_and_selects_all_to_type() {
use egui::accesskit::Role;
use egui_kittest::kittest::{By, Queryable};
use std::cell::RefCell;
use std::rc::Rc;
let fonts: Vec<String> = ["Arial", "Courier New", "Georgia", "Times New Roman"].map(String::from).to_vec();
let recent: Vec<String> = ["Courier New"].map(String::from).to_vec();
let picked = Rc::new(RefCell::new(None));
let current = Rc::new(RefCell::new("Arial".to_string()));
fn font_combo_harness(
id: &'static str,
initial: &str,
fonts: Vec<String>,
recent: Vec<String>,
) -> (egui_kittest::Harness<'static>, std::rc::Rc<std::cell::RefCell<Option<String>>>) {
let picked = std::rc::Rc::new(std::cell::RefCell::new(None));
let current = std::rc::Rc::new(std::cell::RefCell::new(initial.to_string()));
let picked_c = picked.clone();
let current_c = current.clone();
let mut h = egui_kittest::Harness::builder().with_size(vec2(400.0, 600.0)).build_ui(move |ui| {
let cur = current_c.borrow().clone();
let v = font_combo_with_recent(ui, "font_test", 150.0, &cur, &fonts, &recent, None);
if let Some(f) = v {
*current_c.borrow_mut() = f.clone();
let cur = current.borrow().clone();
if let Some(f) = font_combo_with_recent(ui, id, 150.0, &cur, &fonts, &recent, None) {
*current.borrow_mut() = f.clone();
*picked_c.borrow_mut() = Some(f);
}
});
h.run_steps(2);
// Before click: dropdown is closed, font name "Arial" is displayed
(h, picked)
}
fn click_at_separated(h: &mut egui_kittest::Harness<'_>, pos: egui::Pos2) {
h.event(egui::Event::PointerMoved(pos));
h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() });
h.step();
h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() });
h.run_steps(2);
}
/// #6722: clicking on the font text field focuses it and selects all text for immediate
/// replacement typing without opening the 420px dropdown popup; subsequent clicks inside the
/// already-focused field place the caret without re-selecting all; only typing opens the filtered list.
#[test]
fn clicking_the_font_field_selects_all_without_opening_dropdown() {
use egui::accesskit::Role;
use egui_kittest::kittest::{By, Queryable};
let fonts: Vec<String> = ["Arial", "Courier New", "Georgia", "Times New Roman"].map(String::from).to_vec();
let recent: Vec<String> = ["Courier New"].map(String::from).to_vec();
let (mut h, picked) = font_combo_harness("font_field_test", "Arial", fonts, recent);
assert_eq!(h.get(By::new().role(Role::TextInput)).value().as_deref(), Some("Arial"));
assert!(h.query_by_label("All Fonts").is_none());
// Focus without click (e.g. keyboard navigation via Tab) selects text but does not open popup
// Focus without click (e.g. Tab navigation) selects text without opening the dropdown.
h.get(By::new().role(Role::TextInput)).focus();
h.run_steps(2);
assert!(h.get(By::new().role(Role::TextInput)).is_focused(), "field takes focus on Tab/focus");
assert!(h.query_by_label("All Fonts").is_none(), "focusing without click does not open the 420px dropdown");
// Typing while focused without click replaces the selected text (verifying selection on focus alone)
h.event(egui::Event::Text("g".into()));
h.run_steps(2);
assert_eq!(h.get(By::new().role(Role::TextInput)).value().as_deref(), Some("g"), "typing replaces font name selected on focus alone");
assert!(h.query_by_label("Georgia").is_some(), "typing while focused opens list and filters to matches");
// Cancel out with Escape to restore the initial state
h.key_press(egui::Key::Escape);
h.run_steps(2);
assert_eq!(h.get(By::new().role(Role::TextInput)).value().as_deref(), Some("Arial"));
assert!(h.query_by_label("All Fonts").is_none(), "dropdown closes on Escape");
// Click on the font name field
// Click on the unfocused field: focuses and selects all text without opening the dropdown.
h.get(By::new().role(Role::TextInput)).click();
h.run_steps(2);
assert!(h.get(By::new().role(Role::TextInput)).is_focused(), "clicking field focuses it");
assert!(h.query_by_label("Recently Used Fonts").is_none(), "clicking field does not open recently used fonts");
assert!(h.query_by_label("All Fonts").is_none(), "clicking field does not open the dropdown list");
// After click: other fonts show up (Recently Used Fonts and All Fonts)
assert!(h.query_by_label("Recently Used Fonts").is_some(), "recently used fonts should show up on click");
assert!(h.query_by_label("All Fonts").is_some(), "all fonts should show up on click");
// "Courier New" is present in both Recently Used and All Fonts sections
assert_eq!(h.query_all_by_label("Courier New").count(), 2, "the other fonts should show up on click");
assert!(h.query_by_label("Times New Roman").is_some(), "the other fonts should show up on click");
// Typing a letter replaces the selected text and filters the list
h.event(egui::Event::Text("t".into()));
h.run_steps(2);
assert_eq!(h.get(By::new().role(Role::TextInput)).value().as_deref(), Some("t"));
assert!(h.query_by_label("Times New Roman").is_some(), "matching font shows up");
assert!(h.query_by_label("Times New Roman").is_some(), "matching font shows up on typing");
assert_eq!(h.query_all_by_label("Courier New").count(), 0, "non-matching font is filtered out");
// Press Enter to apply the matching font
h.key_press(egui::Key::Enter);
h.run_steps(2);
assert_eq!(picked.borrow().as_deref(), Some("Times New Roman"));
assert!(h.query_by_label("All Fonts").is_none(), "dropdown closes after applying");
assert!(!h.get(By::new().role(Role::TextInput)).is_focused(), "field loses focus after Enter");
// Exercise arrow button: clicking the arrow button opens the dropdown, focuses the text edit,
// and selects all text so typing immediately replaces the font name.
let arrow_btn = h.get(By::new().role(Role::Button).label_contains("Font options"));
arrow_btn.click();
// First click selects all without opening; a second click inside the focused field places the
// caret for partial edits instead of re-selecting all. Separate press/release frames match real input.
let field_center = h.get(By::new().role(Role::TextInput)).rect().center();
click_at_separated(&mut h, field_center);
assert!(h.get(By::new().role(Role::TextInput)).is_focused());
assert!(h.query_by_label("All Fonts").is_none(), "first click does not open the dropdown");
click_at_separated(&mut h, field_center);
assert!(h.query_by_label("All Fonts").is_none(), "second click keeps the dropdown closed");
h.event(egui::Event::Text("!".into()));
h.run_steps(2);
assert_eq!(h.get(By::new().role(Role::TextInput)).value().as_deref(), Some("Times New !Roman"));
h.key_press(egui::Key::Backspace);
h.run_steps(2);
assert_eq!(h.get(By::new().role(Role::TextInput)).value().as_deref(), Some("Times New Roman"));
assert!(h.query_by_label("Times New Roman").is_some(), "editing the box opens the filtered dropdown");
}
assert!(h.query_by_label("All Fonts").is_some(), "dropdown opens on arrow click");
/// #6722: clicking the dropdown arrow opens Recently Used Fonts and All Fonts, focuses the field,
/// and selects all text; clicking inside the field while open preserves caret placement; clicking
/// the arrow again toggles the dropdown closed.
#[test]
fn clicking_the_font_arrow_toggles_dropdown_and_preserves_caret_on_field_click() {
use egui::accesskit::Role;
use egui_kittest::kittest::{By, Queryable};
let fonts: Vec<String> = ["Arial", "Courier New", "Georgia", "Times New Roman"].map(String::from).to_vec();
let recent: Vec<String> = ["Courier New"].map(String::from).to_vec();
let (mut h, _picked) = font_combo_harness("font_arrow_test", "Times New Roman", fonts, recent);
h.get(By::new().role(Role::Button).label_contains("Font options")).click();
h.run_steps(2);
assert!(h.query_by_label("Recently Used Fonts").is_some(), "recently used fonts show up on arrow click");
assert!(h.query_by_label("All Fonts").is_some(), "all fonts show up on arrow click");
assert_eq!(h.query_all_by_label("Courier New").count(), 2, "the other fonts show up on arrow click");
assert!(h.get(By::new().role(Role::TextInput)).is_focused(), "text edit has focus after arrow click");
// Clicking the text field while already open preserves caret placement rather than re-selecting all text
// Clicking the text field while already open preserves caret placement rather than re-selecting all text.
h.get(By::new().role(Role::TextInput)).click();
h.run_steps(2);
assert!(h.query_by_label("All Fonts").is_some(), "dropdown remains open on click inside field");
// Typing inserts at the clicked cursor position rather than replacing all text
h.event(egui::Event::Text("!".into()));
h.run_steps(2);
assert_eq!(h.get(By::new().role(Role::TextInput)).value().as_deref(), Some("Times New !Roman"));
assert!(egui::Popup::is_any_open(&h.ctx), "dropdown popup stays open even with no matches");
// Clicking the arrow button again toggles the dropdown closed
let arrow_btn = h.get(By::new().role(Role::Button).label_contains("Font options"));
arrow_btn.click();
h.get(By::new().role(Role::Button).label_contains("Font options")).click();
h.run_steps(2);
assert!(!egui::Popup::is_any_open(&h.ctx), "dropdown popup closes on arrow click toggle");
assert!(h.query_by_label("All Fonts").is_none(), "dropdown closes on arrow click toggle");
}
@@ -562,10 +590,10 @@ fn uninstalled_current_font_not_in_list_commits_box_text_on_enter_without_replac
h.run_steps(2);
assert_eq!(h.get(By::new().role(Role::TextInput)).value().as_deref(), Some("Calibri"));
// Click font name field to open dropdown
h.get(By::new().role(Role::TextInput)).click();
// Click dropdown arrow to open the list
h.get(By::new().role(Role::Button).label_contains("Font options")).click();
h.run_steps(2);
assert!(h.query_by_label("All Fonts").is_some(), "dropdown opens on click");
assert!(h.query_by_label("All Fonts").is_some(), "dropdown opens on arrow click");
// Press Enter without typing and without moving: commits box text "Calibri", not first recent font
h.key_press(egui::Key::Enter);
@@ -574,9 +602,9 @@ fn uninstalled_current_font_not_in_list_commits_box_text_on_enter_without_replac
assert_eq!(h.get(By::new().role(Role::TextInput)).value().as_deref(), Some("Calibri"));
assert!(h.query_by_label("All Fonts").is_none(), "dropdown closes after Enter");
// Re-open and move highlight with ArrowDown: now it picks the first font on Enter
// Re-open via arrow and move highlight with ArrowDown: now it picks the first font on Enter
*picked.borrow_mut() = None;
h.get(By::new().role(Role::TextInput)).click();
h.get(By::new().role(Role::Button).label_contains("Font options")).click();
h.run_steps(2);
assert!(h.query_by_label("All Fonts").is_some());
@@ -586,10 +614,10 @@ fn uninstalled_current_font_not_in_list_commits_box_text_on_enter_without_replac
h.run_steps(2);
assert_eq!(picked.borrow().as_deref(), Some("Courier New"), "ArrowDown moves highlight to first available font");
// Re-open, type partial query "co", lose and regain focus while pointer is over the popup:
// Re-open via arrow, type partial query "co", lose and regain focus while pointer is over the popup:
// verify the dropdown stays open and the query is not re-selected.
*picked.borrow_mut() = None;
h.get(By::new().role(Role::TextInput)).click();
h.get(By::new().role(Role::Button).label_contains("Font options")).click();
h.run_steps(2);
h.event(egui::Event::Text("co".into()));
h.run_steps(2);
+10
View File
@@ -39,9 +39,12 @@ pub(crate) struct WindowUi {
pub(crate) seen_full_screen: Option<bool>,
pub(crate) escape_free: bool,
pub(crate) status_counts: (u64, crate::StatusCounts),
pub(crate) print_memo: crate::print_page::Memo,
/// Per window, as each window shows its own layout: one shared list would be read again
/// on every frame of every window.
pub(crate) missing_fonts: crate::chrome::MissingFontsMemo,
/// This window's refused or failed export, shown on its Export and Print pages (Backstage hides the status bar).
pub(crate) export_error: String,
pub(crate) last_autosave: f64,
pub(crate) equation_prev_tab: Option<String>,
pub(crate) smart_art_item: Option<usize>,
@@ -112,7 +115,9 @@ impl WindowUi {
seen_full_screen: None,
escape_free: false,
status_counts: NOT_COUNTED,
print_memo: Default::default(),
missing_fonts: Default::default(),
export_error: String::new(),
last_autosave: 0.0,
equation_prev_tab: None,
smart_art_item: None,
@@ -164,6 +169,7 @@ impl WordApp {
services: _,
printing: _,
print_feedback_seen: _,
print_gen: _,
font_generation: _,
integrated_titlebar: _,
mac_titlebar: _,
@@ -243,7 +249,9 @@ impl WordApp {
seen_full_screen,
escape_free,
status_counts,
print_memo,
missing_fonts,
export_error,
last_autosave,
equation_prev_tab,
smart_art_item,
@@ -349,7 +357,9 @@ impl WordApp {
seen_full_screen,
escape_free,
status_counts,
print_memo,
missing_fonts,
export_error,
last_autosave,
equation_prev_tab,
smart_art_item,
+1 -1
View File
@@ -84,7 +84,7 @@ let apps move windows, so there Arrange All and Side by Side only resize.
| Method | Params | Result |
|---|---|---|
| `engine.execute` | `command`, `params`, `doc?` | the command's result (any id from `engine.commands`, including UI commands `ui.tab`, `ui.dialog` (`{"name": dialog, "part"?: table style part}`; `part` opens New / Modify Table Style (`newTableStyle` / `modifyTableStyle`) on that part: `wholeTable`, `headerRow`, `firstColumn`, `bandedRows`, `nwCell`… as `table.modifyStyle` names them), `ui.backstage`, `ui.zotero.*` (see `docs/zotero.md`), `ui.language` (`{"value": "auto"\|"en"\|"zh-hans"\|"zh-hant"\|"ja"\|"pt-br"\|"es"\|"uk"\|"sr"\|"sr-latn"\|"et"\|"tr"\|"ru"\|"pl"\|"de"\|"it"\|"cs"\|"hu"\|"fr"}`), `ui.theme` (`{"value": "system"\|"light"\|"dark"}`; `system` follows the OS appearance, light when it reports none), `ui.interfaceSize` (`{"value": "auto"}` or `{"percent": 50–300}`, clamped; no value reads it; `auto` keeps the system display scale, capped so a window of at least 900x460 points fits the screen (#4030), a percentage is absolute, so 100 is one screen pixel per point (#822); the result's `percent` is the size drawn at and `auto` whether it follows the system; document zoom stays `view.zoom`), `ui.animations` (`{"value": "system"\|"on"\|"off"}`; no value reads it; `system` follows the system's animation setting, which the desktop app reads on Windows, macOS, Linux and the BSDs and the web app from `prefers-reduced-motion`, and means on where the system doesn't say; the result's `enabled` is what the setting comes to and `system` what the system reports, `null` when it doesn't say), `ui.fileBrowser` (desktop: `{"purpose": "document"\|"picture"\|"recipients"\|"save"}` opens WordCraft's own file browser, for when the system file dialog doesn't show up, #576), `ui.saveAsTemplate` (File › Save As › Save as Word Template: the Save dialog for a `.dotx`, starting in the user templates folder; the result's `dir` is that folder, `null` on the web, #2852), `ui.caretAnimation` (`{"value": true\|false}`; no value reads it; off, the caret jumps and blinks on and off instead of gliding and fading), `ui.startScreen` (`{"value": true\|false}`; no value reads it; on, the default, the desktop and web apps start on File › Home when launched with nothing to open, #766), `ui.alignmentGuides` (`{"value": true\|false}`; no value reads it; on, the default, moving a picture or shape snaps it to the page, the margins and other objects, with guide lines while dragging; Alt moves freely), `ui.quickAccessToolbar` (`{"value": true\|false}`; no value toggles it; false takes the Quick Access Toolbar out of the title bar, as its menu's Hide Quick Access Toolbar does, and true brings it back, #1945), `ui.displayServer` (`{"value": "auto"\|"wayland"\|"x11"}`; no value reads it; File › Options › Advanced › Linux display server, which the desktop app reads on Linux and the BSDs at its next launch; `WORDCRAFT_WAYLAND` overrides it, #2184), `ui.scrollSpeed` (`{"value": "slow"\|"normal"\|"fast"}`; no value reads it; mouse-wheel scroll speed, #6146), `ui.touchpadScrollSpeed` (`{"value": "slow"\|"normal"\|"fast"}`; no value reads it; scales touchpad scrolling on Wayland: slow 2×, normal 4×, fast 8×; on macOS: 0.5×, 1×, 2×; File › Options › Advanced › Scrolling › Touchpad scroll speed, #6146), `ui.statusCount` (`{"value": "words"\|"characters"\|"charactersNoSpaces"}`; no value reads it; what the status bar's count shows — words (the default), characters with spaces, or characters without spaces — kept between runs, #2797), `ui.recentRemove` (`{"path": entry}` takes that document off the recent list — `path` must be an entry on the list; on the desktop the new list is saved right away: the result's `saved` is true then, false with `saveError` when the write failed (the removal still holds for this run) and null where the host keeps no preferences (the web app, or preferences switched off), #2716), `ui.recentClear` (`{}` clears the whole list; the result reports `removed`, the new `recent` and `saved` as above), `ui.focusRibbon` (`{"value": true\|false}`; no value toggles it; in Focus, true drops the ribbon down over the page, as the bar's ⋯ does, and false puts it away, as a click on the page does; outside Focus it stays put away, #1678), `ui.contextMenu` (opens the page's context menu below the caret, as Shift+F10 does), `ui.paneDock` (`{"pane": "navigation"\|"clipboard"\|"styles"\|"styleInspector"\|"accessibility"\|"altText"\|"formatShape"\|"restrictEditing"\|"comments"\|"smartArtText", "dock"?: "left"\|"right"\|"float", "before"?: pane\|null}`; no `dock` reads it; docks or floats a task pane as its menu does, kept between runs; Styles is `view.stylesPaneDock`, #1756; `before` puts the pane directly before that pane in the order, outside it on their edge, as a drop over a docked pane's outer third does, and `null` after every pane; the order is kept between runs)…) |
| `engine.execute` | `command`, `params`, `doc?` | the command's result (any id from `engine.commands`, including UI commands `ui.tab`, `ui.dialog` (`{"name": dialog, "part"?: table style part}`; `part` opens New / Modify Table Style (`newTableStyle` / `modifyTableStyle`) on that part: `wholeTable`, `headerRow`, `firstColumn`, `bandedRows`, `nwCell`… as `table.modifyStyle` names them), `ui.backstage`, `ui.zotero.*` (see `docs/zotero.md`), `ui.language` (`{"value": "auto"\|"en"\|"zh-hans"\|"zh-hant"\|"ja"\|"pt-br"\|"es"\|"uk"\|"sr"\|"sr-latn"\|"et"\|"tr"\|"ru"\|"pl"\|"de"\|"it"\|"cs"\|"hu"\|"fr"}`), `ui.theme` (`{"value": "system"\|"light"\|"dark"}`; `system` follows the OS appearance, light when it reports none), `ui.interfaceSize` (`{"value": "auto"}` or `{"percent": 50–300}`, clamped; no value reads it; `auto` keeps the system display scale, capped so a window of at least 900x460 points fits the screen (#4030), a percentage is absolute, so 100 is one screen pixel per point (#822); the result's `percent` is the size drawn at and `auto` whether it follows the system; document zoom stays `view.zoom`), `ui.animations` (`{"value": "system"\|"on"\|"off"}`; no value reads it; `system` follows the system's animation setting, which the desktop app reads on Windows, macOS, Linux and the BSDs and the web app from `prefers-reduced-motion`, and means on where the system doesn't say; the result's `enabled` is what the setting comes to and `system` what the system reports, `null` when it doesn't say), `ui.fileBrowser` (desktop: `{"purpose": "document"\|"picture"\|"recipients"\|"save"\|"export"}` opens WordCraft's own file browser, for when the system file dialog doesn't show up, #576; `export` offers File › Export's formats as its types, #3535), `ui.saveAsTemplate` (File › Save As › Save as Word Template: the Save dialog for a `.dotx`, starting in the user templates folder; the result's `dir` is that folder, `null` on the web, #2852), `ui.caretAnimation` (`{"value": true\|false}`; no value reads it; off, the caret jumps and blinks on and off instead of gliding and fading), `ui.startScreen` (`{"value": true\|false}`; no value reads it; on, the default, the desktop and web apps start on File › Home when launched with nothing to open, #766), `ui.alignmentGuides` (`{"value": true\|false}`; no value reads it; on, the default, moving a picture or shape snaps it to the page, the margins and other objects, with guide lines while dragging; Alt moves freely), `ui.quickAccessToolbar` (`{"value": true\|false}`; no value toggles it; false takes the Quick Access Toolbar out of the title bar, as its menu's Hide Quick Access Toolbar does, and true brings it back, #1945), `ui.displayServer` (`{"value": "auto"\|"wayland"\|"x11"}`; no value reads it; File › Options › Advanced › Linux display server, which the desktop app reads on Linux and the BSDs at its next launch; `WORDCRAFT_WAYLAND` overrides it, #2184), `ui.scrollSpeed` (`{"value": "slow"\|"normal"\|"fast"}`; no value reads it; mouse-wheel scroll speed, #6146), `ui.touchpadScrollSpeed` (`{"value": "slow"\|"normal"\|"fast"}`; no value reads it; scales touchpad scrolling on Wayland: slow 2×, normal 4×, fast 8×; on macOS: 0.5×, 1×, 2×; File › Options › Advanced › Scrolling › Touchpad scroll speed, #6146), `ui.statusCount` (`{"value": "words"\|"characters"\|"charactersNoSpaces"}`; no value reads it; what the status bar's count shows — words (the default), characters with spaces, or characters without spaces — kept between runs, #2797), `ui.recentRemove` (`{"path": entry}` takes that document off the recent list — `path` must be an entry on the list; on the desktop the new list is saved right away: the result's `saved` is true then, false with `saveError` when the write failed (the removal still holds for this run) and null where the host keeps no preferences (the web app, or preferences switched off), #2716), `ui.recentClear` (`{}` clears the whole list; the result reports `removed`, the new `recent` and `saved` as above), `ui.focusRibbon` (`{"value": true\|false}`; no value toggles it; in Focus, true drops the ribbon down over the page, as the bar's ⋯ does, and false puts it away, as a click on the page does; outside Focus it stays put away, #1678), `ui.contextMenu` (opens the page's context menu below the caret, as Shift+F10 does), `ui.paneDock` (`{"pane": "navigation"\|"clipboard"\|"styles"\|"styleInspector"\|"accessibility"\|"altText"\|"formatShape"\|"restrictEditing"\|"comments"\|"smartArtText", "dock"?: "left"\|"right"\|"float", "before"?: pane\|null}`; no `dock` reads it; docks or floats a task pane as its menu does, kept between runs; Styles is `view.stylesPaneDock`, #1756; `before` puts the pane directly before that pane in the order, outside it on their edge, as a drop over a docked pane's outer third does, and `null` after every pane; the order is kept between runs)…) |
| `engine.commands` | — | every command: id, label, location, shortcut, params, enabled |
| `document.inspect` | `text?`, `doc?` | blocks (text, style, runs, lists, tables), parts, sections, selection, pages |
| `ui.inspect` | — | UI state, view, dialog, window size, page rects on screen, caret, comment balloons (`balloons`: id + screen rect; `balloon`: the selected one), perf; `windows`: the other windows as the drawn window sees them (`available`, `others`, `sideBySide`, `syncScroll`); `document`: the active document's id; `documents`: the open documents (`id`, `title`, `path`, `dirty`, `active`) |
+1
View File
@@ -198,6 +198,7 @@ Page Setup's margin, paper-size and document-grid number boxes scroll long text
| Date | Change | Summary |
|---|---|---|
| 2026-10-26 | trivial | Dialog sections improve readability across 13 dialogs; conditional scrolling keeps tall dialogs usable. Ranked gaps and estimates unchanged (#4035, #4038) |
| 2026-11-12 | trivial | Clipboard: a copied picture is published to the system clipboard as PNG, with HTML where the host writes it, and WordCraft's own paste keeps the original fragment; a copy of only shapes stays in WordCraft (#6205). Native external-app paste remains untested. |
| 2026-11-04 | trivial | #4501 refactor regressions restored: per-section header/footer grid, ODT default font, link tooltip (#4683); no ranked gap changed; readiness estimates unchanged |
| 2026-11-08 | trivial | #10 narrowed: a turned inline picture with no recorded effect extent keeps its line to its frame (exchanged near a quarter turn in Word 2013+ layout), cut at the line; gap stays open |
File diff suppressed because one or more lines are too long
+10 -3
View File
File diff suppressed because one or more lines are too long