Compare commits

..
Author SHA1 Message Date
Michael HigginsandClaude Opus 5.5 fea7a9182e #6518: typing after Backspace keeps the deleted character's formatting (#6522)
* #6518: typing after Backspace keeps the deleted character's formatting

As in Word, Backspace over one ordinary character leaves that character's
formatting waiting at the caret until it moves, and the Font buttons show
it. Forward Delete, deleting a selection and Track Changes carry nothing.

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

* #6518: a Backspace that changes nothing keeps formatting waiting at the caret

At the start of the document Backspace changes nothing, so the formatting carried from a deleted character, or set at the caret, still applies to the next typed text, as in Word for Windows. A paragraph join still drops it.

* #6518: Ctrl+Backspace that deletes nothing keeps formatting waiting at the caret

Observed in Word for Windows: at the start of the document Ctrl+Backspace changes nothing and the next typed text keeps formatting carried by an earlier Backspace or set at the caret; one that deletes a word or joins paragraphs drops it. WordCraft already behaves this way; pin it with a test and make the parity doc say so.

* #6518: formatting carried by Backspace applies only where the caret was

Backspace now records where it carried the deleted character's formatting
(Session::pending_at). Typing moves that place along; anything else that
leaves the caret elsewhere or selects text (a paste, Find, Go To, a click
in the front end) drops the carried formatting before the next command and
whenever it is read, so typing takes the formatting where the caret is.
Pasted text never takes it. The place is kept with undo steps, window views
and parked documents. Formatting set at the caret (Bold with nothing
selected) is unchanged.

Tests: Backspace then paste then type, Backspace then Find/Go To/click then
type, a Find with no match keeps it, typing and Undo keep it.

* #6518: Backspace with Track Changes on carries the deleted character's formatting

* #6518: keep carried formatting through failed commands and drop it on direct caret moves

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 18:40:41 +00:00
pakiatandClaude Opus 5.5 cdebeace8d DOCX: a run marked w:cs is bold and italic only by w:bCs and w:iCs (#4852)
* DOCX: a run marked w:cs is bold and italic only by w:bCs and w:iCs

Word draws Thai marked w:cs with <w:b/> and no w:bCs plain (and with
<w:i/> and no w:iCs upright), through the run, its styles and the
defaults. WordCraft borrowed the Latin bold and italic, so a WPS memo's
subject line showed bold. Runs not marked w:cs still borrow them, and
the complex-script size still borrows w:sz until generated styles carry
w:szCs (#4197).

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

* Bold and Italic buttons follow what a complex-script run shows

A run marked w:cs shows its w:bCs/w:iCs, so format.state reports those
and format.bold/format.italic toggle from them (CodeRabbit on #4852).

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

* Bold and Italic buttons read right-to-left runs' complex-script values

Layout draws a w:rtl run with its complex-script bold and italic, so the
buttons and their toggles read those for rtl runs as for cs ones
(CodeRabbit on #4852).

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

* Test the Latin text keeps w:b and w:i beside complex-script runs

Review: every case of complex_script_runs_take_bold_and_italic_only_from_bcs_and_ics now also checks the run's Latin bold and italic, through every save generation; Hebrew no writer marked w:cs keeps borrowing w:b, as Word draws it bold (measured in Word for Windows).

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

* Merge Formatting and style sets keep complex-script bold and italic

Merge Formatting gives pasted text the destination's w:cs, so its emphasis
now sets w:bCs/w:iCs with w:b/w:i (either one in the source counts). The
basic and casual style sets make headings bold and italic in both scripts.

The file-format parity sentence goes into the current row instead of an
older copy of it the merge had added.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 18:35:32 +00:00
Mex 46954248d1 M14: expose supported TIFF pictures in choosers and errors (#6704)
* M14: list TIFF in supported picture formats

Match the existing TIFF probe support and insertion test in the unsupported-format diagnostic.

* M14: show TIFF files in picture choosers

* M14: cover TIFF visibility in the picture browser

* M14: include TIFF in the web picture chooser

* M14: document supported TIFF pictures and chooser coverage

* Update roadmap with recent changes and dates

* M14: share picture suffixes and cover TIFF inbox routing

The PICTURES constant is now public and includes picture suffixes for file dialogs. Added a new function to check if a file name has a picture suffix.

* M14: dispatch TIFF drops and picked files as pictures

* M14: recognize TIFF paths through shared picture suffixes

* M14: keep the web picture chooser on the shared suffix list

* M14: restore complete format-parity revision history

Restore the complete upstream file from be56b5f1bb and reapply only the TIFF status clause, Pictures row and owned revision entry. Preserve all upstream history, including the rounded-rectangle update, and describe chooser, drop, inbox and pasted-path routing accurately. Complete source captured in chunks; inverse transformation exactly reproduces upstream. No local build or tests run for this documentation repair; hosted CI will validate the new head.

* M14: record TIFF drop and pasted-path routing

Update only the three TIFF-owned roadmap lines to mention native drops, picked-file inbox dispatch and pasted picture paths, matching the shared suffix routing already implemented. Preserve the complete 1460-line roadmap and all existing revision history. No local build or tests run for this wording-only follow-up.

* M14: carry TIFF picture routing onto framework file services

Preserve the incoming #7101 file-service implementation and reapply the shared TIFF suffix list. Port chooser/drop/copied-path regressions to ScriptedFiles and FileIntake. Companion conflict-resolution commits will retain the remaining incoming framework files before updating the branch from main. No local Rust toolchain is available; hosted CI must validate the integrated head.

* M14: preserve framework intake while dispatching TIFF drops

Carry the incoming #7101 file-intake and close-guard implementation unchanged, except for routing picture drops through the shared picture suffix predicate. This preserves TIFF name dispatch and the incoming framework changes. Hosted CI will validate after the companion conflict resolutions and main update.

* M14: keep incoming framework web picker integration

Retain the complete current-main web host implementation from #7101. Native and web picture filters now come through the UI crate's PickRequest rather than an app-local IMAGE_EXTS list. This file intentionally matches incoming main to resolve the framework migration conflict.

* M14: retain framework fallback chooser migration

Keep #7101's removal of the app-local file browser; the framework file service owns the fallback chooser. TIFF filter, selected-content, drop and copied-path coverage is carried in file_dialogs::picture_dispatch_tests against the new request and intake APIs.

* M14: preserve incoming parity updates and continuous revision history

Start from the complete current-main parity document, retain the incoming frame-preset status, content and history, and reapply only the TIFF-owned status, Pictures row and revision entry. Remove the duplicated October status block and surrounding blank lines so all revision rows form one continuous Markdown table. All 453 upstream table rows are retained; one TIFF revision row is added. No local build or runtime test ran for this documentation repair.
2026-11-20 18:28:19 +00:00
FredApps f2e6234c52 Merge pull request #5132 from squalorso/formatting-shortcuts-say-what-they-did
Screen readers: formatting shortcuts say what they did, as Word does
2026-11-21 00:00:57 +07:00
FredApps f42efe368c Merge main and preserve both accessibility roadmap entries 2026-11-20 16:56:45 +01:00
FredApps eb5a5a451c Merge pull request #5057 from squalorso/dialog-controls-named
#3172: dialogs, their tabs and colour fields say what they are
2026-11-20 22:54:59 +07:00
FredApps 147780b8a8 Set explicit theme swatch in migrated dialog regressions 2026-11-20 15:50:43 +01:00
FredApps ec8f946621 Read explicit live properties directly from the AccessKit predicate node 2026-11-20 15:49:19 +01:00
FredApps e4f17d8dcc Distinguish formatting announcements from status-bar live regions in regressions 2026-11-20 15:39:58 +01:00
FredApps 20c06f9f77 Use framework-era language API in dialog regression 2026-11-20 15:27:10 +01:00
FredApps 79a36f192d Merge main and preserve dialog accessibility on framework surfaces 2026-11-20 15:18:59 +01:00
FredApps 578f3576e9 Format the font-size announcement using the active number region 2026-11-20 15:15:21 +01:00
FredApps e28050be8b Merge main and announce formatting shortcuts through the framework command runtime 2026-11-20 15:14:16 +01:00
squalorso d22840c369 Announcements: each window keeps its own
An announcement was app-wide, so for three seconds every window drawn put it
in its own tree, though it describes formatting in the window whose shortcut
made it. It is now per-window state, swapped with the window's status message
and the rest, and a test checks that another window has nothing to say.
2026-11-18 14:51:11 +01:00
squalorso a7257e8fed Main's newer dialog tests: a dialog tab is a tab, a dialog is a dialog
Three tests that reached main after this branch's last merge look the
dialogs up by the roles this branch replaces: the tab strip's tabs as
toggle buttons (tests_dialog_tabs, widgets::tests) and Date and Time as a
window. With this branch they are a tab, selected or not, and a dialog, as
in Word, so the tests now ask for those.
2026-11-18 13:47:37 +01:00
squalorso 0478b7633f Merge main (4e8c9d55) into formatting-shortcuts-say-what-they-did 2026-11-18 13:42:34 +01:00
squalorso 3eaf2e1dcf Merge main (4e8c9d55) into dialog-controls-named 2026-11-18 13:41:12 +01:00
squalorsoandClaude Opus 5.5 7d1b59ffd7 Merge main (661a7905) into dialog-controls-named
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 10:51:36 +01:00
squalorsoandClaude Opus 5.5 f5c59929b7 Merge main (421bc8cd) into dialog-controls-named
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 22:40:41 +01:00
squalorsoandClaude Opus 5.5 5df58a74e8 #3172: test every kind of colour field's name, translated too
After review: a colour field's drop-down says its label and its colour
in each kind of field (Font's Font color, Borders' Color, Shading's Fill,
a table style's Font color and Fill color), the colour picked after a
click, and in a fixture language the translated label and "none" entry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 20:55:05 +01:00
squalorsoandClaude Opus 5.5 cb149e62a2 Tests: every formatting shortcut's words, and a burst of presses
Each shortcut says its own words, read from the formatting after it ran. Ten presses, one per frame or all in one, leave one announcement, the latest, in one live region, and the words go through the interface catalogs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 20:33:38 +01:00
squalorsoandClaude Opus 5.5 ee167c2696 Merge main (bbe3547d) into dialog-controls-named
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 19:45:03 +01:00
squalorsoandClaude Opus 5.5 4a1b0aac18 Merge main (bbe3547d) into formatting-shortcuts-say-what-they-did
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 19:25:56 +01:00
squalorsoandClaude Opus 5.5 016d9f3525 Merge main (84b4623e) into dialog-controls-named
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 18:55:11 +01:00
squalorsoandClaude Opus 5.5 6b5f158769 Screen readers: an alignment shortcut says what the paragraph it formatted now is
A selection ending at the next paragraph's start (Shift+Down from a paragraph's
start) formats only the paragraph it covers (#418), but the announcement read
the alignment at the focus, in the paragraph left out: Ctrl+E said "Center Off"
after centring. It now reads a paragraph the command formatted, as the command
chooses it. A test also pins that the announcement is in the tree on the frame
after the key, which egui asks for itself.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 01:41:26 +01:00
squalorsoandClaude Opus 5.5 7e5f66bdac Screen readers: formatting shortcuts say what they did, as Word does
After a keyboard shortcut for Bold, Italic, Underline, Subscript or
Superscript, an alignment or the font size, WordCraft announces what it did in
a polite live region, in the words Word uses: "Bold On", "Bold Off",
"Center On", "Font 14 pt". Each announcement is a new node, so the same words
twice are heard twice, and it stays three seconds. Ribbon clicks aren't
announced: their buttons say their state.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 00:46:43 +01:00
squalorsoandClaude Opus 5.5 ebd5dbdbab gaps: NVDA was tried on the dialogs; VoiceOver and Orca not yet
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 17:54:17 +01:00
squalorsoandClaude Opus 5.5 ada55c97d6 Merge main (e6a5cd05) into dialog-controls-named
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 17:26:49 +01:00
squalorsoandClaude Opus 5.5 6e8c5e5a44 Merge main (401c6c0d) into dialog-controls-named
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 16:58:13 +01:00
squalorsoandClaude Opus 5.5 d75d53376c #3172: only the first status line of ROADMAP.md and gaps.md moves
CodeRabbit on 6eab393e: the second status line of ROADMAP.md (and of
docs/gaps.md) repeated the first one's new entry. main's own changes
update only the first line; the second is back as main has it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 16:13:57 +01:00
squalorsoandClaude Opus 5.5 6eab393ee7 Merge main (c9349771) into dialog-controls-named
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 15:37:14 +01:00
squalorsoandClaude Opus 5.5 eb7e360652 #3172: doc comments on the Font dialog and the colour swatch (review)
The two functions this PR touches without a doc comment get one, as
CodeRabbit's docstring check asked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 12:13:00 +01:00
squalorsoandClaude Opus 5.5 8c73173d92 #3172: a dialog is a dialog to screen readers
Every dialog was an egui window, so to UI Automation a plain window:
NVDA said "Font, window", and read none of the text in it. It is now a
dialog (Role::Dialog, which AccessKit exposes with IsDialog), as Word's
are, and NVDA reads the dialog's text as it opens: Word Count's figures
("Pages 1, Words 70, …"), Bookmark's "The document has no bookmarks
yet", Insert Hyperlink's labels. Save Changes stays an alert dialog.

Two tests looked for Cross-reference and Table of Figures as windows;
they look for dialogs now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 12:07:02 +01:00
squalorsoandClaude Opus 5.5 c787c3e8b2 #3172: dialog tabs are tabs, and colour fields say their colour
Screen readers heard what dialogs draw only in part:
- a dialog's tabs (Paragraph, Find and Replace, About) were buttons
  with a selected state, read as toggles ("Indents and Spacing, toggle
  button, pressed"). They are tabs now, the one shown selected, which UI
  Automation exposes as a tab item with SelectionItem, as Word's are;
- a colour field's drop-down (Font color in Font, the borders' and
  fill's colours, table styles) was named by its text alone, the
  colour's hex digits ("104861, button"). It now says its field's label
  and the colour ("Font color: #104861"), or None/Automatic;
- the colour grid's swatches had no name; each says its colour, as its
  tooltip shows it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 11:38:55 +01:00
47 changed files with 1296 additions and 78 deletions
+16 -12
View File
@@ -1,4 +1,4 @@
# Exercise the native print host and all UI tests on Windows and macOS on PRs; the broad FreeBSD/ARM64 gates
# Exercise the native print host and all UI tests on PRs; the broad FreeBSD/ARM64 gates
# stay on their existing nightly/release schedule.
name: Printing
@@ -30,27 +30,31 @@ concurrency:
cancel-in-progress: true
jobs:
# The print host and UI tests on Windows and macOS, through the suite's shared gate: it checks out
# craft-i18n (craft-i18n.rev) and craft-fonts. Linux is not repeated here: ci.yml's gate runs
# `cargo xtask ci` there, which already covers fmt, workspace clippy, every test and the wasm build.
# The print host and UI tests on Linux, Windows and macOS, through the suite's shared gate: it
# checks out craft-i18n (craft-i18n.rev) and craft-fonts, and installs the Ubuntu packages through
# install-apt-packages, which falls back to mirrors outside ubuntu.com (as on 11 Nov 2026).
native:
name: Print
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
with:
os: '["windows-latest","macos-latest"]'
os: '["ubuntu-24.04","windows-latest","macos-latest"]'
timeout-minutes: 90
# The catalogs include CJK interface languages, so the UI tests need the suite's fonts, as in
# the gate (same commit as ci.yml and release.yml).
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
packages: >-
pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcursor-dev libxrandr-dev
libxi-dev libgtk-3-dev libfontconfig1-dev libfreetype-dev libvulkan1 mesa-vulkan-drivers
# No nextest: the tests run with cargo test, as before.
tools: ""
# Its own cache, apart from ci.yml's gate, which builds the whole workspace.
cache-version: v1-printing
# Test binaries without debug info: they link faster and shrink to about a third, and panics
# keep their file:line.
dev-strip: true
# Clippy on its own leg beside the tests, off their critical path. fmt is platform-independent
# and runs in ci.yml.
lint-command: cargo clippy -p wordcraft -p wordcraft-ui-egui --all-targets --locked -- -D warnings
command: cargo test -p wordcraft -p wordcraft-ui-egui --locked
command: |
cargo fmt --all -- --check
cargo clippy -p wordcraft -p wordcraft-ui-egui --all-targets --locked -- -D warnings
cargo test -p wordcraft -p wordcraft-ui-egui --locked
# Browser compatibility, once.
if [ "$RUNNER_OS" = Linux ]; then
cargo check -p wordcraft-web --target wasm32-unknown-unknown --locked
fi
+10 -2
View File
File diff suppressed because one or more lines are too long
+7 -2
View File
@@ -118,8 +118,13 @@ impl ResolvedChar {
font_cs: c.font_cs.clone().or_else(|| c.font.clone()).unwrap_or_else(|| crate::styles::BODY_FONT.to_string()),
font_ea: c.font_ea.clone(),
size_cs: c.size_cs.or(c.size).unwrap_or(crate::props::DEFAULT_FONT_SIZE).clamp(1.0, 1638.0),
bold_cs: c.bold_cs.or(c.bold).unwrap_or(false),
italic_cs: c.italic_cs.or(c.italic).unwrap_or(false),
// A run marked complex script (`w:cs`) is bold and italic only by `w:bCs` and `w:iCs`:
// Word draws Thai with `<w:b/><w:cs/>` and no `w:bCs` upright and plain (measured in
// Word for Windows). Other runs, including those no DOCX marked, still borrow the
// Latin values. The size keeps borrowing `w:sz` until generated styles carry a
// `w:szCs` (#4197).
bold_cs: c.bold_cs.or(c.bold.filter(|_| c.cs != Some(true))).unwrap_or(false),
italic_cs: c.italic_cs.or(c.italic.filter(|_| c.cs != Some(true))).unwrap_or(false),
}
}
/// The formatting complex-script text in this run is drawn with: the complex-script font,
@@ -142,6 +142,34 @@ fn complex_script_direct_properties_leave_latin_defaults_inherited() {
});
}
#[test]
fn complex_script_runs_take_bold_and_italic_only_from_bcs_and_ics() {
// Word draws Thai marked `w:cs` with `<w:b/><w:i/>` and no `w:bCs`/`w:iCs` neither bold nor
// italic, through a style too; a run not marked `w:cs`, as older writers leave Hebrew, still
// borrows the Latin values (Word draws such Hebrew bold). The Latin text of every run keeps
// `w:b` and `w:i`. Measured in Word for Windows.
let styles = r#"
<w:style w:type="paragraph" w:styleId="LatinBold"><w:name w:val="LatinBold"/><w:rPr><w:b/><w:i/></w:rPr></w:style>
<w:style w:type="paragraph" w:styleId="BothBold"><w:name w:val="BothBold"/><w:rPr><w:bCs/><w:iCs/></w:rPr></w:style>"#;
let cases = [
(r#"<w:b/><w:i/><w:cs/>"#, "", false),
(r#"<w:cs/>"#, r#"<w:pStyle w:val="LatinBold"/>"#, false),
(r#"<w:b/><w:i/><w:cs/>"#, r#"<w:pStyle w:val="BothBold"/>"#, true),
(r#"<w:b/><w:bCs/><w:i/><w:iCs/><w:cs/>"#, "", true),
(r#"<w:b/><w:i/>"#, "", true),
];
for (run, style, complex) in cases {
check_generations(&package(run, "", styles, style), |d| {
let p = paragraph(d);
let c = d.styles.resolve_char(p.props.style.as_deref(), &p.runs[0].props);
let cs = c.complex();
assert_eq!((cs.bold, cs.italic), (complex, complex), "{run} {style}");
let latin = run.contains("<w:b/>") || style.contains("LatinBold");
assert_eq!((c.bold, c.italic), (latin, latin), "Latin text: {run} {style}");
});
}
}
#[test]
fn tracked_formatting_keeps_independent_complex_script_values() {
let defaults = r#"<w:szCs w:val="36"/><w:bCs/><w:iCs/>"#;
+10
View File
@@ -376,6 +376,12 @@ pub fn type_text_with_lang(s: &mut Session, text: &str, language: Option<&str>)
/// right-to-left direction when its first strong letter is RTL, and returns whether content or state
/// changed.
fn insert_text(s: &mut Session, text: &str, enter: bool, language: Option<&str>) -> Result<InsertEffect, CmdError> {
// Formatting Backspace carried over is for typing at the place it was deleted (#6518).
if enter {
s.drop_stale_carried();
} else {
s.forget_carried();
}
let mut props = s.typing_props();
if s.sel.is_collapsed() {
s.sel = crate::Selection::caret(s.doc.past_field_ends(&s.sel.focus));
@@ -437,6 +443,10 @@ fn insert_text(s: &mut Session, text: &str, enter: bool, language: Option<&str>)
}
}
}
// Formatting Backspace carried over goes on applying to the text typed after this (#6518).
if s.pending_at.is_some() {
s.pending_at = Some(at.clone());
}
s.sel = crate::Selection::caret(at);
s.goal_x = None;
let content_changed = deletion.content_changed || inserted;
+7 -1
View File
@@ -155,14 +155,20 @@ fn style_set(s: &mut Session, v: &Value) -> CmdResult {
match name {
"basic" if heading => {
st.chr.color = Some(TextColor::Rgb(Rgb(0x26, 0x26, 0x26)));
// Both scripts, as Word's own heading styles carry `w:b` with `w:bCs`: a Thai
// heading in a run marked `w:cs` is drawn bold too.
st.chr.bold = Some(true);
st.chr.bold_cs = Some(true);
}
"lines" if st.id == "Heading1" || st.id == "Title" => st.para.borders = Some(Borders { bottom: Some(line), ..Default::default() }),
"shaded" if st.id == "Heading1" => {
st.para.shading = Some(accent);
st.chr.color = Some(TextColor::Rgb(Rgb::WHITE));
}
"casual" if heading => st.chr.italic = Some(true),
"casual" if heading => {
st.chr.italic = Some(true);
st.chr.italic_cs = Some(true);
}
"centered" if heading => st.para.align = Some(wordcraft_doc::Align::Center),
"minimalist" if heading => {
st.chr.caps = Some(true);
+20 -5
View File
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
toggle(
s,
v,
|r| r.bold,
shown_bold,
|c, on| {
c.bold = Some(on);
c.bold_cs = Some(on);
@@ -34,7 +34,7 @@ pub fn specs() -> Vec<CommandSpec> {
toggle(
s,
v,
|r| r.italic,
shown_italic,
|c, on| {
c.italic = Some(on);
c.italic_cs = Some(on);
@@ -281,7 +281,10 @@ fn resolved(s: &Session) -> Vec<ResolvedChar> {
return out;
}
}
let Some((a, b)) = selected_text_box(s).or_else(|| target(s)) else {
// Formatting waiting at a caret is what the caret shows, also inside a word: after Backspace
// it is the deleted character's (#6518), as Word's buttons show it.
let waiting = s.sel.is_collapsed() && s.waiting().is_some();
let Some((a, b)) = selected_text_box(s).or_else(|| target(s)).filter(|_| !waiting) else {
let f = &s.sel.focus;
let style = s.doc.para_at(f).and_then(|p| p.props.style.clone());
out.push(s.doc.styles.resolve_char(style.as_deref(), &s.typing_props()));
@@ -310,6 +313,18 @@ fn resolved(s: &Session) -> Vec<ResolvedChar> {
out
}
/// Bold as drawn: a run marked complex script (`w:cs`) or right to left (`w:rtl`) shows its
/// complex-script bold.
fn shown_bold(r: &ResolvedChar) -> bool {
if r.cs || r.rtl { r.bold_cs } else { r.bold }
}
/// Italic as drawn: a run marked complex script (`w:cs`) or right to left (`w:rtl`) shows its
/// complex-script italic.
fn shown_italic(r: &ResolvedChar) -> bool {
if r.cs || r.rtl { r.italic_cs } else { r.italic }
}
fn toggle(s: &mut Session, v: &Value, get: fn(&ResolvedChar) -> bool, set: fn(&mut CharProps, bool)) -> CmdResult {
let on = match p::bool(v, "value") {
Some(b) => b,
@@ -887,8 +902,8 @@ pub fn state(s: &Session) -> Value {
"fontShownAs": shown_as,
"fontEastAsia": same(&|r| json!(r.font_ea)),
"size": same(&|r| json!(r.size)),
"bold": all.iter().all(|r| r.bold),
"italic": all.iter().all(|r| r.italic),
"bold": all.iter().all(shown_bold),
"italic": all.iter().all(shown_italic),
"underline": all.iter().all(|r| r.underline != Underline::None),
"underlineColor": same(&|r| json!(r.underline_color.map_or_else(|| "auto".to_string(), |c| c.hex()))),
"strike": all.iter().all(|r| r.strike),
+1 -1
View File
@@ -114,7 +114,7 @@ fn place_picture(s: &mut Session, bytes: Vec<u8>, width: Option<f32>, alt: &str)
Err(wordcraft_geom::picture::Refusal::Unsupported(why)) => return Err(CmdError::Failed(why.into())),
Err(_) => match wordcraft_render::metafile_size(&bytes) {
Some(size) => size,
None => return Err(CmdError::Failed("not a supported image (PNG, JPEG, GIF, WebP, BMP, WMF, EMF)".into())),
None => return Err(CmdError::Failed("not a supported image (PNG, JPEG, GIF, WebP, BMP, TIFF, WMF, EMF)".into())),
},
};
let key = s.doc.add_media(bytes, ext);
+17 -2
View File
@@ -281,6 +281,14 @@ pub enum Pasted {
/// that knows another program owns the clipboard passes `privateClipboard: false`, which keeps
/// the fragment out even when the text matches.
pub fn paste_content(s: &mut Session, v: &Value) -> Result<Pasted, CmdError> {
let pasted = clipboard_content(s, v)?;
// Formatting Backspace carried over is for typing, not for what is pasted (#6518). An empty
// clipboard pastes nothing, so it stays.
s.forget_carried();
Ok(pasted)
}
fn clipboard_content(s: &mut Session, v: &Value) -> Result<Pasted, CmdError> {
let text = p::str(v, "text").map(|t| t.replace("\r\n", "\n"));
if owns_clipboard(v)
&& let Some(f) = &s.clipboard
@@ -330,11 +338,16 @@ pub fn merge_formatting(s: &Session, frag: &mut Fragment) {
p.props = para.clone();
for run in &mut p.runs {
let src = std::mem::replace(&mut run.props, base.clone());
if src.bold == Some(true) {
// Emphasis in either script is kept for both, as the Bold and Italic buttons set
// it: text pasted into a run marked `w:cs` (Thai from a WPS or Word file) is drawn
// with the complex-script bold and italic.
if src.bold == Some(true) || src.bold_cs == Some(true) {
run.props.bold = Some(true);
run.props.bold_cs = Some(true);
}
if src.italic == Some(true) {
if src.italic == Some(true) || src.italic_cs == Some(true) {
run.props.italic = Some(true);
run.props.italic_cs = Some(true);
}
if src.underline.is_some_and(|u| u != wordcraft_doc::props::Underline::None) {
run.props.underline = src.underline;
@@ -354,6 +367,8 @@ pub fn merge_formatting(s: &Session, frag: &mut Fragment) {
/// Replace the selection with `frag`, marking it as an insertion under Track Changes.
pub fn insert(s: &mut Session, mut frag: Fragment) -> Result<(), CmdError> {
// The pasted text keeps its own formatting; what Backspace carried over is not for after it (#6518).
s.forget_carried();
super::controls::prepare_edit(s)?;
let at = delete_selection(s)?;
let track = s.doc.settings.track_changes;
+48 -4
View File
@@ -1,9 +1,17 @@
use super::enter_tab::tab_indent_on;
use super::{Block, CmdResult, NumRef, OBJ, Pos, Selection, Session, StoryRef, Value, delete_selection, delete_selection_effect, sel_result};
use super::{
Block, COLUMN_BREAK, CmdResult, NumRef, OBJ, PAGE_BREAK, Pos, Selection, Session, StoryRef, Value, delete_selection, delete_selection_effect,
sel_result,
};
pub(super) fn backspace(s: &mut Session, v: &Value) -> CmdResult {
let r = backspace_inner(s, v)?;
crate::cmd::controls::restore_placeholder(s)?;
// A content control's placeholder is back: typing replaces it, so nothing is carried.
if s.doc.control_at(&s.sel.focus).is_some_and(|r| r.control.showing_placeholder) {
s.pending = None;
s.pending_at = None;
}
Ok(r)
}
@@ -29,9 +37,32 @@ fn remove_number(s: &mut Session, f: &Pos, n: NumRef) -> CmdResult {
sel_result(s)
}
/// The formatting Backspace carries over from the character between `a` and `f` (#6518): only an
/// ordinary character, not an object, field or anchor marker or a page or column break. With Track
/// Changes on it carries too, as in Word: the character stays, marked deleted (or goes, when this
/// author inserted it), and the caret sits before it. Cleaned up the way the caret's own
/// formatting is: no hyperlink, symbol font, note-number style or revision marks, so typed text
/// gets its own insertion mark and never the deletion.
fn deleted_char_props(s: &Session, a: &Pos, f: &Pos) -> Option<wordcraft_doc::props::CharProps> {
let p = s.doc.para_at(f)?;
let text = p.text.get(a.off..f.off).filter(|t| !t.is_empty())?;
if text.contains([OBJ, PAGE_BREAK, COLUMN_BREAK]) {
return None;
}
let mut props = p.props_of_char(a.off).unlinked().without_symbol();
if matches!(props.style.as_deref(), Some("FootnoteReference" | "EndnoteReference")) {
props.style = None;
}
props.ins = None;
props.del = None;
props.fmt_change = None;
Some(props)
}
fn backspace_inner(s: &mut Session, _: &Value) -> CmdResult {
s.goal_x = None;
s.pending = None;
// Kept for a Backspace that changes nothing, which leaves Word's carried formatting alone.
let kept = (s.pending.take(), s.pending_at.take());
if !s.sel.is_collapsed() {
let effect = delete_selection_effect(s)?;
s.set_ime_edit_outcome(crate::ImeEditOutcome {
@@ -59,7 +90,8 @@ fn backspace_inner(s: &mut Session, _: &Value) -> CmdResult {
if let Some(c) = s.autocap.as_mut() {
c.note_backspace(&a, &f);
}
s.sel = Selection { anchor: a, focus: f };
let carried = deleted_char_props(s, &a, &f);
s.sel = Selection { anchor: a.clone(), focus: f };
let effect = delete_selection_effect(s)?;
s.set_ime_edit_outcome(crate::ImeEditOutcome {
classified: true,
@@ -68,6 +100,12 @@ fn backspace_inner(s: &mut Session, _: &Value) -> CmdResult {
transformed: false,
selection_changed: false,
});
// As in Word, text typed next takes the deleted character's formatting until the caret
// moves (#6518): it applies here only, so whatever puts the caret elsewhere drops it.
if effect.content_changed && s.sel.is_collapsed() && s.sel.focus == a {
s.pending_at = carried.as_ref().map(|_| a.clone());
s.pending = carried;
}
return sel_result(s);
}
// At the start of a paragraph.
@@ -93,7 +131,10 @@ fn backspace_inner(s: &mut Session, _: &Value) -> CmdResult {
}
let i = f.path.last();
if i == 0 {
return sel_result(s); // start of a story or cell
// Start of a story or cell: nothing changes, so formatting waiting at the caret (carried
// from a deleted character, or set there) still applies to the next typed text (Word).
(s.pending, s.pending_at) = kept;
return sel_result(s);
}
let prev_path = f.path.with_last(i - 1);
match s.doc.block(f.story, &prev_path) {
@@ -216,6 +257,9 @@ pub(super) fn delete_word_back(s: &mut Session, v: &Value) -> CmdResult {
return backspace(s, v);
}
let a = Pos { off: para.word_start(f.off), ..f.clone() };
// Formatting a Backspace just carried over belongs to that deletion, not this one.
s.pending = None;
s.pending_at = None;
s.sel = Selection { anchor: a, focus: f };
delete_selection(s)?;
crate::cmd::controls::restore_placeholder(s)?;
+2
View File
@@ -126,6 +126,8 @@ pub(super) struct Undo {
pub(super) sel: Selection,
/// Formatting waiting at the caret (Bold with nothing selected), so Undo takes it back too.
pub(super) pending: Option<CharProps>,
/// Where that formatting applies, if Backspace carried it over (`Session::pending_at`).
pub(super) pending_at: Option<Pos>,
/// The column block or whole cells the selection was (undoing brings the selection back as
/// it was).
pub(super) column: Option<ColumnBlock>,
+5
View File
@@ -51,6 +51,11 @@ pub struct Session {
pub view: ViewState,
/// Formatting picked with a collapsed caret, applied to the next typed text.
pub pending: Option<CharProps>,
/// Where the caret was when Backspace carried [`Self::pending`] over from the character it
/// deleted (#6518), moved on as typing advances the caret. That formatting is for typing
/// there only: once the caret is anywhere else (a paste, Find, Go To or a click put it
/// there) it is dropped (see [`Self::waiting`]). `None` for formatting picked at the caret.
pub(crate) pending_at: Option<Pos>,
/// Last highlighter choice for the shortcut; palette state, outside document undo.
pub(crate) last_highlight: wordcraft_doc::props::Highlight,
pub path: Option<std::path::PathBuf>,
+5
View File
@@ -43,6 +43,7 @@ pub struct DocState {
pub(super) sel: Selection,
pub(super) view: ViewState,
pub(super) pending: Option<CharProps>,
pub(super) pending_at: Option<Pos>,
pub(super) path: Option<PathBuf>,
pub(super) file_name: Option<String>,
pub(super) dirty: bool,
@@ -99,6 +100,7 @@ impl DocState {
sel: Selection::caret(start),
view,
pending: None,
pending_at: None,
path: None,
file_name: None,
dirty: false,
@@ -202,6 +204,7 @@ impl Session {
sel: _,
view: _,
pending: _,
pending_at: _,
path: _,
file_name: _,
dirty: _,
@@ -303,6 +306,7 @@ impl Session {
sel,
view,
pending,
pending_at,
path,
file_name,
dirty,
@@ -352,6 +356,7 @@ impl Session {
swap(&mut self.sel, sel);
swap(&mut self.view, view);
swap(&mut self.pending, pending);
swap(&mut self.pending_at, pending_at);
swap(&mut self.path, path);
swap(&mut self.file_name, file_name);
swap(&mut self.dirty, dirty);
+11 -1
View File
@@ -14,6 +14,7 @@ impl Session {
doc: self.doc.clone(),
sel: self.sel.clone(),
pending: self.pending.clone(),
pending_at: self.pending_at.clone(),
column: self.column.clone(),
}));
if self.history.len() > MAX_UNDO {
@@ -34,7 +35,14 @@ impl Session {
/// Record `doc`/`sel` as their own undo step after the fact and close the typing group, so
/// Undo right after an automatic change (AutoFormat, AutoCorrect) reverts only that change.
pub fn push_undo(&mut self, label: &str, doc: Document, sel: Selection) {
self.history.push(Arc::new(Undo { label: label.to_string(), doc, sel, pending: self.pending.clone(), column: None }));
self.history.push(Arc::new(Undo {
label: label.to_string(),
doc,
sel,
pending: self.pending.clone(),
pending_at: self.pending_at.clone(),
column: None,
}));
if self.history.len() > MAX_UNDO {
self.history.remove(0);
self.undo_evicted += 1;
@@ -210,6 +218,7 @@ impl Session {
doc: std::mem::replace(&mut self.doc, u.doc),
sel: std::mem::replace(&mut self.sel, u.sel),
pending: std::mem::replace(&mut self.pending, u.pending),
pending_at: std::mem::replace(&mut self.pending_at, u.pending_at),
column: std::mem::replace(&mut self.column, u.column),
};
self.redo.push(Arc::new(cur));
@@ -236,6 +245,7 @@ impl Session {
doc: std::mem::replace(&mut self.doc, u.doc),
sel: std::mem::replace(&mut self.sel, u.sel),
pending: std::mem::replace(&mut self.pending, u.pending),
pending_at: std::mem::replace(&mut self.pending_at, u.pending_at),
column: std::mem::replace(&mut self.column, u.column),
};
self.history.push(Arc::new(cur));
+2
View File
@@ -41,6 +41,7 @@ impl Session {
sel,
view,
pending,
pending_at,
path,
file_name,
dirty,
@@ -91,6 +92,7 @@ impl Session {
sel,
view,
pending,
pending_at,
last_highlight: wordcraft_doc::props::Highlight::Yellow,
path,
file_name,
+42 -2
View File
@@ -225,7 +225,7 @@ impl Session {
pub fn typing_props(&self) -> CharProps {
let (a, _) = self.sel.ordered();
let first = match self.doc.para_at(&a) {
Some(p) if self.pending.is_none() && !self.sel.is_collapsed() && a.off < p.len() => Some(p.props_of_char(a.off)),
Some(p) if self.waiting().is_none() && !self.sel.is_collapsed() && a.off < p.len() => Some(p.props_of_char(a.off)),
_ => None,
};
let mut c = match first {
@@ -243,9 +243,49 @@ impl Session {
c
}
/// The formatting waiting for the next typed text ([`Self::pending`]), unless Backspace
/// carried it over at a place the caret has since left, or a selection now stands there:
/// that formatting is for typing where the character was deleted only (#6518).
pub fn waiting(&self) -> Option<&CharProps> {
let p = self.pending.as_ref()?;
match &self.pending_at {
Some(at) if !self.sel.is_collapsed() || self.sel.focus != *at => None,
_ => Some(p),
}
}
/// Forget formatting Backspace carried over once it no longer applies ([`Self::waiting`]):
/// whatever moved the caret or selected text — a paste, Find, Go To, a click — leaves the
/// next typed text the formatting of where it lands, as in Word (#6518).
pub(crate) fn drop_stale_carried(&mut self) {
if self.pending.is_none() {
self.pending_at = None;
} else if self.pending_at.is_some() && self.waiting().is_none() {
self.pending = None;
self.pending_at = None;
}
}
/// Move the caret or select text without a command, as a front end does for a right-click,
/// a click into a header or a balloon. Formatting Backspace carried over stays only if the
/// caret is still where the character was deleted: once it has been anywhere else, coming
/// back does not bring it back (#6518). Assigning [`Self::sel`] directly skips this.
pub fn set_selection(&mut self, sel: Selection) {
self.sel = sel;
self.drop_stale_carried();
}
/// Drop formatting Backspace carried over, wherever the caret is: it is for typing, and a
/// paste is not typing, so pasted text takes the formatting where it lands (#6518).
pub(crate) fn forget_carried(&mut self) {
if self.pending_at.take().is_some() {
self.pending = None;
}
}
/// The caret's formatting, as Reveal Formatting shows it.
pub fn caret_props(&self) -> CharProps {
if let Some(p) = &self.pending {
if let Some(p) = self.waiting() {
return p.clone();
}
let f = &self.sel.focus;
+29 -1
View File
@@ -70,7 +70,22 @@ impl Session {
{
crate::cmd::md_source::before_command(self, id, mutates)?;
}
self.run_command(id, params)
// Formatting Backspace carried over is for typing where the character was deleted: a
// caret the front end moved itself (a click elsewhere) has left it behind (#6518).
self.drop_stale_carried();
let carried_before = self.pending_at.clone().map(|at| (self.pending.clone(), at));
// The formatting waiting at the caret is not part of the document snapshot a failed
// command is rolled back to: put it back here, so a refused edit (a Backspace into a
// locked content control) leaves it as it was.
let document_before = self.document_id;
let waiting_before = (self.pending.clone(), self.pending_at.clone());
let result = self.run_command(id, params);
if result.is_ok() {
self.settle_carried(carried_before);
} else if self.document_id == document_before {
(self.pending, self.pending_at) = waiting_before;
}
result
}
/// Dispatches `id` through the command registry with transactional rollback on failure,
@@ -302,6 +317,19 @@ impl Session {
result
}
/// After a command, formatting Backspace carried over stays only where typing would use it
/// (#6518). One the command left alone is dropped if the caret is elsewhere now (a paste,
/// Find, Go To); one it changed (Bold, a hyperlink's end) is for the caret it left.
fn settle_carried(&mut self, before: Option<(Option<CharProps>, Pos)>) {
if let Some((pending, at)) = before
&& self.pending_at.as_ref() == Some(&at)
&& self.pending != pending
{
self.pending_at = Some(self.sel.focus.clone());
}
self.drop_stale_carried();
}
fn finish_success(&mut self, context: SuccessContext<'_>) {
let SuccessContext {
id,
+11 -3
View File
@@ -23,6 +23,7 @@ impl Session {
self.math = None;
self.sel = Selection::caret(self.doc.start_of(StoryRef::Body));
self.pending = None;
self.pending_at = None;
self.typing = None;
self.also_selected.clear();
self.member = None;
@@ -51,7 +52,7 @@ impl Session {
/// A snapshot to put back with [`Session::restore`], for a caller that runs a command and
/// may want to take it back without a trace (cheap: the document's blocks are shared).
///
/// Covered: `doc`, `sel`, the undo stack (its length, and its oldest steps when it is near
/// Covered: `doc`, `sel`, `pending` with `pending_at`, the undo stack (its length, and its oldest steps when it is near
/// the limit), `redo`, the open typing group, the pending `join_next_undo`,
/// `join_next_equation_edit` and body replacement promises, whether the typing group has a
/// step of its own, and `dirty`. `rev`,
@@ -71,7 +72,8 @@ impl Session {
doc,
sel,
view: _,
pending: _,
pending,
pending_at,
last_highlight: _,
path: _,
file_name: _,
@@ -181,6 +183,8 @@ impl Session {
EditSnapshot {
doc: doc.clone(),
sel: sel.clone(),
pending: pending.clone(),
pending_at: pending_at.clone(),
history_len: history.len(),
evicted: *undo_evicted,
head,
@@ -196,12 +200,14 @@ impl Session {
}
/// Put a snapshot back: the commands run since leave no trace in the document, the
/// selection or undo/redo (undo steps the limit pushed out meanwhile come back). The layout
/// selection, the formatting waiting at the caret or undo/redo (undo steps the limit pushed out meanwhile come back). The layout
/// is recomputed.
pub fn restore(&mut self, snap: EditSnapshot) {
let EditSnapshot {
doc,
sel,
pending,
pending_at,
history_len,
evicted,
head,
@@ -223,6 +229,8 @@ impl Session {
self.autocap = None;
self.doc = doc;
self.sel = sel;
self.pending = pending;
self.pending_at = pending_at;
self.also_selected.clear();
self.member = None;
self.history.truncate(history_len);
+9
View File
@@ -16,6 +16,7 @@ pub struct WindowView {
sel: Selection,
view: ViewState,
pending: Option<CharProps>,
pending_at: Option<Pos>,
goal_x: Option<f32>,
page_hint: usize,
hf_return: Option<Selection>,
@@ -62,6 +63,7 @@ impl Session {
sel: replace(&mut self.sel, Selection::caret(start)),
view: take(&mut self.view),
pending: self.pending.take(),
pending_at: self.pending_at.take(),
goal_x: self.goal_x.take(),
page_hint: take(&mut self.page_hint),
hf_return: self.hf_return.take(),
@@ -86,6 +88,7 @@ impl Session {
sel: self.sel.clone(),
view: self.view.clone(),
pending: self.pending.clone(),
pending_at: self.pending_at.clone(),
goal_x: self.goal_x,
page_hint: self.page_hint,
hf_return: self.hf_return.clone(),
@@ -116,6 +119,7 @@ impl Session {
sel,
view,
pending,
pending_at,
goal_x,
page_hint,
hf_return,
@@ -137,6 +141,7 @@ impl Session {
self.view = view;
self.view.follow_prefs(&self.prefs);
self.pending = pending;
self.pending_at = pending_at;
self.goal_x = goal_x;
self.page_hint = page_hint;
self.column_mode = column_mode;
@@ -161,6 +166,10 @@ impl Session {
self.equation_join_next = false;
self.ime_text_join = None;
self.typing = None;
// Formatting Backspace carried over was for the text it was deleted from (#6518).
if self.pending_at.take().is_some() {
self.pending = None;
}
self.also_selected = Vec::new();
self.column = None;
self.widened = None;
+6 -2
View File
@@ -8,11 +8,15 @@ use wordcraft_layout::{DocLayout, NumeralMode, ViewMode};
/// the undo and redo stacks (also the oldest undo steps the undo limit pushes out meanwhile), the
/// open typing group, the pending
/// [`Session::join_next_undo`]/[`Session::join_next_equation_edit`]/body IME replacement promises,
/// whether the group has a step of its own, and the dirty flag. See
/// [`Session::edit_snapshot`].
/// whether the group has a step of its own, the formatting waiting at the caret (with where
/// Backspace carried it over) and the dirty flag. See [`Session::edit_snapshot`].
pub struct EditSnapshot {
pub(super) doc: Document,
pub(super) sel: Selection,
/// `Session::pending` and `Session::pending_at` then: they go together, so a restored caret
/// gets back the formatting it had, carried by Backspace or set there (#6518).
pub(super) pending: Option<wordcraft_doc::props::CharProps>,
pub(super) pending_at: Option<wordcraft_doc::Pos>,
pub(super) history_len: usize,
/// `Session::undo_evicted` when the snapshot was taken.
pub(super) evicted: u64,
+27
View File
@@ -1675,6 +1675,26 @@ fn paste_merge_formatting_keeps_rtf_deletions() {
assert_eq!(text(&s), "xkept");
}
#[test]
fn paste_merge_formatting_keeps_bold_and_italic_in_a_complex_script_run() {
// #4852 review: with the caret in a run marked `w:cs` (Thai from a WPS or Word file), the
// pasted text takes `cs` too, so its bold and italic must be the complex-script ones as well.
let mut s = s();
run(&mut s, "document.setText", json!({"text": "ภาษาไทย"}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.set", json!({"props": {"cs": true}}));
run(&mut s, "caret.docEnd", json!({}));
run(&mut s, "edit.pasteMerge", json!({"rtf": r"{\rtf1{\b bold}{\i slant}\par}"}));
let p = s.doc.para(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap();
let at = |word: &str| p.props_of_char(p.text.find(word).unwrap() + 1).clone();
let (b, i) = (at("bold"), at("slant"));
assert_eq!((b.cs, b.bold, b.bold_cs), (Some(true), Some(true), Some(true)), "{b:?}");
assert_eq!((i.cs, i.italic, i.italic_cs), (Some(true), Some(true), Some(true)), "{i:?}");
assert_ne!(b.italic, Some(true));
let r = s.doc.styles.resolve_char(None, &b);
assert!(r.bold_cs, "drawn bold as complex script");
}
#[test]
fn pasted_rtf_sections_link_their_headers_to_the_previous() {
// #1378: the RTF's own header part ids mean nothing in this document; a pasted section
@@ -13229,6 +13249,13 @@ fn style_set_keeps_imported_styles_latent_styles_and_defaults() {
let mut s = s();
run(&mut s, "design.styleSet", json!({ "name": "title" }));
assert_eq!(s.doc.styles.get("Title").unwrap().chr.size, Some(36.0));
// #4852 review: the sets that make headings bold or italic do it in both scripts, so a Thai
// heading in a run marked `w:cs` is drawn bold or italic too.
let cs = wordcraft_doc::props::CharProps { cs: Some(true), ..Default::default() };
run(&mut s, "design.styleSet", json!({ "name": "basic" }));
assert!(s.doc.styles.resolve_char(Some("Heading1"), &cs).bold_cs, "basic");
run(&mut s, "design.styleSet", json!({ "name": "casual" }));
assert!(s.doc.styles.resolve_char(Some("Heading2"), &cs).italic_cs, "casual");
}
fn style_size(s: &Session, id: &str) -> f32 {
+35
View File
@@ -156,6 +156,41 @@ fn font_commands_override_inherited_complex_script_properties_explicitly() {
assert_eq!((c.size, c.size_cs, c.bold_cs, c.italic_cs), (Some(12.0), Some(18.0), Some(false), Some(false)));
}
#[test]
fn bold_and_italic_buttons_follow_what_a_complex_script_run_shows() {
// Thai marked `w:cs` with `w:b`/`w:i` and no `w:bCs`/`w:iCs` is drawn plain, so the buttons
// are off and the first click makes it bold and italic.
let mut s = session("ทดสอบ", false);
let p = s.doc.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap();
for r in &mut p.runs {
(r.props.cs, r.props.bold, r.props.italic) = (Some(true), Some(true), Some(true));
}
run(&mut s, "select.all", json!({}));
let state = run(&mut s, "format.state", json!({}));
assert_eq!((state["bold"].as_bool(), state["italic"].as_bool()), (Some(false), Some(false)));
run(&mut s, "format.bold", json!({}));
run(&mut s, "format.italic", json!({}));
let c = s.doc.para(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap().props_of_char(0).clone();
assert_eq!((c.bold_cs, c.italic_cs), (Some(true), Some(true)));
let state = run(&mut s, "format.state", json!({}));
assert_eq!((state["bold"].as_bool(), state["italic"].as_bool()), (Some(true), Some(true)));
// A right-to-left run is drawn with its complex-script values too.
let mut s = session("שלום", true);
let p = s.doc.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap();
for r in &mut p.runs {
(r.props.rtl, r.props.bold, r.props.bold_cs, r.props.italic, r.props.italic_cs) =
(Some(true), Some(true), Some(false), Some(true), Some(false));
}
run(&mut s, "select.all", json!({}));
let state = run(&mut s, "format.state", json!({}));
assert_eq!((state["bold"].as_bool(), state["italic"].as_bool()), (Some(false), Some(false)));
run(&mut s, "format.bold", json!({}));
run(&mut s, "format.italic", json!({}));
let c = s.doc.para(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap().props_of_char(0).clone();
assert_eq!((c.bold, c.bold_cs, c.italic, c.italic_cs), (Some(true), Some(true), Some(true), Some(true)));
}
#[test]
fn arrow_keys_move_visually_in_rtl_text() {
let fa = "سلام دنیا";
+349
View File
@@ -1708,6 +1708,355 @@ fn undoing_bold_at_the_caret_turns_bold_typing_off_again() {
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().props_of_char(0).bold, Some(true));
}
/// `text` with the characters from `from` to `to` bold, the caret at `caret`.
fn with_bold(text: &str, from: usize, to: usize, caret: usize) -> Session {
let mut s = Session::new(wordcraft_doc::Document::from_text(text));
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": from}, "focus": {"block": 0, "off": to}}));
run(&mut s, "format.bold", json!({"value": true}));
run(&mut s, "caret.set", json!({"pos": {"block": 0, "off": caret}}));
s
}
/// Whether the character at `off` of the first paragraph is bold.
fn bold_at(s: &Session, off: usize) -> bool {
s.doc.para_at(&Pos::body(0, 0)).unwrap().props_of_char(off).bold == Some(true)
}
/// #6518: after Backspace, Word types with the deleted character's formatting, not the one to
/// the left of the caret, and the Bold button shows it.
#[test]
fn typing_after_backspace_takes_the_deleted_characters_formatting() {
// "Abc abc", "Abc" bold: Backspace after the plain space, then X is plain.
let mut s = with_bold("Abc abc", 0, 3, 4);
typ(&mut s, "\u{8}");
assert_eq!(s.run("format.state", &json!({})).unwrap()["bold"], json!(false));
typ(&mut s, "X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "AbcXabc");
assert!(!bold_at(&s, 3));
// "abc Abc", "Abc" bold: Backspace after the bold A, then X is bold beside a plain space.
let mut s = with_bold("abc Abc", 4, 7, 5);
typ(&mut s, "\u{8}");
assert_eq!(s.run("format.state", &json!({})).unwrap()["bold"], json!(true));
typ(&mut s, "XY");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "abc XYbc");
assert!(bold_at(&s, 4) && bold_at(&s, 5));
// Several Backspaces: the last character deleted wins ("c", then the plain space).
let mut s = with_bold("Abc abc", 0, 3, 4);
typ(&mut s, "\u{8}\u{8}X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "AbXabc");
assert!(bold_at(&s, 2));
// Inside a word the Bold button shows the deleted character too, not the word: in "Ab c"
// with all but the space bold, Backspace after the space leaves the caret in a bold "Abc".
let mut s = with_bold("Ab c", 0, 2, 3);
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 3}, "focus": {"block": 0, "off": 4}}));
run(&mut s, "format.bold", json!({"value": true}));
run(&mut s, "caret.set", json!({"pos": {"block": 0, "off": 3}}));
typ(&mut s, "\u{8}");
assert_eq!(s.run("format.state", &json!({})).unwrap()["bold"], json!(false));
typ(&mut s, "X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "AbXc");
assert!(!bold_at(&s, 2));
}
/// #6518: the carried formatting goes once the caret moves, and Delete never carries it.
#[test]
fn backspace_formatting_is_dropped_by_a_caret_move_and_delete_does_not_carry() {
let mut s = with_bold("Abc abc", 0, 3, 4);
typ(&mut s, "\u{8}");
run(&mut s, "caret.right", json!({}));
run(&mut s, "caret.left", json!({}));
assert_eq!(s.typing_props().bold, Some(true));
typ(&mut s, "X");
assert!(bold_at(&s, 3));
// Delete after the bold "Abc" removes the plain space: X takes the bold to its left.
let mut s = with_bold("Abc abc", 0, 3, 3);
run(&mut s, "text.delete", json!({}));
typ(&mut s, "X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "AbcXabc");
assert!(bold_at(&s, 3));
// Deleting a plain selection with Delete or Backspace carries nothing either.
for key in ["text.delete", "text.backspace"] {
let mut s = with_bold("Abc abc", 0, 3, 3);
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 3}, "focus": {"block": 0, "off": 5}}));
run(&mut s, key, json!({}));
typ(&mut s, "X");
assert!(bold_at(&s, 3), "{key}");
}
// Undo takes the Backspace back, and with it the carried formatting.
let mut s = with_bold("Abc abc", 0, 3, 4);
typ(&mut s, "\u{8}");
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.sel.focus, Pos::body(0, 4));
assert_eq!(s.pending, None);
}
/// #6518: a Backspace that changes nothing, at the start of the document, keeps formatting waiting
/// at the caret; one that joins paragraphs drops it. Observed in Word for Windows.
#[test]
fn backspace_at_the_document_start_keeps_waiting_formatting() {
// "Abc def", "Abc" bold: Backspace deletes the bold A, the second one does nothing, X is bold.
let mut s = with_bold("Abc def", 0, 3, 1);
typ(&mut s, "\u{8}\u{8}");
assert_eq!(s.run("format.state", &json!({})).unwrap()["bold"], json!(true));
typ(&mut s, "X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "Xbc def");
assert!(bold_at(&s, 0));
// Bold at the caret before plain "abc", then a Backspace that does nothing: X is still bold.
let mut s = Session::new(wordcraft_doc::Document::from_text("abc"));
run(&mut s, "caret.set", json!({"pos": {"block": 0, "off": 0}}));
run(&mut s, "format.bold", json!({"value": true}));
typ(&mut s, "\u{8}X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "Xabc");
assert!(bold_at(&s, 0) && !bold_at(&s, 1));
// "xyz" then bold "Abc": Backspace deletes the bold A, the second joins the paragraphs, and X
// takes the plain z to its left.
let mut s = Session::new(wordcraft_doc::Document::from_text("xyz\nAbc"));
run(&mut s, "select.range", json!({"anchor": {"block": 1, "off": 0}, "focus": {"block": 1, "off": 3}}));
run(&mut s, "format.bold", json!({"value": true}));
run(&mut s, "caret.set", json!({"pos": {"block": 1, "off": 1}}));
typ(&mut s, "\u{8}\u{8}X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "xyzXbc");
assert!(!bold_at(&s, 3) && bold_at(&s, 4));
}
/// #6518: Ctrl+Backspace that deletes nothing, at the start of the document, keeps formatting
/// waiting at the caret, as a plain Backspace there does; one that deletes a word or joins
/// paragraphs drops it. Observed in Word for Windows.
#[test]
fn ctrl_backspace_at_the_document_start_keeps_waiting_formatting() {
// "Ab def", "A" bold: Backspace deletes the bold A, Ctrl+Backspace does nothing, X is bold
// beside a plain "b".
let mut s = with_bold("Ab def", 0, 1, 1);
typ(&mut s, "\u{8}");
run(&mut s, "text.deleteWordBack", json!({}));
assert_eq!(s.run("format.state", &json!({})).unwrap()["bold"], json!(true));
typ(&mut s, "X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "Xb def");
assert!(bold_at(&s, 0) && !bold_at(&s, 1));
// Bold at the caret before plain "abc", then a Ctrl+Backspace that does nothing: X is bold.
let mut s = Session::new(wordcraft_doc::Document::from_text("abc"));
run(&mut s, "caret.set", json!({"pos": {"block": 0, "off": 0}}));
run(&mut s, "format.bold", json!({"value": true}));
run(&mut s, "text.deleteWordBack", json!({}));
typ(&mut s, "X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "Xabc");
assert!(bold_at(&s, 0) && !bold_at(&s, 1));
// "pq xy Ab", "A" bold: Backspace deletes the bold A, Ctrl+Backspace deletes "xy ", X is plain.
let mut s = with_bold("pq xy Ab", 6, 7, 7);
typ(&mut s, "\u{8}");
run(&mut s, "text.deleteWordBack", json!({}));
typ(&mut s, "X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "pq Xb");
assert!(!bold_at(&s, 3));
// "pq" then "Ab", "A" bold: Backspace deletes the bold A, Ctrl+Backspace joins the
// paragraphs, X is plain.
let mut s = Session::new(wordcraft_doc::Document::from_text("pq\nAb"));
run(&mut s, "select.range", json!({"anchor": {"block": 1, "off": 0}, "focus": {"block": 1, "off": 1}}));
run(&mut s, "format.bold", json!({"value": true}));
run(&mut s, "caret.set", json!({"pos": {"block": 1, "off": 1}}));
typ(&mut s, "\u{8}");
run(&mut s, "text.deleteWordBack", json!({}));
typ(&mut s, "X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "pqXb");
assert!(!bold_at(&s, 2));
}
/// #6518 review: what Backspace carries over is for typing where the character was deleted. A
/// paste leaves the next typed text the formatting where it lands, and pasted text never takes it.
#[test]
fn backspace_formatting_is_not_kept_past_a_paste() {
// "hello wrld World", "World" bold: copy it, Backspace the plain r, paste, then ! is bold
// like the pasted text to its left.
let mut s = with_bold("hello wrld World", 11, 16, 0);
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 11}, "focus": {"block": 0, "off": 16}}));
run(&mut s, "edit.copy", json!({}));
run(&mut s, "caret.set", json!({"pos": {"block": 0, "off": 8}}));
typ(&mut s, "\u{8}");
run(&mut s, "edit.paste", json!({}));
typ(&mut s, "!");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "hello wWorld!ld World");
assert!(bold_at(&s, 7) && bold_at(&s, 12), "! takes the pasted bold, not the deleted plain r");
// "ab Cd", "C" bold: Backspace the bold C, paste plain text: it takes the plain space before
// it, and so does ! after it.
let mut s = with_bold("ab Cd", 3, 4, 4);
typ(&mut s, "\u{8}");
run(&mut s, "edit.paste", json!({"text": "zz"}));
typ(&mut s, "!");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "ab zz!d");
assert!((3..6).all(|i| !bold_at(&s, i)), "pasted text and ! are plain");
}
/// #6518 review: Find, Go To and a click elsewhere move the caret without the caret commands;
/// the formatting Backspace carried over stays behind. Observed in Word for Windows: typing over
/// a found word takes that word's formatting, and a Find with no match keeps the carried one.
#[test]
fn backspace_formatting_is_not_kept_past_find_or_go_to() {
// "Xy plain word", "X" bold: Backspace the bold X, Find "word" and type over it: Q is plain.
let mut s = with_bold("Xy plain word", 0, 1, 1);
typ(&mut s, "\u{8}");
run(&mut s, "edit.find", json!({"text": "word"}));
assert_eq!(s.run("format.state", &json!({})).unwrap()["bold"], json!(false));
typ(&mut s, "Q");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "y plain Q");
assert!(!bold_at(&s, 8));
// Go To a paragraph puts a caret before a plain word: Q is plain.
let mut s = Session::new(wordcraft_doc::Document::from_text("Xy plain\nword"));
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 0}, "focus": {"block": 0, "off": 1}}));
run(&mut s, "format.bold", json!({"value": true}));
run(&mut s, "caret.set", json!({"pos": {"block": 0, "off": 1}}));
typ(&mut s, "\u{8}");
run(&mut s, "edit.goto", json!({"paragraph": 2}));
assert_eq!(s.sel, crate::Selection::caret(Pos::body(1, 0)));
typ(&mut s, "Q");
assert_eq!(s.doc.para_at(&Pos::body(1, 0)).unwrap().text, "Qword");
assert_ne!(s.doc.para_at(&Pos::body(1, 0)).unwrap().props_of_char(0).bold, Some(true));
// A caret the front end puts elsewhere itself (a right-click in the text): Q is plain.
let mut s = with_bold("Xy plain word", 0, 1, 1);
typ(&mut s, "\u{8}");
s.sel = crate::Selection::caret(Pos::body(0, 8));
assert_ne!(s.typing_props().bold, Some(true));
typ(&mut s, "Q");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "y plain Qword");
assert!(!bold_at(&s, 8));
// A Find with no match leaves the caret where it was, and the formatting with it: Q is bold.
let mut s = with_bold("Xy plain word", 0, 1, 1);
typ(&mut s, "\u{8}");
run(&mut s, "edit.find", json!({"text": "zzz"}));
typ(&mut s, "Q");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "Qy plain word");
assert!(bold_at(&s, 0));
}
/// #6518 review: a Paste with nothing on the clipboard pastes nothing: the formatting Backspace
/// carried over stays for the typing that follows.
#[test]
fn backspace_formatting_survives_a_paste_of_an_empty_clipboard() {
// "ab Cd", "C" bold: Backspace the bold C, Paste fails, X is bold.
let mut s = with_bold("ab Cd", 3, 4, 4);
typ(&mut s, "\u{8}");
assert!(s.run("edit.paste", &json!({})).is_err(), "the clipboard is empty");
typ(&mut s, "X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "ab Xd");
assert!(bold_at(&s, 3));
// What Paste would insert, asked for on its own: nothing, and the formatting stays.
let mut s = with_bold("ab Cd", 3, 4, 4);
typ(&mut s, "\u{8}");
assert!(crate::cmd::paste::paste_content(&mut s, &json!({})).is_err());
assert_eq!(s.waiting().and_then(|p| p.bold), Some(true));
}
/// #6518 review: a front end that moves the caret itself (a right-click) goes through
/// `Session::set_selection`: once the caret has been elsewhere, putting it back where the
/// character was deleted does not bring the carried formatting back.
#[test]
fn backspace_formatting_is_not_kept_past_a_direct_caret_move_and_back() {
// "Xy plain word", "X" bold: Backspace the bold X, the caret goes to "word" and back: Q is plain.
let mut s = with_bold("Xy plain word", 0, 1, 1);
typ(&mut s, "\u{8}");
s.set_selection(crate::Selection::caret(Pos::body(0, 8)));
s.set_selection(crate::Selection::caret(Pos::body(0, 0)));
assert_ne!(s.typing_props().bold, Some(true));
typ(&mut s, "Q");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "Qy plain word");
assert!(!bold_at(&s, 0));
// Put where it already is, the caret keeps it: Q is bold.
let mut s = with_bold("Xy plain word", 0, 1, 1);
typ(&mut s, "\u{8}");
s.set_selection(crate::Selection::caret(Pos::body(0, 0)));
typ(&mut s, "Q");
assert!(bold_at(&s, 0));
}
/// #6518 review: a command that fails leaves the formatting waiting at the caret as it was: a
/// Backspace refused by a content control locked against editing keeps what an earlier Backspace
/// carried over, and Bold picked at the caret.
#[test]
fn a_refused_backspace_keeps_the_formatting_waiting_at_the_caret() {
let w = wordcraft_doc::para::OBJ.len_utf8();
// "abC" in a content control, "C" bold.
let mut s = Session::new(wordcraft_doc::Document::from_text("abC"));
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 2}, "focus": {"block": 0, "off": 3}}));
run(&mut s, "format.bold", json!({"value": true}));
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 0}, "focus": {"block": 0, "off": 3}}));
run(&mut s, "developer.richText", json!({"tag": "ctl"}));
let lock = |s: &mut Session| run(s, "developer.properties", json!({"control": "ctl", "lockEdit": true}));
// Backspace the bold C, lock the control: the next Backspace is refused, and X is still bold.
run(&mut s, "caret.set", json!({"pos": {"block": 0, "off": w + 3}}));
typ(&mut s, "\u{8}");
lock(&mut s);
assert_eq!(s.waiting().and_then(|p| p.bold), Some(true));
let before = s.doc.clone();
assert!(s.run("text.backspace", &json!({})).is_err(), "the control is locked");
assert_eq!(s.doc, before);
assert_eq!(s.sel, crate::Selection::caret(Pos::body(0, w + 2)));
assert_eq!(s.waiting().and_then(|p| p.bold), Some(true), "the refused Backspace keeps the carried bold");
// Bold picked at the caret, then a refused Backspace: still bold.
run(&mut s, "caret.set", json!({"pos": {"block": 0, "off": w + 1}}));
s.pending = Some(wordcraft_doc::props::CharProps { bold: Some(true), ..Default::default() });
assert!(s.run("text.backspace", &json!({})).is_err(), "the control is locked");
assert_eq!(s.waiting().and_then(|p| p.bold), Some(true), "the refused Backspace keeps the Bold picked at the caret");
}
/// #6518: the carried formatting goes on with the typing that follows, and Undo of that typing
/// brings it back where it was, so typing again there takes it once more.
#[test]
fn backspace_formatting_follows_typing_and_comes_back_with_undo() {
// "ab Cd", "C" bold: Backspace the bold C, then Y and X are both bold (Word).
let mut s = with_bold("ab Cd", 3, 4, 4);
typ(&mut s, "\u{8}YX");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "ab YXd");
assert!(bold_at(&s, 3) && bold_at(&s, 4) && !bold_at(&s, 5));
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "ab d");
typ(&mut s, "Z");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "ab Zd");
assert!(bold_at(&s, 3));
}
/// #6518: with Track Changes on, Backspace leaves the character in place marked deleted, and text
/// typed next still takes its formatting (a tracked insertion, never marked deleted); moving the
/// caret away and back drops it. Backspace over the author's own tracked insertion, which removes
/// it, carries it too. Observed in Word for Windows.
#[test]
fn tracked_backspace_carries_the_deleted_characters_formatting() {
// "xy Abc", "Abc" bold: Backspace after the bold A, then X is bold beside a plain space.
let mut s = with_bold("xy Abc", 3, 6, 4);
run(&mut s, "review.trackChanges", json!({"value": true}));
typ(&mut s, "\u{8}");
assert_eq!(s.sel, crate::Selection::caret(Pos::body(0, 3)));
assert_eq!(s.run("format.state", &json!({})).unwrap()["bold"], json!(true));
typ(&mut s, "X");
let p = s.doc.para_at(&Pos::body(0, 0)).unwrap();
assert_eq!(p.text, "xy XAbc", "the A stays, marked deleted");
let x = p.props_of_char(3);
assert!(x.bold == Some(true) && x.ins.is_some() && x.del.is_none(), "X is a bold tracked insertion: {x:?}");
assert!(p.props_of_char(4).del.is_some() && p.props_of_char(5).del.is_none());
// Moving the caret right and back after the Backspace drops it: X is plain.
let mut s = with_bold("xy Abc", 3, 6, 4);
run(&mut s, "review.trackChanges", json!({"value": true}));
typ(&mut s, "\u{8}");
run(&mut s, "caret.right", json!({}));
run(&mut s, "caret.left", json!({}));
assert_eq!(s.sel, crate::Selection::caret(Pos::body(0, 3)));
typ(&mut s, "X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "xy XAbc");
assert!(!bold_at(&s, 3));
// A bold A this author typed with Track Changes on: Backspace removes it, X is still bold.
let mut s = Session::new(wordcraft_doc::Document::from_text("xy "));
run(&mut s, "review.trackChanges", json!({"value": true}));
run(&mut s, "caret.set", json!({"pos": {"block": 0, "off": 3}}));
run(&mut s, "format.bold", json!({"value": true}));
typ(&mut s, "A");
run(&mut s, "caret.set", json!({"pos": {"block": 0, "off": 4}}));
typ(&mut s, "\u{8}");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "xy ");
typ(&mut s, "X");
let p = s.doc.para_at(&Pos::body(0, 0)).unwrap();
assert_eq!(p.text, "xy X");
let x = p.props_of_char(3);
assert!(x.bold == Some(true) && x.ins.is_some() && x.del.is_none(), "X is a bold tracked insertion: {x:?}");
}
/// Myanmar (#604): typed in memory order (consonant, medial, then the prevowel ေ that is drawn
/// before it), the caret steps over whole syllables and Backspace removes one sign at a time.
#[test]
+364
View File
@@ -0,0 +1,364 @@
//! Screen readers: what a formatting shortcut did, said as Word says it ("Bold On", "Center Off",
//! "Font 14pt"). Word raises these itself; here they go through a polite live region, which
//! screen readers read when it appears.
use egui::accesskit::{Live, Role};
use serde_json::Value;
use wordcraft_doc::Align;
use crate::WordApp;
/// How long an announcement stays in the tree: a screen reader reads its name after the
/// live-region event, so it must still be there then.
const SHOWN_MS: f64 = 3000.0;
/// An announcement for screen readers. Each one gets its own node, numbered: a live region is
/// read when it appears or its text changes, so the same text twice needs a new node.
#[derive(Clone, Debug)]
pub(crate) struct Announcement {
text: String,
serial: u64,
at: f64,
}
/// Announces what the shortcut for command `id` did, once it has run; nothing for a command Word
/// doesn't announce.
pub(crate) fn after_shortcut(app: &mut WordApp, id: &str, ctx: &egui::Context) {
let Some(text) = describe(app, id) else { return };
let serial = app.announcement.as_ref().map_or(0, |a| a.serial.wrapping_add(1));
app.announcement = Some(Announcement { text, serial, at: ctx.input(|i| i.time) * 1000.0 });
}
/// The words for what command `id` did: the command's name and whether its formatting is now on,
/// or the font size the selection now has.
fn describe(app: &WordApp, id: &str) -> Option<String> {
let on_off = |name: &str, on: bool| format!("{name} {}", if on { tl!("On") } else { tl!("Off") });
let state = || wordcraft_engine::cmd::format::state(&app.session);
let character = match id {
"format.bold" => Some(("bold", tl!("Bold"))),
"format.italic" => Some(("italic", tl!("Italic"))),
"format.underline" => Some(("underline", tl!("Underline"))),
"format.subscript" => Some(("subscript", tl!("Subscript"))),
"format.superscript" => Some(("superscript", tl!("Superscript"))),
_ => None,
};
if let Some((key, name)) = character {
return Some(on_off(name, state().get(key).and_then(Value::as_bool).unwrap_or(false)));
}
let alignment = match id {
"para.alignLeft" => Some((Align::Left, tl!("Align Left"))),
"para.alignCenter" => Some((Align::Center, tl!("Center"))),
"para.alignRight" => Some((Align::Right, tl!("Align Right"))),
"para.justify" => Some((Align::Justify, tl!("Justify"))),
_ => None,
};
if let Some((want, name)) = alignment {
// As the ribbon's buttons show it: Center twice centres, then goes back to the left. Read
// in a paragraph the command formatted: a selection ending at the next paragraph's start
// leaves that one out (#418).
let s = &app.session;
let formatted = wordcraft_engine::cmd::selected_paths(s);
let path = if formatted.contains(&s.sel.focus.path) { Some(s.sel.focus.path.clone()) } else { formatted.last().cloned() };
let at = path.map(|path| wordcraft_doc::Pos { path, off: 0, ..s.sel.focus.clone() });
let align = at.and_then(|at| s.doc.para_at(&at)).map(|p| s.doc.styles.resolve_para(&p.props)).map(|r| r.align.visual(r.bidi));
return Some(on_off(name, align == Some(want)));
}
if matches!(id, "format.growFont" | "format.shrinkFont" | "format.growFont1" | "format.shrinkFont1") {
// A selection of mixed sizes has no one size to say.
let size = state().get("size").and_then(Value::as_f64)?;
let unit = wordcraft_geom::Unit::Points;
let number = unit.number(size as f32, app.session.region().decimal());
return Some(format!("{} {number}{}", tl!("Font"), crate::options::unit_suffix(unit)));
}
None
}
/// Puts the latest announcement in the tree, as a polite live region, while it is fresh.
pub(crate) fn expose(app: &WordApp, ctx: &egui::Context) {
let Some(a) = &app.announcement else { return };
let age = ctx.input(|i| i.time) * 1000.0 - a.at;
if !(0.0..SHOWN_MS).contains(&age) {
return;
}
ctx.accesskit_node_builder(egui::Id::unique(("announcement", a.serial)), |node| {
// A label's text is its value: that is the name screen readers read (UI Automation's
// live-region event goes only to a node with a name).
node.set_role(Role::Label);
node.set_live(Live::Polite);
node.set_value(a.text.clone());
});
// A frame when it's due to go, so it leaves the tree even while nothing else happens.
ctx.request_repaint_after(std::time::Duration::from_secs_f64((SHOWN_MS - age) / 1000.0));
}
#[cfg(test)]
mod tests {
use egui::accesskit::{Live, Role};
use egui::{Key, Modifiers};
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::json;
use crate::WordApp;
/// An announcement belongs to the window whose shortcut made it, as its status message does:
/// another window drawn within its three seconds doesn't put it in its own tree.
#[test]
fn an_announcement_stays_with_its_window() {
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), crate::Services::default());
app.announcement = Some(super::Announcement { text: "Bold On".into(), serial: 0, at: 0.0 });
let mut other = crate::window_ui::WindowUi::new(app.session.document_id());
app.swap_window(&mut other);
assert!(app.announcement.is_none(), "the other window has nothing to say");
app.swap_window(&mut other);
assert_eq!(app.announcement.as_ref().map(|a| a.text.as_str()), Some("Bold On"), "it is back with its window");
}
fn harness(text: &str) -> egui_kittest::Harness<'static, WordApp> {
let app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text(text)), crate::Services::default());
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
app,
);
let ctx = h.ctx.clone();
h.state_mut().canvas.focus_page(&ctx);
crate::test_harness::frames(&mut h, 6);
assert!(h.state().canvas.focused(&ctx), "the page has the keyboard");
h.state_mut().session.sel = wordcraft_engine::Selection { anchor: wordcraft_doc::Pos::body(0, 0), focus: wordcraft_doc::Pos::body(0, 8) };
crate::test_harness::frames(&mut h, 2);
h
}
/// The live region's text and node (its id, written out), if one is in the tree. The text is
/// the label's value, which is its name to screen readers.
fn heard(h: &egui_kittest::Harness<'_, WordApp>) -> Option<(String, String)> {
let node = h.query_by(|n| n.role() == Role::Label && n.data().live() == Some(Live::Polite))?;
let n = node.accesskit_node();
assert!(n.label_comes_from_value(), "a label, named by its value");
Some((n.value().unwrap_or_default(), format!("{:?}", n.id())))
}
fn press(h: &mut egui_kittest::Harness<'_, WordApp>, m: Modifiers, key: Key) -> Option<(String, String)> {
h.key_press_modifiers(m, key);
crate::test_harness::frames(h, 2);
heard(h)
}
/// Ctrl+B, Ctrl+I, Ctrl+U and the alignment keys say what they did, as Word does ("Bold On",
/// then "Bold Off"), each time in a new live region, so the same words twice are heard twice.
#[test]
fn formatting_shortcuts_say_what_they_did() {
let mut h = harness("Lanterns glow");
assert_eq!(heard(&h), None, "nothing to say before a shortcut");
let (text, first) = press(&mut h, Modifiers::COMMAND, Key::B).expect("Ctrl+B is announced");
assert_eq!(text, "Bold On");
let (text, second) = press(&mut h, Modifiers::COMMAND, Key::B).expect("again");
assert_eq!(text, "Bold Off");
assert_ne!(first, second, "each announcement is a new live region");
for (key, said) in [
(Key::I, "Italic On"),
(Key::U, "Underline On"),
(Key::E, "Center On"),
(Key::E, "Center Off"),
(Key::R, "Align Right On"),
(Key::J, "Justify On"),
(Key::L, "Align Left On"),
] {
assert_eq!(press(&mut h, Modifiers::COMMAND, key).map(|(t, _)| t).as_deref(), Some(said), "{key:?}");
}
let (_, before) = heard(&h).expect("the last one");
let (text, again) = press(&mut h, Modifiers::COMMAND, Key::L).expect("Ctrl+L twice");
assert_eq!(text, "Align Left On", "left alignment stays");
assert_ne!(before, again, "the same words twice are a new live region, so they are heard again");
let grown = press(&mut h, Modifiers::COMMAND | Modifiers::SHIFT, Key::Period).map(|(t, _)| t).expect("Ctrl+Shift+. is announced");
assert!(grown.starts_with("Font ") && grown.ends_with(" pt"), "{grown}");
}
/// Only shortcuts are announced: a ribbon button says its own state, and a command that isn't
/// formatting says nothing. An announcement leaves the tree after three seconds.
#[test]
fn only_formatting_shortcuts_are_announced_for_a_while() {
let mut h = harness("Lanterns glow");
h.state_mut().run("format.bold", json!({})).unwrap();
crate::test_harness::frames(&mut h, 2);
assert_eq!(heard(&h), None, "a command run another way isn't announced");
assert_eq!(press(&mut h, Modifiers::COMMAND, Key::Z), None, "Undo isn't announced");
assert!(press(&mut h, Modifiers::COMMAND, Key::I).is_some());
if let Some(a) = &mut h.state_mut().announcement {
a.at -= super::SHOWN_MS;
}
crate::test_harness::frames(&mut h, 2);
assert_eq!(heard(&h), None, "gone after three seconds");
}
/// A selection ending at the next paragraph's start (Shift+Down from a paragraph's start)
/// formats only the paragraph it covers, as in Word: that is the one the announcement says.
#[test]
fn alignment_is_said_for_the_paragraph_the_shortcut_formatted() {
let mut h = harness("Lanterns glow\nRivers run");
h.state_mut().session.sel = wordcraft_engine::Selection { anchor: wordcraft_doc::Pos::body(0, 0), focus: wordcraft_doc::Pos::body(1, 0) };
crate::test_harness::frames(&mut h, 2);
assert_eq!(press(&mut h, Modifiers::COMMAND, Key::E).map(|(t, _)| t).as_deref(), Some("Center On"));
let align =
|h: &egui_kittest::Harness<'_, WordApp>, i| h.state().session.doc.para_at(&wordcraft_doc::Pos::body(i, 0)).and_then(|p| p.props.align);
assert_eq!((align(&h, 0), align(&h, 1)), (Some(wordcraft_doc::Align::Center), None), "only the first paragraph is centred");
assert_eq!(press(&mut h, Modifiers::COMMAND, Key::E).map(|(t, _)| t).as_deref(), Some("Center Off"));
}
/// The shortcut runs after the announcement's place in the frame, so the announcement goes in
/// the next frame's tree: a key asks egui for that frame itself.
#[test]
fn the_announcement_is_in_the_frame_after_the_key() {
let mut h = harness("Lanterns glow");
// The key down alone, in one frame (`key_press_modifiers` gives each event a frame).
h.input_mut().events.push(egui::Event::Key { key: Key::B, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::COMMAND });
crate::test_harness::frame(&mut h);
assert_eq!(heard(&h), None, "the key's own frame built its tree before the shortcut ran");
assert!(h.ctx.has_requested_repaint(), "the key asked for another frame");
crate::test_harness::frame(&mut h);
assert_eq!(heard(&h).map(|(t, _)| t).as_deref(), Some("Bold On"));
}
/// Each formatting shortcut says its own words, read from the formatting after it ran: the
/// format's name and On or Off for Ctrl+B, I, U, = (Subscript) and Shift+= (Superscript), the
/// alignment's name for Ctrl+E, R, J and L, and the size the selection now has for
/// Ctrl+Shift+. and , (Grow and Shrink Font) and Ctrl+] and [ (by 1 pt). A selection of mixed
/// sizes has no one size to say, so nothing is said.
#[test]
fn every_formatting_shortcut_says_its_own_words() {
let mut h = harness("Lanterns glow");
h.state_mut().run("format.size", json!({"size": 12})).unwrap();
crate::test_harness::frames(&mut h, 2);
let (cmd, shift) = (Modifiers::COMMAND, Modifiers::COMMAND | Modifiers::SHIFT);
for (m, key, said) in [
(cmd, Key::B, "Bold On"),
(cmd, Key::B, "Bold Off"),
(cmd, Key::I, "Italic On"),
(cmd, Key::I, "Italic Off"),
(cmd, Key::U, "Underline On"),
(cmd, Key::U, "Underline Off"),
(cmd, Key::Equals, "Subscript On"),
(cmd, Key::Equals, "Subscript Off"),
(shift, Key::Equals, "Superscript On"),
(shift, Key::Equals, "Superscript Off"),
(cmd, Key::E, "Center On"),
(cmd, Key::R, "Align Right On"),
(cmd, Key::J, "Justify On"),
(cmd, Key::L, "Align Left On"),
(shift, Key::Period, "Font 14 pt"),
(shift, Key::Comma, "Font 12 pt"),
(cmd, Key::CloseBracket, "Font 13 pt"),
(cmd, Key::OpenBracket, "Font 12 pt"),
] {
assert_eq!(press(&mut h, m, key).map(|(t, _)| t).as_deref(), Some(said), "{m:?} {key:?}");
}
let mut h = harness("Lanterns glow");
let sizes = [(0, 8, 12.0), (8, 13, 16.0)];
for (from, to, size) in sizes {
h.state_mut().session.sel =
wordcraft_engine::Selection { anchor: wordcraft_doc::Pos::body(0, from), focus: wordcraft_doc::Pos::body(0, to) };
h.state_mut().run("format.size", json!({"size": size})).unwrap();
}
h.state_mut().session.sel = wordcraft_engine::Selection { anchor: wordcraft_doc::Pos::body(0, 0), focus: wordcraft_doc::Pos::body(0, 13) };
crate::test_harness::frames(&mut h, 2);
assert_eq!(press(&mut h, shift, Key::Period), None, "mixed sizes: nothing to say");
assert!(h.state().announcement.is_none(), "and nothing waits to be said");
}
/// The words are looked up in the interface catalogs, so each language says its own.
#[test]
fn the_words_go_through_the_interface_catalogs() {
let mut h = harness("Lanterns glow");
// These delimiters mark translations in the synthetic locale and are absent from some test fonts.
h.ctx.add_glyph_rasterizer(egui::GlyphRasterizer::new("wordcraft::announce::pseudo_markers", |request| {
matches!(request.cluster, "⟦" | "⟧").then(|| egui::RasterizedGlyph {
bitmap: egui::GlyphBitmap {
image: egui::ColorImage::new([1, 1], vec![egui::Color32::WHITE]),
offset_px: egui::Vec2::ZERO,
is_color: false,
},
advance_px: request.font_size_px.max(1.0),
})
}));
h.state_mut().ui.language = "pseudo".into();
let said = press(&mut h, Modifiers::COMMAND, Key::B).map(|(t, _)| t).unwrap_or_default();
crate::i18n::apply_language(crate::i18n::Lang::EN);
assert!(
said.split_whitespace().all(|word| word.starts_with('⟦') && word.ends_with('⟧')) && said.contains('⟦'),
"every word is marked: {said:?}"
);
}
/// Ten presses in a burst, one per frame or all in one frame (a held key, or keys typed
/// faster than frames), leave one announcement at a time, the latest, in one live region:
/// each replaces the last (`WordApp::announcement` holds one), so nothing queues up.
#[test]
fn a_burst_of_ten_presses_leaves_one_announcement_the_latest() {
let live =
|h: &egui_kittest::Harness<'_, WordApp>| h.query_all_by(|n| n.role() == Role::Label && n.data().live() == Some(Live::Polite)).count();
let mut h = harness("Lanterns glow");
let mut nodes = std::collections::HashSet::new();
for i in 0..10 {
let (text, node) = press(&mut h, Modifiers::COMMAND, Key::B).expect("each press is announced");
assert_eq!(text, if i % 2 == 0 { "Bold On" } else { "Bold Off" }, "press {i}");
assert_eq!(live(&h), 1, "press {i}: one live region in the tree");
nodes.insert(node);
}
assert_eq!(nodes.len(), 10, "each press a new node, so each is heard");
let mut h = harness("Lanterns glow");
let key = |pressed| egui::Event::Key { key: Key::B, physical_key: None, pressed, repeat: false, modifiers: Modifiers::COMMAND };
for _ in 0..10 {
h.input_mut().events.extend([key(true), key(false)]);
}
crate::test_harness::frames(&mut h, 2);
let bold = wordcraft_engine::cmd::format::state(&h.state().session).get("bold").and_then(serde_json::Value::as_bool);
assert_eq!(bold, Some(false), "ten Ctrl+B in one frame: bold on and off five times");
assert_eq!(live(&h), 1, "one live region in the tree");
assert_eq!(heard(&h).map(|(t, _)| t).as_deref(), Some("Bold Off"), "the latest is said");
}
/// The words go through the interface's catalogs (`tl!`), as the ribbon's labels do: a
/// translated interface says them in its language. Checked with a fixture language and, when
/// the craft-i18n catalogs are embedded (`CRAFT_I18N_DIR`), Turkish and Simplified Chinese.
#[test]
fn the_announcements_are_in_the_interface_language() {
let said = |app: &mut WordApp, id: &str| {
app.run(id, json!({})).unwrap();
super::describe(app, id)
};
let app = || {
let mut app =
WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("Lanterns glow")), crate::Services::default());
app.session.sel = wordcraft_engine::Selection { anchor: wordcraft_doc::Pos::body(0, 0), focus: wordcraft_doc::Pos::body(0, 8) };
app.run("format.size", json!({"size": 12})).unwrap();
app
};
let mut a = app();
crate::i18n::apply_language(crate::i18n::fixture_lang(
"x-fixture",
"\tBold\tBold-FX\n\tOn\tOn-FX\n\tOff\tOff-FX\n\tCenter\tCenter-FX\n\tFont\tFont-FX\n\tpt\tpt-FX\n",
));
assert_eq!(said(&mut a, "format.bold").as_deref(), Some("Bold-FX On-FX"));
assert_eq!(said(&mut a, "format.bold").as_deref(), Some("Bold-FX Off-FX"));
assert_eq!(said(&mut a, "para.alignCenter").as_deref(), Some("Center-FX On-FX"));
assert_eq!(said(&mut a, "format.growFont").as_deref(), Some("Font-FX 14 pt-FX"));
// The catalogs' own words: craft-i18n's `common.tsv` and `wordcraft.tsv` rows.
if crate::i18n::catalogs_embedded() {
for (code, bold, center, font) in
[("tr", "Kalın Açık", "Ortala Açık", "Yazı Tipi 14 pt"), ("zh-hans", "加粗 开", "居中 开", "字体 14 磅")]
{
let mut a = app();
crate::i18n::apply_language(crate::i18n::Lang::from_code(code).expect("an interface language"));
assert_eq!(said(&mut a, "format.bold").as_deref(), Some(bold), "{code}");
assert_eq!(said(&mut a, "para.alignCenter").as_deref(), Some(center), "{code}");
assert_eq!(said(&mut a, "format.growFont").as_deref(), Some(font), "{code}");
}
}
crate::i18n::apply_language(crate::i18n::Lang::EN);
}
}
+2
View File
@@ -53,6 +53,7 @@ impl WordApp {
restrict,
spelling_review,
status,
announcement,
previews,
change_picture_target,
recipient_list_pending,
@@ -137,6 +138,7 @@ impl WordApp {
restrict,
spelling_review,
status,
announcement,
previews,
change_picture_target,
recipient_list_pending,
+4 -1
View File
@@ -123,7 +123,7 @@ impl WordApp {
for (id, label) in GATED_UI_COMMANDS {
defs.push(CommandDef::new(CommandRef::new(*id), tl!(*label), Scope::app()));
}
// Word's Alt chords (Alt+Q, Alt+F7, Ctrl+Alt+1…) fire while the person types in the page:
// Word's Alt chords (Alt+Q, Alt+F7, Ctrl+Alt+1…) fire while the person types in the page:
// plain keys type, and every modified chord is offered to the keymap first.
match AppCatalog::new(defs, generation) {
Ok(catalog) => {
@@ -204,6 +204,9 @@ impl WordApp {
self.edits = host;
}
let result = if fired.source == FireSource::Automation { self.execute(id, params) } else { self.run(id, params) };
if from_key && result.is_ok() {
crate::announce::after_shortcut(self, id, ctx);
}
if let Err(error) = result {
log::debug!("command {id}: {error}");
}
+1 -1
View File
@@ -674,7 +674,7 @@ impl WordApp {
let name = file.path.as_ref().map(|p| p.to_string_lossy().to_string()).unwrap_or_else(|| file.name.clone());
let lower = name.to_ascii_lowercase();
let data = file.bytes.as_ref().map(|b| wordcraft_engine::cmd::insert::base64_encode(b.as_ref()));
let img = [".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".wmf", ".emf"].iter().any(|e| lower.ends_with(e));
let img = file_dialogs::is_picture_name(&name);
// Any recipient file ends the pending picker request, so a later .txt drop opens normally.
let asked = std::mem::take(&mut self.recipient_list_pending);
let list = lower.ends_with(".csv") || lower.ends_with(".tsv") || (lower.ends_with(".txt") && asked);
+1
View File
@@ -75,6 +75,7 @@ impl WordApp {
/// handed in as values and read back after, so no body reads a stale copy. Returns the
/// shell's regions; a window another command swapped in mid-draw returns none.
pub(super) fn paint_window(&mut self, ui: &mut egui::Ui) -> ShellRegions {
crate::announce::expose(self, ui.ctx());
let window = self.windows.shown();
let stale = |app: &WordApp| app.windows.shown() != window;
let mode = self.screen_mode();
+2 -2
View File
@@ -22,7 +22,7 @@ impl WordApp {
let Some(off) = end.off.checked_sub(wordcraft_doc::para::OBJ.len_utf8()) else { return };
let start = wordcraft_doc::Pos { off, ..end.clone() };
if self.session.doc.para_at(&start).and_then(|p| p.object_at(off)).is_some_and(|o| o.is_drawing()) {
self.session.sel = wordcraft_engine::Selection { anchor: start, focus: end };
self.session.set_selection(wordcraft_engine::Selection { anchor: start, focus: end });
}
}
@@ -38,7 +38,7 @@ impl WordApp {
/// arrive in one drop, put the caret after the picture placed by the previous file (#1592).
pub(super) fn caret_after_placed_picture(&mut self, placed: bool) {
if placed {
self.session.sel.anchor = self.session.sel.focus.clone();
self.session.set_selection(wordcraft_engine::Selection::caret(self.session.sel.focus.clone()));
}
}
+1 -1
View File
@@ -76,7 +76,7 @@ fn apply(app: &mut WordApp, cards: &[Card], edit: CommentEdit) {
_ => None,
});
if let Some(pos) = pos {
app.session.sel = wordcraft_engine::Selection::caret(pos);
app.session.set_selection(wordcraft_engine::Selection::caret(pos));
}
}
CommentEdit::Edit { thread, index, text, .. } => {
+1 -1
View File
@@ -154,7 +154,7 @@ fn rows(app: &mut WordApp, ui: &mut Ui) {
let (a, b) = app.session.sel.ordered();
let trimmed = app.session.doc.para_at(&a).and_then(|p| p.text.get(a.off..b.off)).map(|t| t.trim_end().len()).unwrap_or(0);
let end = wordcraft_doc::Pos { off: a.off + trimmed, ..b };
app.session.sel = wordcraft_engine::Selection { anchor: a, focus: end };
app.session.set_selection(wordcraft_engine::Selection { anchor: a, focus: end });
let _ = app.run("text.insert", json!({"text": w, "raw": true}));
}
}
+8 -8
View File
@@ -304,13 +304,13 @@ pub(crate) fn handle_secondary_selection(app: &mut WordApp, body: &PageBody<'_>,
return;
}
if let Some(pos) = layout.hit(page, x, y, app.session.sel.focus.story) {
app.session.sel = wordcraft_engine::Selection::caret(pos);
app.session.set_selection(wordcraft_engine::Selection::caret(pos));
app.session.page_hint = page;
}
}
match layout.equation_hit(page, x, y, app.session.sel.focus.story) {
Some((pos, inner)) => {
app.session.sel = wordcraft_engine::Selection::caret(pos);
app.session.set_selection(wordcraft_engine::Selection::caret(pos));
let _ = app.run("equation.edit", json!({"pos": serde_json::to_value(&inner).unwrap_or_default()}));
return;
}
@@ -334,7 +334,7 @@ pub(crate) fn handle_secondary_selection(app: &mut WordApp, body: &PageBody<'_>,
}
}
if let Some(pos) = layout.hit(page, x, y, app.session.sel.focus.story) {
app.session.sel = wordcraft_engine::Selection::caret(pos);
app.session.set_selection(wordcraft_engine::Selection::caret(pos));
app.session.page_hint = page;
}
}
@@ -372,7 +372,7 @@ fn handle_primary_press(
if app.run(id, json!({ "page": page })).is_ok() {
let to = app.session.sel.focus.story;
if let Some(pos) = app.session.layout().hit(page, x, y, to) {
app.session.sel = wordcraft_engine::Selection::caret(pos);
app.session.set_selection(wordcraft_engine::Selection::caret(pos));
}
app.session.page_hint = page;
}
@@ -388,7 +388,7 @@ fn handle_primary_press(
if !mods.shift
&& let Some((at, inner)) = layout.equation_hit(page, x, y, story)
{
app.session.sel = wordcraft_engine::Selection::caret(at);
app.session.set_selection(wordcraft_engine::Selection::caret(at));
let _ = app.run("equation.edit", json!({"pos": serde_json::to_value(&inner).unwrap_or_default()}));
app.session.page_hint = page;
return true;
@@ -521,14 +521,14 @@ fn handle_completed_click(app: &mut WordApp, pointer: &PagePointer<'_>) -> bool
if app.run(id, json!({ "page": page })).is_ok()
&& let Some(pos) = app.session.layout().hit(page, x, y, app.session.sel.focus.story)
{
app.session.sel = wordcraft_engine::Selection::caret(pos);
app.session.set_selection(wordcraft_engine::Selection::caret(pos));
}
return true;
}
if matches!(story, StoryRef::Part(_)) && !in_text_box(app) && hf_zone.is_none() {
let _ = app.run("insert.closeHeader", json!({}));
if let Some(pos) = layout.hit(page, x, y, StoryRef::Body) {
app.session.sel = wordcraft_engine::Selection::caret(pos);
app.session.set_selection(wordcraft_engine::Selection::caret(pos));
}
return true;
}
@@ -536,7 +536,7 @@ fn handle_completed_click(app: &mut WordApp, pointer: &PagePointer<'_>) -> bool
if let Some(pos) = layout.hit(page, x, y, story)
&& let Some(field) = field_showing_code(app, &pos)
{
app.session.sel = wordcraft_engine::Selection::caret(field);
app.session.set_selection(wordcraft_engine::Selection::caret(field));
let _ = app.run("fields.setCode", json!({}));
return true;
}
+7 -3
View File
@@ -303,7 +303,7 @@ fn swatch_table(
current: Option<Rgb>,
) -> (Option<Rgb>, craft::behavior::Preview<Rgb>, egui::Response) {
use craft::behavior::Preview;
let swatches: Vec<(Label, Srgba)> = colors.iter().map(|c| (Label::from(c.hex()), srgba(*c))).collect();
let swatches: Vec<(Label, Srgba)> = colors.iter().map(|c| (Label::from(format!("#{}", c.hex())), srgba(*c))).collect();
let out = SwatchTable::new(name.to_string(), &swatches)
.per_row(per_row)
.tips(true)
@@ -640,7 +640,9 @@ pub fn color_field(ui: &mut Ui, label: &Label, value: &mut String, empty: &Color
),
};
let icon = shown.map_or_else(IconSpec::empty_swatch, IconSpec::swatch);
SplitButton::<NoValue>::body(text, |ui: &mut Ui, cx: &mut BodyCx<'_>| {
let spoken_value = current.map_or_else(|| text.as_str().to_string(), |c| format!("#{}", c.hex()));
let spoken = format!("{} {spoken_value}", label.as_str());
let field = SplitButton::<NoValue>::body(text, |ui: &mut Ui, cx: &mut BodyCx<'_>| {
let empty_label = match empty {
ColorFieldEmpty::NoColor => Label::from(tl!("No Color").to_string()),
ColorFieldEmpty::Automatic { label, .. } => label.clone(),
@@ -664,9 +666,11 @@ pub fn color_field(ui: &mut Ui, label: &Label, value: &mut String, empty: &Color
cx.request_close();
}
})
.arrow_label(label.clone())
.arrow_label(spoken.clone())
.icon(icon)
.show(ui);
// The framework keeps the short visible value; both parts say the field and its value.
ui.ctx().accesskit_node_builder(field.response.id, |node| node.set_label(spoken));
resp
}
+91
View File
@@ -1691,3 +1691,94 @@ fn font_dialog_effects_stand_two_to_a_line_and_kerning_on_one() {
let size = h.query_all_by_label("Points and above").map(|node| node.rect()).min_by(|a, b| a.min.x.total_cmp(&b.min.x)).expect("the kerning size");
assert!((kern.center().y - size.center().y).abs() < 4.0 && kern.max.x <= size.min.x, "the kerning size is on the check box's line");
}
/// #5057: keep the accessibility contract when dialogs move onto the framework.
#[test]
fn dialogs_their_tabs_and_colour_fields_say_what_they_are() {
use egui::accesskit::Role;
let mut app = app_with("Lanterns");
// The framework palette lists the document theme; use a known colour rather than its default.
app.session.doc.settings.theme_colors = vec![wordcraft_doc::Rgb(0xC0, 0, 0)];
let mut h = app_harness(app);
open_named(&mut h, "paragraph", json!({}));
assert!(h.query_by_role_and_label(Role::Dialog, "Paragraph").is_some(), "Paragraph is a dialog");
assert!(h.query_by_role_and_label(Role::Window, "Paragraph").is_none(), "not only a window");
assert_eq!(h.get_by_role_and_label(Role::Tab, "Indents and Spacing").accesskit_node().is_selected(), Some(true));
assert_eq!(h.get_by_role_and_label(Role::Tab, "Line and Page Breaks").accesskit_node().is_selected(), Some(false));
assert!(h.query_by_role_and_label(Role::Button, "Indents and Spacing").is_none(), "not a button");
let ctx = h.ctx.clone();
close_all(h.state_mut(), &ctx);
h.run_steps(2);
open_named(&mut h, "font", json!({}));
// The framework's split field has a face and a menu arrow; the latter opens the palette.
h.query_all_by_role_and_label(Role::Button, "Font color: Automatic").last().expect("named colour field").click();
h.run_steps(3);
assert!(h.query_by_label("#C00000").is_some(), "the swatches say their colour");
h.get_by_label("#C00000").click();
h.run_steps(3);
assert!(h.query_all_by_role_and_label(Role::Button, "Font color: #C00000").next().is_some(), "the field says the colour picked");
}
/// #5057: every caller retains its translated label and selected colour.
#[test]
fn colour_fields_say_their_label_and_colour_in_the_interface_language() {
use egui::accesskit::Role;
let mut app = app_with("Lanterns");
// The framework palette lists the document theme; use a known colour rather than its default.
app.session.doc.settings.theme_colors = vec![wordcraft_doc::Rgb(0xC0, 0, 0)];
let mut h = app_harness(app);
for (dialog, names) in [("font", vec!["Font color: Automatic"]), ("borders", vec!["Color: Automatic"]), ("shading", vec!["Fill No Color"])] {
let ctx = h.ctx.clone();
close_all(h.state_mut(), &ctx);
h.run_steps(2);
open_named(&mut h, dialog, json!({}));
for name in names {
assert!(h.query_all_by_role_and_label(Role::Button, name).next().is_some(), "{dialog}: {name}");
}
}
h.query_all_by_role_and_label(Role::Button, "Fill No Color").last().expect("shading colour field").click();
h.run_steps(3);
h.get_by_label("#C00000").click();
h.run_steps(3);
assert!(h.query_all_by_role_and_label(Role::Button, "Fill #C00000").next().is_some());
let ctx = h.ctx.clone();
close_all(h.state_mut(), &ctx);
h.state_mut().run("insert.table", json!({"rows": 2, "cols": 2})).unwrap();
open_named(&mut h, "newTableStyle", json!({}));
for name in ["Font color: No Color", "Fill color: No Color"] {
assert!(h.query_all_by_role_and_label(Role::Button, name).next().is_some(), "newTableStyle: {name}");
}
// Draw the shared app field directly: the app frame selects its configured language.
crate::i18n::apply_language(crate::i18n::fixture_lang(
"x-fixture",
"\tFont color:\tFont-color-FX:\n\tAutomatic\tAutomatic-FX\n\tFill\tFill-FX\n\tNo Color\tNo-Color-FX\n",
));
let mut h = crate::test_harness::builder().with_size(egui::vec2(600.0, 300.0)).build_ui_state(
|ui, values: &mut [String; 2]| {
use crate::colors::{AutoFace, ColorFieldEmpty, Palette, color_field};
use craft::ui::runtime::env::Label;
ui.push_id("font", |ui| {
let empty = ColorFieldEmpty::Automatic {
label: Label::from(tl!("Automatic")),
value: "auto",
face: AutoFace::One(craft::theme::Srgba::rgb(0.0, 0.0, 0.0)),
};
color_field(ui, &Label::from(tl!("Font color:")), &mut values[0], &empty, &Palette::default());
});
ui.push_id("fill", |ui| {
color_field(ui, &Label::from(tl!("Fill")), &mut values[1], &ColorFieldEmpty::NoColor, &Palette::default());
});
},
["auto".to_string(), String::new()],
);
h.run_steps(3);
let found: Vec<_> = ["Font-color-FX: Automatic-FX", "Fill-FX No-Color-FX"]
.into_iter()
.map(|name| (name, h.query_all_by_role_and_label(Role::Button, name).next().is_some()))
.collect();
crate::i18n::apply_language(crate::i18n::Lang::EN);
for (name, present) in found {
assert!(present, "the translated field is {name}");
}
}
+54 -1
View File
@@ -18,7 +18,8 @@ use crate::WordApp;
/// Most font files one Add Font pick tries; the rest of a bigger selection is skipped.
const MAX_FONTS_PER_PICK: usize = 2000;
const PICTURES: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "bmp", "wmf", "emf"];
/// Picture suffixes shared by native/web choosers, drop dispatch and copied-file paste.
pub const PICTURES: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "bmp", "tif", "tiff", "wmf", "emf"];
const DOCUMENTS: &[&str] =
&["docx", "docm", "dotx", "dotm", "doc", "dot", "odt", "ott", "fodt", "rtf", "txt", "md", "html", "htm", "mht", "mhtml", "tex", "json", "xml"];
@@ -34,6 +35,11 @@ pub fn open_filters(purpose: &str) -> &'static [(&'static str, &'static [&'stati
}
}
/// Whether a file name has a picture suffix offered by the Insert/Change Picture chooser.
pub(crate) fn is_picture_name(name: &str) -> bool {
name.rsplit_once('.').is_some_and(|(_, ext)| PICTURES.iter().any(|known| known.eq_ignore_ascii_case(ext)))
}
/// `request` with the file types `open_filters` offers for `purpose`.
fn with_open_filters(mut request: PickRequest, purpose: &str) -> PickRequest {
for (label, exts) in open_filters(purpose) {
@@ -525,3 +531,50 @@ impl WordApp {
#[cfg(test)]
mod tests;
#[cfg(test)]
mod picture_dispatch_tests {
use std::sync::Arc;
use craft::host::{AppInfo, Host, Picked, ScriptedFiles};
use craft::platform::open::{DropTarget, DroppedFile, FileIntake};
use super::*;
/// Pickers, drops and copied paths must agree on TIFF suffixes after the framework cutover.
#[test]
fn tiff_suffixes_dispatch_picked_and_dropped_images_and_copied_paths_as_pictures() {
for ext in ["tif", "tiff", "TIF", "TIFF"] {
let name = format!("scan.{ext}");
// Routing depends on the supplied name; the insertion decoder probes these PNG bytes.
let bytes = crate::paste_picture::png_from_rgba(4, 4, vec![200; 4 * 4 * 4]).unwrap();
let files = Arc::new(ScriptedFiles::held());
let host = Host::builder(AppInfo { id: "wordcraft-test", name: "WordCraft", version: "0" }).files(files.clone()).build();
let session = wordcraft_engine::Session::new(wordcraft_doc::Document::new());
let mut app = WordApp::new(session, crate::Services::default()).with_host(Arc::new(host));
let document = app.session.document_id();
app.pick_picture();
let request = files.requests().pop().unwrap();
let extensions: Vec<_> = request.filters.iter().flat_map(|f| f.extensions.iter().map(String::as_str)).collect();
assert!(extensions.contains(&"tif") && extensions.contains(&"tiff") && extensions.contains(&"png"));
assert!(!extensions.contains(&"txt"));
files.answer(Picked::Contents(vec![(name.clone(), bytes.clone())]));
app.poll_file_dialog().unwrap().unwrap();
assert_eq!(app.session.document_id(), document, "picker inserts into the current document: {ext}");
let pictures = app.session.run("arrange.selectionPane", &json!({})).unwrap();
assert_eq!(pictures.as_array().unwrap().len(), 1, "picker inserts a picture: {ext}");
let (intake, sender) = FileIntake::new(craft::host::Wake::none());
let services = crate::Services { intake: Some(intake), ..Default::default() };
let mut dropped = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), services);
let document = dropped.session.document_id();
sender.dropped(vec![DroppedFile { path: None, name, bytes: Some(bytes.into()) }], DropTarget::Elsewhere);
dropped.drain_inbox();
assert_eq!(dropped.session.document_id(), document, "drop inserts into the current document: {ext}");
let pictures = dropped.session.run("arrange.selectionPane", &json!({})).unwrap();
assert_eq!(pictures.as_array().unwrap().len(), 1, "drop inserts a picture: {ext}");
assert!(crate::paste_picture::names_picture_files(&format!("file:///tmp/scan.{ext}")));
}
assert!(!is_picture_name("notes.txt"));
}
}
+4 -3
View File
@@ -704,9 +704,10 @@ fn type_text(app: &mut WordApp, pass: &ToolPass, ctx: &egui::Context, text: &str
let start = app.session.sel.ordered().0;
let pending_before = app.session.pending.clone();
let typed = if let Some(props) = app.canvas.ime_join_text.take() {
// The replacement takes the erased text's formatting. `Session::run` does not restore
// `pending` on failure (it is not part of the document snapshot), so keep it here: a
// refused replacement must not leave its formatting waiting for the next ordinary key.
// The replacement takes the erased text's formatting. A failed `Session::run` puts back
// what was waiting when it started, which is this formatting, so the earlier one is put
// back here: a refused replacement must not leave its formatting waiting for the next
// ordinary key.
// The undo join itself is the engine's scoped body-replacement promise, consumed by
// `Session::run` only for this `text.insert` at the promised selection.
app.session.pending = Some(props);
+3 -4
View File
@@ -248,7 +248,6 @@ fn restored_placeholder_end(s: &wordcraft_engine::Session, deleted_start: usize)
struct ImeRollback {
snapshot: Option<wordcraft_engine::EditSnapshot>,
original: wordcraft_engine::Selection,
pending: Option<wordcraft_doc::props::CharProps>,
goal_x: Option<f32>,
}
@@ -258,8 +257,9 @@ impl ImeRollback {
return;
};
app.session.restore(snapshot);
// The snapshot puts back the formatting waiting at the caret, with where Backspace
// carried it over (#6518).
app.session.sel = self.original.clone();
app.session.pending = self.pending.clone();
app.session.goal_x = self.goal_x;
refuse_ime_request(app);
}
@@ -387,7 +387,6 @@ fn delete_surrounding_common(
let join = app.session.typing_open();
let props = app.session.typing_props();
let original = app.session.sel.clone();
let pending_before = app.session.pending.clone();
let goal_x_before = app.session.goal_x;
let before_stamp = ime_stamp(app);
// Both sides are one IME request: if the second half is refused (Restrict Editing, a
@@ -397,7 +396,7 @@ fn delete_surrounding_common(
// restored: `last_command`, macro recording, Go Back marks, `also_selected`, `typing`/
// `autocap` and canvas preedit (a refusal clears it).
let snapshot = app.session.edit_snapshot();
let mut rollback = ImeRollback { snapshot: Some(snapshot), original, pending: pending_before, goal_x: goal_x_before };
let mut rollback = ImeRollback { snapshot: Some(snapshot), original, goal_x: goal_x_before };
// Stored offsets of the suffix (and of the original selection) move by the paragraph's
// signed length change. A placeholder can make that positive; subtracting a removed-byte
// count cannot describe that, and would leave the second range and the caret inside the
+28
View File
@@ -888,6 +888,34 @@ fn tracked_own_insertion_then_a_refused_side_rolls_the_whole_request_back() {
assert_eq!(h.state().session.goal_x, Some(123.0), "the Up/Down goal column is restored");
}
/// #6518 review: a refused `DeleteSurrounding` rolls back the formatting Backspace carried
/// over together with where it applies: typing at the restored caret still takes it, and a
/// caret moved away leaves it behind, as before the request.
#[test]
fn a_refused_delete_surrounding_keeps_formatting_backspace_carried() {
let mut h = alt_frame_app();
run(&mut h, "document.setText", json!({"text": "abc"}));
// Wrap `c` in a rich-text control that refuses edits, and make `b` bold.
h.state_mut().session.sel = wordcraft_engine::Selection { anchor: wordcraft_doc::Pos::body(0, 2), focus: wordcraft_doc::Pos::body(0, 3) };
run(&mut h, "developer.richText", json!({"tag": "locked"}));
run(&mut h, "developer.properties", json!({"control": "locked", "lockEdit": true}));
h.state_mut().session.sel = wordcraft_engine::Selection { anchor: wordcraft_doc::Pos::body(0, 1), focus: wordcraft_doc::Pos::body(0, 2) };
run(&mut h, "format.bold", json!({"value": true}));
caret(&mut h, 2);
// Backspace the bold `b`: the caret, now after `a`, carries its bold.
run(&mut h, "text.backspace", json!({}));
assert_eq!(h.state().session.typing_props().bold, Some(true));
alt_frame(&mut h, vec![surround(1, 1)]);
assert_eq!(body(h.state()), "ac", "the request is refused and rolled back");
assert_eq!(h.state().session.sel, wordcraft_engine::Selection::caret(wordcraft_doc::Pos::body(0, 1)));
assert_eq!(h.state().session.typing_props().bold, Some(true), "the carried bold still applies at the restored caret");
// It is still carried over by Backspace, not picked at the caret: a caret moved elsewhere
// and back leaves it behind.
h.state_mut().session.set_selection(wordcraft_engine::Selection::caret(wordcraft_doc::Pos::body(0, 0)));
h.state_mut().session.set_selection(wordcraft_engine::Selection::caret(wordcraft_doc::Pos::body(0, 1)));
assert_ne!(h.state().session.typing_props().bold, Some(true), "the caret has been elsewhere");
}
/// Selects a body range, wraps it in a rich-text content control with `tag`, and sets its
/// placeholder.
fn wrap_in_control(h: &mut H, start: usize, end: usize, tag: &str, placeholder: &str) {
+3
View File
@@ -101,6 +101,7 @@ pub use dialogs::dialogs_ribbon;
pub use dialogs::dialogs_smart_art;
pub use file_dialogs::open_filters;
mod announce;
mod app;
mod services;
mod state;
@@ -416,6 +417,8 @@ pub struct WordApp {
pub spelling_review: Option<proofing_pane::SpellingForm>,
/// The status bar's message, until its `until` passes.
pub(crate) status: Option<Status>,
/// The latest formatting shortcut announcement for the active window.
pub(crate) announcement: Option<announce::Announcement>,
pub previews: previews::Previews,
/// Media key of the picture a pending Change Picture replaces (#147).
pub change_picture_target: Option<String>,
+1 -2
View File
@@ -18,7 +18,6 @@ use crate::{WordApp, system_clipboard};
pub(crate) const MAX_FILE_BYTES: u64 = 200 << 20;
/// Most picture files one paste inserts.
const MAX_FILES: usize = 20;
const IMAGE_EXTS: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "bmp", "wmf", "emf"];
/// PNG bytes for clipboard pixels, or why they can't be pasted. The platform read has checked the
/// size already.
@@ -31,7 +30,7 @@ pub fn png_from_rgba(width: usize, height: usize, rgba: Vec<u8>) -> Result<Vec<u
}
fn is_picture_file(path: &Path) -> bool {
path.extension().and_then(std::ffi::OsStr::to_str).is_some_and(|e| IMAGE_EXTS.iter().any(|x| x.eq_ignore_ascii_case(e)))
path.extension().and_then(std::ffi::OsStr::to_str).is_some_and(|e| crate::file_dialogs::PICTURES.iter().any(|x| x.eq_ignore_ascii_case(e)))
}
/// Pasted text that is only paths or `file://` addresses of picture files — what file managers
+1 -1
View File
@@ -41,7 +41,7 @@ pub fn poll(app: &mut WordApp, ctx: &egui::Context) {
let current = if reads_shown_document(app) { app.session.read_aloud.current().map(|u| u.start) } else { None };
if current != app.read_aloud_at {
if let Some(start) = &current {
app.session.sel = wordcraft_engine::Selection::caret(app.session.doc.clamp(start));
app.session.set_selection(wordcraft_engine::Selection::caret(app.session.doc.clamp(start)));
app.session.goal_x = None;
app.canvas.scroll_to_caret = true;
}
+1 -1
View File
@@ -245,7 +245,7 @@ fn enforced_ui(app: &mut WordApp, ui: &mut Ui, st: &mut RestrictPane, mode: &str
if (regions > 0 || fields > 0) && Button::new(tl!("Find Next Editable Region")).show(ui).clicked() {
let from = app.session.sel.ordered().1;
if let Some((a, b)) = wordcraft_engine::cmd::protect::next_region(&app.session, &from) {
app.session.sel = wordcraft_engine::Selection { anchor: a, focus: b };
app.session.set_selection(wordcraft_engine::Selection { anchor: a, focus: b });
app.canvas.focus_page(ui.ctx());
}
}
+5
View File
@@ -22,6 +22,8 @@ pub(crate) struct WindowUi {
pub(crate) restrict: crate::restrict_pane::RestrictPane,
pub(crate) spelling_review: Option<crate::proofing_pane::SpellingForm>,
pub(crate) status: Option<Status>,
/// Announcement belonging to this document window.
pub(crate) announcement: Option<crate::announce::Announcement>,
pub(crate) previews: previews::Previews,
pub(crate) change_picture_target: Option<String>,
pub(crate) recipient_list_pending: bool,
@@ -74,6 +76,7 @@ impl WindowUi {
restrict: Default::default(),
spelling_review: None,
status: None,
announcement: None,
previews: Default::default(),
change_picture_target: None,
recipient_list_pending: false,
@@ -184,6 +187,7 @@ impl WordApp {
restrict,
spelling_review,
status,
announcement,
previews,
change_picture_target,
recipient_list_pending,
@@ -281,6 +285,7 @@ impl WordApp {
restrict,
spelling_review,
status,
announcement,
previews,
change_picture_target,
recipient_list_pending,
File diff suppressed because one or more lines are too long
+4 -2
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+4 -2
View File
File diff suppressed because one or more lines are too long