Compare commits

...
21 Commits
Author SHA1 Message Date
Martin BallandClaude Opus 5.5 b000357c8f #7149 item 8: review fixes: text glyphs at the remaining call sites, grey when disabled
Home (group icons, grow/shrink, clear/phonetic, enclose, sort, Show/Hide
pilcrow, Paragraph Tools), the mini toolbar, Developer controls and the Draw
font colour use icons::spec so they draw the text glyph. A disabled glyph
paints both inks in text.disabled, as production did. The icon-name scan fails
on a glyph name passed through IconId::new or icons::id. Doc link and
ATTRIBUTION.md order fixed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-21 10:26:04 +00:00
Martin Ball 2f4d459900 Merge remote-tracking branch 'origin/main' into fix/7149-item8-ribbon-icons 2026-11-21 10:07:11 +00:00
Martin BallandClaude Opus 5.5 22314f552d Make the seven ui-egui tests that failed on macOS platform-aware (#7144)
Mod is Cmd on macOS, so the paste tests hold the platform's Mod key; Alt+Q is
the command search off macOS only; the unsaved-changes prompt asks Save on
macOS and Yes elsewhere; the default-app row shows Finder's steps on macOS, no
button; the i18n audit knows macOS chord symbols such as the Read Aloud hint.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-20 23:59:43 +00:00
Martin BallandClaude Opus 5.5 2da5e37b70 #7149 item 8: for_command picks the text glyph before the own SVG alias
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-20 21:32:15 +00:00
685869239f Proofing: support freestanding custom.dic dictionary files (#5840) (#5899)
* Proofing: support freestanding custom.dic dictionary files (#5840)

- Add freestanding custom dictionary loader and saver in custom_dict.rs
  supporting UTF-16LE with BOM, UTF-16BE with BOM, UTF-8 with BOM, and UTF-8.
- Detect BOM-less UTF-16LE via NUL-byte heuristic and preserve encoding on save.
- Preserve original dictionary lines and casing (NASA, McDonald, multi-word
  lines, lines > 64 chars) and merge disk additions on save.
- Add bounded reading (4 MB and 100,000 words limit) and graceful error handling.
- Validate read and write access, probe OS write permissions, and reject
  symbolic links and read-only files in check_regular_file_setting.
- Add customDictionary preference in file.options and Proofing options UI.
- Provide wasm fallbacks in crate::io.
- Add comprehensive engine integration, UI Kittest, and unit regression tests.

* Proofing: keep a bound custom dictionary as the source of truth (#5840)

- Do not restore the ui.json word backup when customDictionary is set, so a
  missing or unreadable file cannot leak its words into custom-dictionary.txt.
- Document the supported encodings, write-access checks and logged save
  failures for the review.
- Add a UI regression test for the backup words.

Co-authored-by: CommandCodeBot <[email protected]>

* Proofing: decode a custom dictionary before applying options (#5840)

file.options validated the customDictionary path's metadata but read the
file only while applying settings, so a writable file with malformed
UTF-8 refused the call after author, initials, units, region and
dictionariesFolder had already changed. Decode the requested file (and
the default one for auto) alongside the other parameter checks, then
apply nothing if it fails.

Regression: refused_custom_dictionary_leaves_every_other_option_unchanged
compares every setting, the bound path and the proofing words before and
after a combined refused call.

* Proofing: preserve custom dictionary persistence target during fallback (#5840)

* ROADMAP.md: remove conflict-resolution debris

* Format the custom dictionary tests

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* Commit the custom dictionary path on Enter, and test the startup fallback

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Show the saved custom dictionary path when no edit is open

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: CommandCodeBot <[email protected]>
Co-authored-by: batistalucasv <[email protected]>
Co-authored-by: Claude Sonnet 5.5 <[email protected]>
2026-11-20 20:37:12 +00:00
f5f29dc076 PDF export: tracked changes take the Track Changes Options colours (#5232) (#6144)
* PDF export: tracked changes take the Track Changes Options colours (#5232)

PDF and page image exports now respect Review › Track Changes Options
colours (insertColor, deleteColor) and mark preferences (deleteMark:
hidden), matching on-screen behavior instead of always defaulting to
author-0 magenta (#5232).

Fixes #5232

Co-authored-by: cdhdt <[email protected]>

* Page images and print preview draw headers at full strength (#6267)

The downloaded page image and print preview built RenderOptions::default(),
whose dim_header is true, so a tracked change in a header or footer faded
there while PDF and file.exportPng drew it at full strength. Both now use
full-strength header display, with page_image_options shared across
file.exportPng, file.strictReport's page check and downloaded page images.

file.printPdf documents its compress parameter, which the colour regressions
use to read the content stream.

* Docs: record tracked-change export colours and preview parity (#5232, #6267)

ROADMAP, gaps, file-format parity and UI parity now record the export
colours and marks, final-text print pagination, and the preview matching
the print job. #6263, #6265 and #6266 remain.

* Fix merge conflict markers in PDF and engine option structs (#5232)

* docs: remove stray branch labels in ROADMAP, gaps and ui-parity (#5232)

---------

Co-authored-by: cdhdt <[email protected]>
Co-authored-by: batistalucasv <[email protected]>
Co-authored-by: Claude Sonnet 5.5 <[email protected]>
2026-11-20 19:56:55 +00:00
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 <[email protected]>

* #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 <[email protected]>
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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
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 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 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 0478b7633f Merge main (4e8c9d55) into formatting-shortcuts-say-what-they-did 2026-11-18 13:42:34 +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 <[email protected]>
2026-11-02 20:33:38 +01:00
squalorsoandClaude Opus 5.5 4a1b0aac18 Merge main (bbe3547d) into formatting-shortcuts-say-what-they-did
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 19:25:56 +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 <[email protected]>
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 <[email protected]>
2026-11-01 00:46:43 +01:00
76 changed files with 3212 additions and 152 deletions
+1 -1
View File
@@ -352,8 +352,8 @@ The UI icons are SVG files in `crates/ui-egui/icons/`, one row each below. Gener
| `crates/ui-egui/icons/table.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/tableOfAuthorities.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/tableOfFigures.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/tableStyles.svg` | WordCraft contributors | original: drawn for WordCraft in the style of the code-drawn icon set (#7149) | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/tableStyleOptions.svg` | WordCraft contributors | original: drawn for WordCraft in the style of the code-drawn icon set (#7149) | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/tableStyles.svg` | WordCraft contributors | original: drawn for WordCraft in the style of the code-drawn icon set (#7149) | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/textBox.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/textBoxLink.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/textBoxUnlink.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
+10 -3
View File
File diff suppressed because one or more lines are too long
+1 -2
View File
@@ -544,8 +544,7 @@ fn main() -> eframe::Result {
if prefs::enabled()
&& let Some(path) = prefs::user_dict_path()
{
prefs::load_user_dictionary(&settings, &path);
session.user_dict_path = Some(path);
prefs::load_user_dictionary(&mut session, &settings, path);
}
let spool = Spool::new(host.jobs_shared().clone());
let mut app = WordApp::new(session, services(spool.clone(), intake)).with_host(host).with_settings(settings.clone());
+114 -6
View File
@@ -61,11 +61,49 @@ fn import_window(path: &Path, placement: &mut Store) {
}
}
/// Loads the words of the custom dictionary file at `path` into the spell checker, and counts them
/// as loaded settings: the words only the file has are in `Prefs::dictionary`, so the app's
/// preferences list is the whole dictionary (#3773).
pub fn load_user_dictionary(settings: &SharedSettings<Prefs>, path: &Path) {
let words = wordcraft_proof::load_user_dictionary(path);
/// Loads the custom dictionary into the spell checker and counts its words as loaded settings:
/// the words only the file has are in `Prefs::dictionary`, so the app's preferences list is the
/// whole dictionary (#3773). `default_path` is `custom-dictionary.txt` in the settings folder.
///
/// A bound custom dictionary file (`editing.custom_dictionary`, #5840) that reads is the source of
/// truth and the write target. If it is missing or unreadable, the default file is read for
/// spelling only and `user_dict_path` stays unset, so later writes never go to the default file
/// while the setting still names the custom one. With no custom file, the default is read and written.
pub fn load_user_dictionary(session: &mut wordcraft_engine::Session, settings: &SharedSettings<Prefs>, default_path: PathBuf) {
session.default_user_dict_path = Some(default_path.clone());
let custom = settings.lock().get().editing.custom_dictionary.as_ref().map(PathBuf::from);
let mut words = Vec::new();
let mut loaded = false;
if let Some(p) = &custom {
if p.is_file() {
match wordcraft_engine::custom_dict::load_custom_dictionary_replacing(p) {
Ok(w) => {
words = w;
session.user_dict_path = Some(p.clone());
loaded = true;
}
Err(e) => log::warn!("custom dictionary: failed to load '{}': {e}", p.display()),
}
} else {
log::warn!("custom dictionary: '{}' is not a regular file", p.display());
}
}
if !loaded {
if default_path.is_file() {
if custom.is_some() {
match wordcraft_engine::custom_dict::load_custom_dictionary_replacing(&default_path) {
Ok(w) => words = w,
Err(e) => log::warn!("default dictionary: failed to load '{}': {e}", default_path.display()),
}
} else {
words = wordcraft_proof::load_user_dictionary(&default_path);
session.user_dict_path = Some(default_path);
}
} else if custom.is_none() {
// A missing default file is not a replacement: keep any words restored from preferences.
session.user_dict_path = Some(default_path);
}
}
settings.lock().update(|prefs| {
for word in words {
if !prefs.dictionary.contains(&word) {
@@ -112,7 +150,7 @@ mod tests {
std::fs::write(&dict, "zqxinfile\n").unwrap();
let (settings, report) = open_in(Some(dir.path().to_path_buf()), &mut Store::in_memory());
assert!(matches!(report.source, Source::Legacy(_)), "ui.json is imported: {:?}", report.source);
load_user_dictionary(&settings, &dict);
load_user_dictionary(&mut wordcraft_engine::Session::new(wordcraft_doc::Document::new()), &settings, dict.clone());
let words = settings.lock().get().dictionary.clone();
for word in ["zqxinjson", "zqxinfile"] {
assert!(words.iter().any(|w| w == word), "{word}: {words:?}");
@@ -166,4 +204,74 @@ mod tests {
assert_eq!(now.ribbon.qat, None, "A's old copy of the toolbar does not bring it back");
assert!(now.dictionary.iter().any(|w| w == "zqxtoolbar"), "A's own change is kept");
}
/// The tests that bind a custom dictionary replace the spell checker's words, which every
/// test shares: one at a time.
static CUSTOM_DICT: std::sync::Mutex<()> = std::sync::Mutex::new(());
/// #5840: while the setting names a custom file that is missing, the default file is read
/// for spelling only. Nothing becomes the write target, so Add to Dictionary never moves the
/// person's words into `custom-dictionary.txt` behind the setting's back.
#[test]
fn a_missing_custom_dictionary_leaves_no_write_target() {
let _one = CUSTOM_DICT.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let dir = tempfile::tempdir().unwrap();
let default = dir.path().join("custom-dictionary.txt");
std::fs::write(&default, "zqxfallbackword\n").unwrap();
let (settings, _) = open_in(Some(dir.path().to_path_buf()), &mut Store::in_memory());
let missing = dir.path().join("gone").join("CUSTOM.DIC");
settings.lock().update(|p| p.editing.custom_dictionary = Some(missing.to_string_lossy().into_owned()));
let mut session = wordcraft_engine::Session::new(wordcraft_doc::Document::new());
load_user_dictionary(&mut session, &settings, default.clone());
assert_eq!(session.user_dict_path, None, "no write target while the custom file is missing");
assert_eq!(session.default_user_dict_path.as_deref(), Some(default.as_path()));
assert!(wordcraft_engine::proof::user_dictionary().iter().any(|w| w == "zqxfallbackword"), "the default file still spells");
wordcraft_engine::proof::remove_word("zqxfallbackword");
}
/// #5840: a custom file that is set but missing, with no default file either: nothing is a
/// write target (the `custom.is_none()` arm does not claim the default), and nothing panics.
#[test]
fn a_missing_custom_and_default_dictionary_leave_no_write_target() {
let _one = CUSTOM_DICT.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let dir = tempfile::tempdir().unwrap();
let default = dir.path().join("custom-dictionary.txt");
let (settings, _) = open_in(Some(dir.path().to_path_buf()), &mut Store::in_memory());
let missing = dir.path().join("gone").join("CUSTOM.DIC");
settings.lock().update(|p| p.editing.custom_dictionary = Some(missing.to_string_lossy().into_owned()));
let mut session = wordcraft_engine::Session::new(wordcraft_doc::Document::new());
load_user_dictionary(&mut session, &settings, default.clone());
assert_eq!(session.user_dict_path, None, "no write target while the custom file is missing");
assert_eq!(session.default_user_dict_path.as_deref(), Some(default.as_path()));
assert_eq!(settings.lock().get().editing.custom_dictionary.as_deref(), Some(&*missing.to_string_lossy()), "the setting is kept");
}
/// #5840: with no custom file set, the default file is the write target, whether or not it
/// exists yet; a readable custom file is the write target when it is set.
#[test]
fn the_write_target_is_the_default_file_unless_a_custom_one_reads() {
let _one = CUSTOM_DICT.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let dir = tempfile::tempdir().unwrap();
let default = dir.path().join("custom-dictionary.txt");
let (settings, _) = open_in(Some(dir.path().to_path_buf()), &mut Store::in_memory());
let mut session = wordcraft_engine::Session::new(wordcraft_doc::Document::new());
load_user_dictionary(&mut session, &settings, default.clone());
assert_eq!(session.user_dict_path.as_deref(), Some(default.as_path()), "a missing default file is still the target");
std::fs::write(&default, "zqxdefaultword\n").unwrap();
let mut session = wordcraft_engine::Session::new(wordcraft_doc::Document::new());
load_user_dictionary(&mut session, &settings, default.clone());
assert_eq!(session.user_dict_path.as_deref(), Some(default.as_path()));
let custom = dir.path().join("CUSTOM.DIC");
std::fs::write(&custom, "zqxcustomword\r\n").unwrap();
settings.lock().update(|p| p.editing.custom_dictionary = Some(custom.to_string_lossy().into_owned()));
let mut session = wordcraft_engine::Session::new(wordcraft_doc::Document::new());
load_user_dictionary(&mut session, &settings, default.clone());
assert_eq!(session.user_dict_path.as_deref(), Some(custom.as_path()), "a readable custom file is the target");
let words = wordcraft_engine::proof::user_dictionary();
assert!(words.iter().any(|w| w == "zqxcustomword") && !words.iter().any(|w| w == "zqxdefaultword"), "{words:?}");
wordcraft_engine::proof::remove_word("zqxcustomword");
wordcraft_engine::proof::remove_word("zqxdefaultword");
}
}
+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);
+14 -7
View File
@@ -131,7 +131,7 @@ pub fn specs() -> Vec<CommandSpec> {
.pure(),
CommandSpec::new("file.printPdf", "Print to PDF", "File › Print", crate::print::print_pdf_to_file)
.params(
r#"{"path": string, "pagesPerSheet"?: 1 | 2 | 4 | 6 | 9 | 16 | "booklet" | "bookletReverse", "range"?: "all" | "current" | "selection" (the pages the selection touches) | "custom", "pages"?: "1-3,5" (implies custom), "parity"?: "all" | "odd" | "even", "copies"?: 1-999, "collate"?: bool (default true), "paper"?: "none" | "Letter" | "Legal" | "A4" | … (a Layout › Size name: scale every page to this paper, centred; the document keeps its size)}"#,
r#"{"path": string, "pagesPerSheet"?: 1 | 2 | 4 | 6 | 9 | 16 | "booklet" | "bookletReverse", "range"?: "all" | "current" | "selection" (the pages the selection touches) | "custom", "pages"?: "1-3,5" (implies custom), "parity"?: "all" | "odd" | "even", "copies"?: 1-999, "collate"?: bool (default true), "paper"?: "none" | "Letter" | "Legal" | "A4" | … (a Layout › Size name: scale every page to this paper, centred; the document keeps its size), "compress"?: bool (default true: compress the PDF's content streams; false writes the same pages uncompressed, which is larger)"#,
)
.pure(),
CommandSpec::new("file.print", "Print", "File", |s, _| {
@@ -485,8 +485,8 @@ fn save_as(s: &mut Session, v: &Value) -> CmdResult {
}
/// How a copy is written: Print Markup from the command's `markup`, else the File › Print
/// setting (`file.printMarkup`); comments as Track Changes Options show them; digits as the
/// Numeral setting shows them on screen.
/// setting (`file.printMarkup`); comments and revision marks/colours as Track Changes Options show them;
/// digits as the Numeral setting shows them on screen.
pub fn export_options(s: &Session, v: &Value) -> crate::io::ExportOptions {
let markup = p::bool(v, "markup").unwrap_or(s.prefs.print_markup);
crate::io::ExportOptions {
@@ -494,6 +494,7 @@ pub fn export_options(s: &Session, v: &Value) -> crate::io::ExportOptions {
comments: markup && s.prefs.markup.comments,
word2003: p::str(v, "format") == Some(FORMAT_WORD_2003),
numeral: s.view.numeral.resolve(crate::session::system_locale()),
revisions: s.prefs.markup.clone(),
strict: p::bool(v, "strict").unwrap_or(false),
}
}
@@ -517,7 +518,10 @@ fn strict_report(s: &mut Session, v: &Value) -> CmdResult {
if l.pages.get(page).is_none() {
return Err(CmdError::Params(format!("no page {}", page + 1)));
}
crate::strict::strict_report(&s.doc, &l, &crate::strict::png_display(), Some(page..=page), wordcraft_layout::StrictOutput::Png)
// The page image `file.exportPng` writes: the printed page, tracked changes marked as
// Track Changes Options mark them.
let display = crate::io_ext::page_image_options(&opts).display;
crate::strict::strict_report(&s.doc, &l, &display, Some(page..=page), wordcraft_layout::StrictOutput::Png)
}
None => {
let out = super::references::output_fields(&s.doc);
@@ -527,6 +531,7 @@ fn strict_report(s: &mut Session, v: &Value) -> CmdResult {
Ok(report.to_json())
}
/// Exports a page of the current document as a PNG image at the requested scale.
fn export_png(s: &mut Session, v: &Value) -> CmdResult {
// No path: the app asks where to save, as file.exportPdf does (#2313).
let Some(path) = p::str(v, "path") else {
@@ -536,11 +541,13 @@ fn export_png(s: &mut Session, v: &Value) -> CmdResult {
let page = crate::p::page_index(p::u64(v, "page").unwrap_or(1));
let strict = p::bool(v, "strict").unwrap_or(false);
let scale = p::f32(v, "scale").unwrap_or(2.0).clamp(0.1, 8.0);
let l = s.export_layout_with(export_options(s, v).markup);
let export = export_options(s, v);
let l = s.export_layout_with(export.markup);
let pg = l.pages.get(page).ok_or_else(|| CmdError::Params(format!("no page {}", page + 1)))?;
// A page image is the printed page: headers and footers at full strength. Dimming them is
// the on-screen cue while editing the body, not part of the page.
let opts = wordcraft_render::RenderOptions { display: crate::strict::png_display(), ..Default::default() };
// the on-screen cue while editing the body, not part of the page. Tracked changes are marked
// as Track Changes Options mark them on screen.
let opts = crate::io_ext::page_image_options(&export);
if !path.to_ascii_lowercase().ends_with(".png") {
return Err(CmdError::Params("path must end in .png".into()));
}
+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);
+80 -1
View File
@@ -18,11 +18,12 @@ pub const MAX_WORD_CHARS: usize = 64;
/// Most words one call may add or remove.
const MAX_WORDS_PER_CALL: usize = 1000;
/// Command specifications for options commands.
pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec::new("file.options", "Options", "File", options)
.params(
r#"{"pane"?: "general|display|proofing|save|language|accessibility|advanced|agents", "author"?: string, "initials"?: string, "units"?: "inches|centimeters|millimeters|points|picas|auto" (auto: the region's), "region"?: string (a locale tag like pl-PL, saved: the paper File › New starts on, the default units and the decimal separator; auto: the system's), "typingReplacesSelection"?: bool, "insertKeyOvertype"?: bool, "overtype"?: bool, "marks"?: {"tabs"?: bool, "spaces"?: bool, "paragraphs"?: bool, "hidden"?: bool}, "checkSpelling"?: bool, "markGrammar"?: bool, "ignoreUppercase"?: bool, "ignoreNumbers"?: bool, "ignoreInternet"?: bool, "dictionariesFolder"?: string (a folder of Hunspell .aff/.dic files searched first, saved; auto: clear the configured folder), "userTemplatesFolder"?: string (the folder File › New lists personal templates from, saved; auto: the app's own Templates folder; not a network folder), "addWords"?: [string], "removeWords"?: [string]} — with any setting it changes them and opens nothing; without, it opens File › Options (at `pane`). Returns the settings."#,
r#"{"pane"?: "general|display|proofing|save|language|accessibility|advanced|agents", "author"?: string, "initials"?: string, "units"?: "inches|centimeters|millimeters|points|picas|auto" (auto: the region's), "region"?: string (a locale tag like pl-PL, saved: the paper File › New starts on, the default units and the decimal separator; auto: the system's), "typingReplacesSelection"?: bool, "insertKeyOvertype"?: bool, "overtype"?: bool, "marks"?: {"tabs"?: bool, "spaces"?: bool, "paragraphs"?: bool, "hidden"?: bool}, "checkSpelling"?: bool, "markGrammar"?: bool, "ignoreUppercase"?: bool, "ignoreNumbers"?: bool, "ignoreInternet"?: bool, "dictionariesFolder"?: string (a folder of Hunspell .aff/.dic files searched first, saved; auto: clear the configured folder), "customDictionary"?: string (a custom-word dictionary file like custom.dic, saved; auto: the default custom-dictionary.txt in the settings folder), "userTemplatesFolder"?: string (the folder File › New lists personal templates from, saved; auto: the app's own Templates folder; not a network folder), "addWords"?: [string], "removeWords"?: [string]} — with any setting it changes them and opens nothing; without, it opens File › Options (at `pane`). Returns the settings."#,
)
.pure(),
CommandSpec::new("text.overtype", "Overtype", "File › Options › Advanced", |s, v| {
@@ -78,6 +79,7 @@ fn words_param(v: &Value, k: &str) -> Result<Vec<String>, CmdError> {
Ok(out)
}
/// Open File › Options (or change settings programmatically via `file.options`).
fn options(s: &mut Session, v: &Value) -> CmdResult {
let pane = match p::str(v, "pane") {
Some(name) if PANES.contains(&name) => name,
@@ -120,6 +122,18 @@ fn options(s: &mut Session, v: &Value) -> CmdResult {
Some(Value::String(f)) => Some(folder_setting("dictionariesFolder", f, false)?),
Some(_) => return Err(CmdError::Params("`dictionariesFolder` must be a folder path, or auto".into())),
};
let custom_dictionary = match v.get("customDictionary") {
None | Some(Value::Null) => None,
Some(Value::String(f)) => Some(file_setting("customDictionary", f)?),
Some(_) => return Err(CmdError::Params("`customDictionary` must be a file path, or auto".into())),
};
// Decode the requested dictionary while still only validating: a file that passes the
// metadata and access checks but can't be decoded refuses the call before `author`, `units`,
// `region` or any other setting changes.
let custom_dictionary_state = match custom_dictionary {
None => None,
Some(ref f) => Some((prepare_custom_dictionary(s, f.as_deref())?, f.clone())),
};
let templates_folder = match v.get("userTemplatesFolder") {
None | Some(Value::Null) => None,
// Never a folder on another machine (#2852): listing it would make Windows authenticate there.
@@ -153,6 +167,7 @@ fn options(s: &mut Session, v: &Value) -> CmdResult {
|| units.is_some()
|| region.is_some()
|| folder.is_some()
|| custom_dictionary.is_some()
|| templates_folder.is_some()
|| !flag_values.is_empty()
|| !mark_values.is_empty()
@@ -175,6 +190,16 @@ fn options(s: &mut Session, v: &Value) -> CmdResult {
use_dictionaries_folder(f.as_deref());
s.prefs.dictionaries_folder = f;
}
if let Some(((new_path, new_words), setting)) = custom_dictionary_state {
if s.user_dict_path.as_ref() != new_path.as_ref() {
crate::custom_dict::clear_user_dictionary();
for w in new_words {
wordcraft_proof::add_word(&w);
}
s.user_dict_path = new_path;
}
s.prefs.custom_dictionary = setting;
}
if let Some(f) = templates_folder {
s.prefs.user_templates_folder = f;
}
@@ -231,6 +256,7 @@ pub fn current(s: &Session) -> Value {
"ignoreNumbers": pr.ignore_numbers,
"ignoreInternet": pr.ignore_internet,
"dictionary": wordcraft_proof::user_dictionary(),
"customDictionary": pr.custom_dictionary,
"dictionariesFolder": pr.dictionaries_folder,
"userTemplatesFolder": pr.user_templates_folder,
"dictionaries": wordcraft_proof::installed_dictionaries()
@@ -240,6 +266,27 @@ pub fn current(s: &Session) -> Value {
})
}
/// The path the custom dictionary becomes and the words it holds, read before any setting is
/// applied. `None` (`auto`) means the default `custom-dictionary.txt` in the settings folder;
/// a missing default file is an empty dictionary, as it was before the setting was bound.
fn prepare_custom_dictionary(s: &Session, setting: Option<&str>) -> Result<(Option<std::path::PathBuf>, Vec<String>), CmdError> {
match setting {
Some(path_str) => {
let path = std::path::PathBuf::from(path_str);
let words = crate::custom_dict::read_custom_dictionary_words_checked(&path).map_err(CmdError::Failed)?;
Ok((Some(path), words))
}
None => {
let path = s.default_user_dict_path.clone();
let words = match path.as_deref() {
Some(def) if def.exists() => crate::custom_dict::read_custom_dictionary_words_checked(def).map_err(CmdError::Failed)?,
_ => Vec::new(),
};
Ok((path, words))
}
}
}
/// A folder setting (`dictionariesFolder`, `userTemplatesFolder`): `auto` (or nothing) forgets
/// it; otherwise an existing folder, given as an absolute path or one starting with `~/`. With
/// `local_only`, a network folder is refused before anything looks at it (#2852): even checking
@@ -271,6 +318,38 @@ fn folder_setting(key: &str, f: &str, local_only: bool) -> Result<Option<String>
Ok(Some(path.to_string_lossy().into_owned()))
}
/// A file setting (`customDictionary`): `auto` (or nothing) forgets it; otherwise an existing
/// file, given as an absolute path or one starting with `~/`.
fn file_setting(key: &str, f: &str) -> Result<Option<String>, CmdError> {
let f = f.trim();
if f.is_empty() || f.eq_ignore_ascii_case("auto") {
return Ok(None);
}
if f.chars().count() > MAX_FOLDER_CHARS || f.chars().any(char::is_control) {
return Err(CmdError::Params(format!("`{key}` isn't a file path")));
}
let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).filter(|h| !h.is_empty()).map(std::path::PathBuf::from);
let path = if let Some(rest) = f.strip_prefix("~/") {
match home {
Some(h) => h.join(rest),
None => return Err(CmdError::Params(format!("`{key}`: cannot expand `~/` because HOME or USERPROFILE is not set"))),
}
} else {
std::path::PathBuf::from(f)
};
if !path.is_absolute() {
return Err(CmdError::Params(format!("`{key}`: {f:?} isn't a full path")));
}
match crate::io::check_regular_file_setting(&path, crate::custom_dict::MAX_CUSTOM_FILE_BYTES, key) {
Ok(()) => {}
Err(crate::io::FileCheckError::IsDirectory(msg) | crate::io::FileCheckError::IsSymlink(msg)) => return Err(CmdError::Params(msg)),
Err(crate::io::FileCheckError::Access(msg) | crate::io::FileCheckError::NotFound(msg) | crate::io::FileCheckError::TooLarge(msg)) => {
return Err(CmdError::Failed(msg));
}
}
Ok(Some(path.to_string_lossy().into_owned()))
}
/// Search `folder` for Hunspell dictionaries before the system locations, from now on (the saved
/// setting, applied when the app starts and when it changes).
pub fn use_dictionaries_folder(folder: Option<&str>) {
+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)?;
+706
View File
@@ -0,0 +1,706 @@
//! Custom dictionary file reading and saving (#5840).
//!
//! Microsoft Word stores custom user words in freestanding dictionary files (commonly `CUSTOM.DIC`).
//! On Windows, Word traditionally encodes `CUSTOM.DIC` as UTF-16LE with a byte order mark (BOM)
//! and CRLF line endings, but also accepts UTF-8 (with or without BOM).
//!
//! This module loads and persists custom dictionary files, preserving their detected encoding
//! across edits and merging external additions safely. Format and encoding characteristics were
//! observed black-box from synthetic user dictionary files created and saved by Word on Windows.
use std::collections::HashSet;
use std::path::Path;
/// Maximum size of a custom dictionary file read into memory, in bytes (4 MB).
pub const MAX_CUSTOM_FILE_BYTES: u64 = 4_000_000;
/// Maximum number of words loaded from a custom dictionary file.
pub const MAX_CUSTOM_WORDS: usize = 100_000;
/// The text encoding detected for a custom dictionary file.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DictEncoding {
/// UTF-16 Little Endian with BOM (`[0xFF, 0xFE]`), standard for Word's `CUSTOM.DIC` on Windows.
Utf16LeBom,
/// UTF-16 Big Endian with BOM (`[0xFE, 0xFF]`).
Utf16BeBom,
/// UTF-8 with BOM (`[0xEF, 0xBB, 0xBF]`).
Utf8Bom,
/// Standard UTF-8 without BOM.
Utf8,
}
/// Check if raw bytes appear to be BOM-less UTF-16LE using a NUL-byte heuristic on even/odd positions.
pub fn is_bomless_utf16le(bytes: &[u8]) -> bool {
bytes.len() >= 4 && bytes.iter().skip(1).step_by(2).filter(|&&b| b == 0).count() > bytes.len() / 4
}
/// Detect the text encoding of raw dictionary file bytes.
pub fn detect_file_encoding(bytes: &[u8]) -> DictEncoding {
if bytes.len() >= 2 && bytes[0] == 0xFF && bytes[1] == 0xFE {
DictEncoding::Utf16LeBom
} else if bytes.len() >= 2 && bytes[0] == 0xFE && bytes[1] == 0xFF {
DictEncoding::Utf16BeBom
} else if bytes.len() >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF {
DictEncoding::Utf8Bom
} else if is_bomless_utf16le(bytes) {
DictEncoding::Utf16LeBom
} else {
DictEncoding::Utf8
}
}
/// Decode UTF-16 `payload` bytes (no BOM) in the given byte order.
fn decode_utf16(payload: &[u8], big_endian: bool, label: &str) -> Result<String, String> {
if !payload.len().is_multiple_of(2) {
return Err(format!("malformed {label}: odd byte length"));
}
let units = payload.as_chunks::<2>().0.iter().map(|&b| if big_endian { u16::from_be_bytes(b) } else { u16::from_le_bytes(b) });
char::decode_utf16(units).collect::<Result<String, _>>().map_err(|_| format!("malformed {label}: unpaired surrogate"))
}
/// Decode raw dictionary bytes into a UTF-8 string, handling UTF-16LE, UTF-16BE, UTF-8 with BOM,
/// and UTF-8, returning an error on malformed encodings, odd byte lengths, or unpaired surrogates.
pub fn decode_dictionary_bytes(bytes: &[u8]) -> Result<String, String> {
if bytes.len() >= 2 && bytes[0] == 0xFF && bytes[1] == 0xFE {
return decode_utf16(&bytes[2..], false, "UTF-16LE");
}
if bytes.len() >= 2 && bytes[0] == 0xFE && bytes[1] == 0xFF {
return decode_utf16(&bytes[2..], true, "UTF-16BE");
}
let slice = if bytes.len() >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF { &bytes[3..] } else { bytes };
// Check for UTF-16LE without a BOM (common in headless Windows exports) before the UTF-8
// attempt. ASCII-only UTF-16LE is also valid UTF-8, so the UTF-8 check cannot detect it.
if is_bomless_utf16le(slice) {
decode_utf16(slice, false, "UTF-16LE")
} else {
std::str::from_utf8(slice).map(str::to_string).map_err(|e| format!("malformed UTF-8: {e}"))
}
}
/// Parse dictionary words from decoded text lines, validating each word and capping at [`MAX_CUSTOM_WORDS`].
///
/// If `path_for_err` is `Some`, returns an error when the dictionary exceeds [`MAX_CUSTOM_WORDS`] words.
pub fn parse_dictionary_words(text: &str, path_for_err: Option<&str>) -> Result<Vec<String>, String> {
let mut words = Vec::new();
for line in text.lines() {
let cleaned = line.trim_matches(|c: char| c == '\r' || c == '\n');
if let Some(w) = wordcraft_proof::custom_word(cleaned) {
if words.len() >= MAX_CUSTOM_WORDS {
if let Some(p) = path_for_err {
return Err(format!("{p}: dictionary exceeds limit of {MAX_CUSTOM_WORDS} words"));
}
break;
}
words.push(w);
}
}
Ok(words)
}
/// Read the raw words from a custom dictionary file, capped at [`MAX_CUSTOM_FILE_BYTES`] and
/// [`MAX_CUSTOM_WORDS`].
///
/// Returns `Ok(Vec::new())` if the file does not exist (treating a missing dictionary as empty).
/// Returns an error if an existing file cannot be read within limits.
pub fn read_custom_dictionary_words(path: &Path) -> Result<Vec<String>, String> {
if !path.exists() {
return Ok(Vec::new());
}
let path_str = path.to_string_lossy();
let bytes = crate::io::read_file_capped(&path_str, MAX_CUSTOM_FILE_BYTES, "dictionary")?;
let text = decode_dictionary_bytes(&bytes).map_err(|e| format!("{path_str}: {e}"))?;
parse_dictionary_words(&text, Some(&path_str))
}
/// Read words from a custom dictionary file, capped at [`MAX_CUSTOM_FILE_BYTES`] and
/// [`MAX_CUSTOM_WORDS`].
///
/// Returns an error if the file cannot be read within limits or does not exist.
pub fn read_custom_dictionary_words_checked(path: &Path) -> Result<Vec<String>, String> {
let path_str = path.to_string_lossy();
let bytes = crate::io::read_file_capped(&path_str, MAX_CUSTOM_FILE_BYTES, "dictionary")?;
let text = decode_dictionary_bytes(&bytes).map_err(|e| format!("{path_str}: {e}"))?;
parse_dictionary_words(&text, Some(&path_str))
}
/// Load custom dictionary words from `path` into proofing's user dictionary.
///
/// Returns the list of words added to the proofing dictionary, or an error if an existing file
/// could not be read within limits.
pub fn load_custom_dictionary(path: &Path) -> Result<Vec<String>, String> {
let words = read_custom_dictionary_words(path)?;
let mut added = Vec::new();
for w in words {
wordcraft_proof::add_word(&w);
added.push(w);
}
Ok(added)
}
/// Load custom dictionary words from `path`, replacing all existing in-memory custom words
/// only if the file is successfully read.
///
/// If `path` cannot be read within limits or does not exist, returns an error without
/// modifying the existing in-memory proofing dictionary.
///
/// # Errors
/// Returns an error string if the file does not exist, exceeds size limits, or has invalid encoding.
pub fn load_custom_dictionary_replacing(path: &Path) -> Result<Vec<String>, String> {
let words = read_custom_dictionary_words_checked(path)?;
clear_user_dictionary();
for w in &words {
wordcraft_proof::add_word(w);
}
Ok(words)
}
/// Clear all custom words currently held in the in-memory proofing dictionary.
pub fn clear_user_dictionary() {
for w in wordcraft_proof::user_dictionary() {
wordcraft_proof::remove_word(&w);
}
}
/// Encode a list of words into bytes matching the requested [`DictEncoding`].
pub fn encode_dictionary_words(words: &[String], encoding: DictEncoding) -> Vec<u8> {
match encoding {
DictEncoding::Utf16LeBom => {
let mut out = Vec::with_capacity(words.len() * 20 + 2);
out.extend_from_slice(&[0xFF, 0xFE]);
for w in words {
for u in w.encode_utf16() {
out.extend_from_slice(&u.to_le_bytes());
}
// CRLF line endings for Word UTF-16LE custom dictionaries.
out.extend_from_slice(&[0x0D, 0x00, 0x0A, 0x00]);
}
out
}
DictEncoding::Utf16BeBom => {
let mut out = Vec::with_capacity(words.len() * 20 + 2);
out.extend_from_slice(&[0xFE, 0xFF]);
for w in words {
for u in w.encode_utf16() {
out.extend_from_slice(&u.to_be_bytes());
}
out.extend_from_slice(&[0x00, 0x0D, 0x00, 0x0A]);
}
out
}
DictEncoding::Utf8Bom => {
let mut out = Vec::with_capacity(words.len() * 10 + 3);
out.extend_from_slice(&[0xEF, 0xBB, 0xBF]);
for w in words {
out.extend_from_slice(w.as_bytes());
out.push(b'\n');
}
out
}
DictEncoding::Utf8 => {
let mut out = Vec::with_capacity(words.len() * 10);
for w in words {
out.extend_from_slice(w.as_bytes());
out.push(b'\n');
}
out
}
}
}
/// Save the current user dictionary to `path`, merging any external additions made on disk,
/// omitting `removed`, and preserving the file's encoding (UTF-16LE, UTF-8 BOM, or UTF-8)
/// and existing lines (preserving exact original casing, comments, spaces, and formatting).
///
/// If an existing file cannot be read within [`MAX_CUSTOM_FILE_BYTES`] or exceeds [`MAX_CUSTOM_WORDS`],
/// an error is returned before modifying the in-memory dictionary or writing to disk, keeping
/// existing file contents intact.
pub fn save_custom_dictionary(path: &Path, removed: &[String]) -> Result<(), String> {
let path_str = path.to_string_lossy();
let mut encoding = DictEncoding::Utf8;
let removed_keys: HashSet<String> = removed.iter().filter_map(|w| wordcraft_proof::custom_word(w)).collect();
let mut out_lines: Vec<String> = Vec::new();
let mut existing_keys: HashSet<String> = HashSet::new();
if path.exists() {
let bytes = crate::io::read_file_capped(&path_str, MAX_CUSTOM_FILE_BYTES, "dictionary")?;
encoding = detect_file_encoding(&bytes);
let text = decode_dictionary_bytes(&bytes).map_err(|e| format!("{path_str}: {e}"))?;
let line_count = text.lines().count();
if line_count > MAX_CUSTOM_WORDS {
return Err(format!("{path_str}: dictionary exceeds limit of {MAX_CUSTOM_WORDS} words"));
}
for raw_line in text.lines() {
let line = raw_line.trim_matches(|c: char| c == '\r' || c == '\n');
let is_removed = removed.iter().any(|r| r == line || r.trim() == line)
|| wordcraft_proof::custom_word(line).is_some_and(|k| removed_keys.contains(&k));
if is_removed {
continue;
}
out_lines.push(line.to_string());
if let Some(k) = wordcraft_proof::custom_word(line) {
wordcraft_proof::add_word(&k);
existing_keys.insert(k);
} else {
existing_keys.insert(line.to_lowercase());
}
}
}
for w in removed {
wordcraft_proof::remove_word(w);
}
for w in wordcraft_proof::user_dictionary() {
if !existing_keys.contains(&w) && !removed_keys.contains(&w) {
out_lines.push(w.clone());
existing_keys.insert(w);
}
}
if out_lines.len() > MAX_CUSTOM_WORDS {
return Err(format!("Dictionary at '{}' exceeds maximum word limit ({})", path_str, MAX_CUSTOM_WORDS));
}
let bytes = encode_dictionary_words(&out_lines, encoding);
if bytes.len() as u64 > MAX_CUSTOM_FILE_BYTES {
return Err(format!("Dictionary at '{}' exceeds maximum file size ({} bytes)", path_str, MAX_CUSTOM_FILE_BYTES));
}
crate::io::write_file(&path_str, &bytes)
}
#[cfg(test)]
pub(crate) use tests::{DICT_TEST_LOCK, TestDir};
#[cfg(test)]
mod tests {
use super::*;
/// Test lock serializing tests that access the global proofing dictionary.
pub(crate) static DICT_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
/// RAII guard for temporary directories in dictionary tests.
pub(crate) struct TestDir(pub(crate) std::path::PathBuf);
impl TestDir {
/// Create a new unique temporary directory with the given prefix.
pub(crate) fn new(prefix: &str) -> Self {
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(0);
let count = COUNTER.fetch_add(1, Ordering::Relaxed);
let path = std::env::temp_dir().join(format!("wc-test-{prefix}-{}-{count}", std::process::id()));
let _ = std::fs::create_dir_all(&path);
TestDir(path)
}
/// Return a reference to the temporary directory path.
pub(crate) fn path(&self) -> &std::path::Path {
&self.0
}
}
impl Drop for TestDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// Test decoding UTF-16LE encoded bytes with a BOM.
#[test]
fn decodes_utf16le_with_bom() {
let mut bytes = vec![0xFF, 0xFE];
for c in "mameui\r\nfreestanding\r\n".encode_utf16() {
bytes.extend_from_slice(&c.to_le_bytes());
}
let text = decode_dictionary_bytes(&bytes).unwrap();
assert_eq!(text, "mameui\r\nfreestanding\r\n");
}
/// Test decoding UTF-8 bytes with a BOM.
#[test]
fn decodes_utf8_with_bom() {
let mut bytes = vec![0xEF, 0xBB, 0xBF];
bytes.extend_from_slice(b"retro\ncomputing\n");
let text = decode_dictionary_bytes(&bytes).unwrap();
assert_eq!(text, "retro\ncomputing\n");
}
/// Test decoding ASCII-only UTF-16LE bytes without a BOM.
#[test]
fn decodes_ascii_utf16le_without_bom() {
let mut bytes = Vec::new();
for c in "freestanding\r\nmameui\r\n".encode_utf16() {
bytes.extend_from_slice(&c.to_le_bytes());
}
let text = decode_dictionary_bytes(&bytes).unwrap();
assert_eq!(text, "freestanding\r\nmameui\r\n");
}
/// Test saving and loading a UTF-16LE dictionary file preserves encoding and content.
#[test]
fn save_and_load_utf16le_custom_dictionary() {
let _guard = DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let dir = TestDir::new("utf16");
let path = dir.path().join("custom.dic");
// Seed file with UTF-16LE data
let mut initial = vec![0xFF, 0xFE];
for c in "alpha\r\nbeta\r\n".encode_utf16() {
initial.extend_from_slice(&c.to_le_bytes());
}
std::fs::write(&path, initial).unwrap();
let added = load_custom_dictionary(&path).unwrap();
assert!(added.contains(&"alpha".to_string()));
assert!(added.contains(&"beta".to_string()));
// Add a new word and save
wordcraft_proof::add_word("gamma");
save_custom_dictionary(&path, &[]).unwrap();
let raw = std::fs::read(&path).unwrap();
assert_eq!(raw[0..2], [0xFF, 0xFE], "remains UTF-16LE with BOM");
let decoded = decode_dictionary_bytes(&raw).unwrap();
assert!(decoded.contains("alpha"));
assert!(decoded.contains("beta"));
assert!(decoded.contains("gamma"));
wordcraft_proof::remove_word("gamma");
}
/// Test saving and loading a UTF-16BE dictionary file preserves big-endian BOM and content.
#[test]
fn save_and_load_utf16be_custom_dictionary() {
let _guard = DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let dir = TestDir::new("utf16be");
let path = dir.path().join("custom_be.dic");
let mut initial = vec![0xFE, 0xFF];
for c in "alpha\r\nbeta\r\n".encode_utf16() {
initial.extend_from_slice(&c.to_be_bytes());
}
std::fs::write(&path, initial).unwrap();
let added = load_custom_dictionary(&path).unwrap();
assert!(added.contains(&"alpha".to_string()));
assert!(added.contains(&"beta".to_string()));
wordcraft_proof::add_word("gamma");
save_custom_dictionary(&path, &[]).unwrap();
let raw = std::fs::read(&path).unwrap();
assert_eq!(raw[0..2], [0xFE, 0xFF], "remains UTF-16BE with BOM");
let decoded = decode_dictionary_bytes(&raw).unwrap();
assert!(decoded.contains("alpha"));
assert!(decoded.contains("beta"));
assert!(decoded.contains("gamma"));
wordcraft_proof::remove_word("alpha");
wordcraft_proof::remove_word("beta");
wordcraft_proof::remove_word("gamma");
}
/// Test saving and loading an ASCII-only BOM-less UTF-16LE dictionary writes Word-compatible UTF-16LE with BOM.
#[test]
fn save_and_load_bomless_utf16le_custom_dictionary() {
let _guard = DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let dir = TestDir::new("bomless-utf16");
let path = dir.path().join("bomless.dic");
// Seed file with BOM-less UTF-16LE data
let mut initial = Vec::new();
for c in "alpha\r\nbeta\r\n".encode_utf16() {
initial.extend_from_slice(&c.to_le_bytes());
}
std::fs::write(&path, initial).unwrap();
let added = load_custom_dictionary(&path).unwrap();
assert!(added.contains(&"alpha".to_string()));
assert!(added.contains(&"beta".to_string()));
// Add a new word and save
wordcraft_proof::add_word("gamma");
save_custom_dictionary(&path, &[]).unwrap();
let raw = std::fs::read(&path).unwrap();
assert_eq!(raw[0..2], [0xFF, 0xFE], "saved with Word-compatible UTF-16LE BOM");
let decoded = decode_dictionary_bytes(&raw).unwrap();
assert!(decoded.contains("alpha"));
assert!(decoded.contains("beta"));
assert!(decoded.contains("gamma"));
wordcraft_proof::remove_word("gamma");
wordcraft_proof::remove_word("alpha");
wordcraft_proof::remove_word("beta");
}
/// Test that saving a custom dictionary merges external additions made on disk after loading.
#[test]
fn save_custom_dictionary_merges_external_additions() {
let _guard = DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let dir = TestDir::new("external-merge");
let path = dir.path().join("custom.dic");
std::fs::write(&path, "alpha\nbeta\n").unwrap();
let loaded = load_custom_dictionary(&path).unwrap();
assert_eq!(loaded, vec!["alpha".to_string(), "beta".to_string()]);
// External editor appends "externalword"
std::fs::write(&path, "alpha\nbeta\nexternalword\n").unwrap();
// In-session addition "internalword"
wordcraft_proof::add_word("internalword");
save_custom_dictionary(&path, &[]).unwrap();
let words = read_custom_dictionary_words(&path).unwrap();
assert!(words.contains(&"alpha".to_string()));
assert!(words.contains(&"beta".to_string()));
assert!(words.contains(&"externalword".to_string()), "external additions merged on save");
assert!(words.contains(&"internalword".to_string()), "internal additions preserved on save");
wordcraft_proof::remove_word("alpha");
wordcraft_proof::remove_word("beta");
wordcraft_proof::remove_word("externalword");
wordcraft_proof::remove_word("internalword");
}
/// Test that reading a custom dictionary rejects files exceeding the byte limit.
#[test]
fn read_custom_dictionary_words_rejects_file_over_byte_limit() {
let _guard = DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let dir = TestDir::new("read-overlimit");
let path = dir.path().join("oversized.dic");
let large_content = vec![b'a'; (MAX_CUSTOM_FILE_BYTES + 1024) as usize];
std::fs::write(&path, &large_content).unwrap();
let err1 = read_custom_dictionary_words(&path).unwrap_err();
assert!(err1.contains("larger than"));
let err2 = read_custom_dictionary_words_checked(&path).unwrap_err();
assert!(err2.contains("larger than"));
}
/// Test that parsing custom dictionary text enforces the maximum word limit.
#[test]
fn parse_dictionary_words_rejects_or_truncates_over_word_limit() {
let mut text = String::new();
for i in 0..MAX_CUSTOM_WORDS + 10 {
text.push_str(&format!("word{i}\n"));
}
// When path is provided for error reporting, returns an error.
let err = parse_dictionary_words(&text, Some("custom.dic")).unwrap_err();
assert!(err.contains(&format!("dictionary exceeds limit of {MAX_CUSTOM_WORDS} words")));
// When path is None, safely truncates at MAX_CUSTOM_WORDS.
let capped = parse_dictionary_words(&text, None).unwrap();
assert_eq!(capped.len(), MAX_CUSTOM_WORDS);
}
/// Test that decoding UTF-16LE bytes with an odd byte count returns an error.
#[test]
fn decode_dictionary_bytes_rejects_odd_byte_length_utf16le() {
let bytes = vec![0xFF, 0xFE, 0x61];
let err = decode_dictionary_bytes(&bytes).unwrap_err();
assert!(err.contains("odd byte length"));
}
/// Test that decoding UTF-16LE bytes with an unpaired surrogate returns an error.
#[test]
fn decode_dictionary_bytes_rejects_unpaired_surrogate_utf16le() {
let bytes = vec![0xFF, 0xFE, 0x00, 0xD8];
let err = decode_dictionary_bytes(&bytes).unwrap_err();
assert!(err.contains("unpaired surrogate"));
}
/// Test that decoding UTF-16BE bytes with an odd byte count returns an error.
#[test]
fn decode_dictionary_bytes_rejects_odd_byte_length_utf16be() {
let bytes = vec![0xFE, 0xFF, 0x61];
let err = decode_dictionary_bytes(&bytes).unwrap_err();
assert!(err.contains("odd byte length"));
}
/// Test that decoding UTF-16BE bytes with an unpaired surrogate returns an error.
#[test]
fn decode_dictionary_bytes_rejects_unpaired_surrogate_utf16be() {
let bytes = vec![0xFE, 0xFF, 0xD8, 0x00];
let err = decode_dictionary_bytes(&bytes).unwrap_err();
assert!(err.contains("unpaired surrogate"));
}
/// Test that clearing the user dictionary removes all words from memory.
#[test]
fn clear_user_dictionary_removes_all_words() {
let _guard = DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
clear_user_dictionary();
wordcraft_proof::add_word("tempclearwordone");
wordcraft_proof::add_word("tempclearwordtwo");
assert!(wordcraft_proof::user_dictionary().contains(&"tempclearwordone".to_string()));
clear_user_dictionary();
assert!(wordcraft_proof::user_dictionary().is_empty());
}
/// Test that save_custom_dictionary returns an error and preserves an existing file that
/// exceeds the maximum size limit.
#[test]
fn save_custom_dictionary_refuses_over_limit_file() {
let _guard = DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let dir = TestDir::new("overlimit");
let path = dir.path().join("oversized.dic");
let large_content = vec![b'a'; (MAX_CUSTOM_FILE_BYTES + 1024) as usize];
std::fs::write(&path, &large_content).unwrap();
wordcraft_proof::add_word("newword");
let result = save_custom_dictionary(&path, &[]);
assert!(result.is_err(), "should reject oversized dictionary file");
let read_back = std::fs::read(&path).unwrap();
assert_eq!(read_back.len(), large_content.len());
wordcraft_proof::remove_word("newword");
}
/// Test that read_custom_dictionary_words returns Ok(empty) on a missing file.
#[test]
fn read_custom_dictionary_words_returns_empty_on_missing_file() {
let _guard = DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let dir = TestDir::new("missing");
let path = dir.path().join("nonexistent.dic");
let words = read_custom_dictionary_words(&path).unwrap();
assert!(words.is_empty());
}
/// Test that save_custom_dictionary rejects writing when encoded output exceeds byte limit.
#[test]
fn save_custom_dictionary_refuses_when_output_exceeds_byte_limit() {
let _guard = DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
clear_user_dictionary();
struct ResetDict;
impl Drop for ResetDict {
fn drop(&mut self) {
clear_user_dictionary();
}
}
let _reset = ResetDict;
let dir = TestDir::new("oversized-output");
let path = dir.path().join("oversized.dic");
// Populate the in-memory custom dictionary with words that exceed MAX_CUSTOM_FILE_BYTES (4MB)
// while staying below MAX_CUSTOM_WORDS (100k) and keeping each word <= 64 chars.
// 70,000 words * 64 bytes (63 chars + '\n') = ~4.48 MB > 4 MB limit.
let word_count = 70_000;
let prefix = "a".repeat(58);
for i in 0..word_count {
wordcraft_proof::add_word(&format!("{prefix}{:05}", i));
}
let res = save_custom_dictionary(&path, &[]);
assert!(res.is_err(), "Expected save_custom_dictionary to reject oversized output");
let err = res.unwrap_err();
assert!(err.contains("exceeds maximum file size"), "Error message was: {err}");
assert!(!path.exists(), "File must not be written when output exceeds byte limit");
}
/// Test that save_custom_dictionary preserves original lines and casing (e.g. capitalized
/// entries like NASA, McDonald, multi-word lines, and lines exceeding 64 chars).
#[test]
fn save_custom_dictionary_preserves_original_lines_and_casing() {
let _guard = DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
clear_user_dictionary();
struct ResetDict;
impl Drop for ResetDict {
fn drop(&mut self) {
clear_user_dictionary();
}
}
let _reset = ResetDict;
let dir = TestDir::new("preserve-lines");
let path = dir.path().join("CUSTOM.DIC");
// Create an initial UTF-16LE dictionary matching Word's format with mixed casing,
// a multi-word line, and a line longer than 64 characters.
let over_64_chars = "a".repeat(70);
let content = format!("NASA\r\nMcDonald\r\ntwo words\r\n{over_64_chars}\r\n");
let mut initial_bytes = vec![0xFF, 0xFE];
for c in content.encode_utf16() {
initial_bytes.extend_from_slice(&c.to_le_bytes());
}
std::fs::write(&path, &initial_bytes).unwrap();
// Load the dictionary into proofing. Proofing parses valid words ("nasa", "mcdonald")
// and skips unparseable lines ("two words", 70-char line).
let loaded = load_custom_dictionary(&path).unwrap();
assert!(loaded.contains(&"nasa".to_string()));
assert!(loaded.contains(&"mcdonald".to_string()));
assert_eq!(loaded.len(), 2);
// Add a new word in session
wordcraft_proof::add_word("newword");
// Save back to the file
save_custom_dictionary(&path, &[]).unwrap();
// Verify file remains UTF-16LE with BOM
let saved_bytes = std::fs::read(&path).unwrap();
assert_eq!(saved_bytes[0..2], [0xFF, 0xFE]);
let decoded = decode_dictionary_bytes(&saved_bytes).unwrap();
// Original lines must preserve exact casing and unparsed content
assert!(decoded.contains("NASA\r\n"), "must preserve capitalized NASA");
assert!(decoded.contains("McDonald\r\n"), "must preserve mixed-case McDonald");
assert!(decoded.contains("two words\r\n"), "must preserve multi-word line");
assert!(decoded.contains(&format!("{over_64_chars}\r\n")), "must preserve line > 64 chars");
// Newly added word must be appended
assert!(decoded.contains("newword\r\n"), "must append new word");
// Now remove McDonald and save again
save_custom_dictionary(&path, &["McDonald".to_string()]).unwrap();
let after_remove = decode_dictionary_bytes(&std::fs::read(&path).unwrap()).unwrap();
assert!(after_remove.contains("NASA\r\n"), "NASA still retained");
assert!(!after_remove.contains("McDonald"), "McDonald removed");
assert!(after_remove.contains("two words\r\n"), "multi-word line still retained");
assert!(after_remove.contains(&format!("{over_64_chars}\r\n")), "line > 64 chars still retained");
assert!(after_remove.contains("newword\r\n"), "newword still retained");
}
/// Test that load_custom_dictionary_replacing replaces stale restored words on successful load,
/// but preserves in-memory words if the target file does not exist or fails to load.
#[test]
fn load_custom_dictionary_replacing_reconciles_stale_words() {
let _guard = DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let dir = TestDir::new("reconcile");
let path = dir.path().join("custom.dic");
clear_user_dictionary();
wordcraft_proof::add_word("stale_word");
assert!(wordcraft_proof::user_dictionary().contains(&"stale_word".to_string()));
// Non-existent file must return Err and not clear existing words
let nonexistent = dir.path().join("missing.dic");
let res = load_custom_dictionary_replacing(&nonexistent);
assert!(res.is_err(), "missing file must error");
assert!(wordcraft_proof::user_dictionary().contains(&"stale_word".to_string()), "must preserve words on missing file");
// Existing file must replace stale words with its own words
std::fs::write(&path, "fresh_word\r\n").unwrap();
let loaded = load_custom_dictionary_replacing(&path).unwrap();
assert_eq!(loaded, vec!["fresh_word".to_string()]);
let in_memory = wordcraft_proof::user_dictionary();
assert!(in_memory.contains(&"fresh_word".to_string()), "must contain fresh word");
assert!(!in_memory.contains(&"stale_word".to_string()), "must have cleared stale word");
clear_user_dictionary();
}
}
+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>,
+92 -1
View File
@@ -53,7 +53,7 @@ pub fn is_word_package(ext: &str) -> bool {
}
/// How a copy in another format is written.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ExportOptions {
/// Print Markup: PDFs show tracked changes marked up and, with `comments`, each page scaled
/// down beside a markup area with the comments in balloons (page images get the area too);
@@ -66,6 +66,9 @@ pub struct ExportOptions {
pub word2003: bool,
/// How digits look in PDFs and page images (the Numeral setting, `System` resolved).
pub numeral: wordcraft_layout::NumeralMode,
/// How tracked changes are marked in PDFs and page images (Track Changes Options): the
/// insertion and deletion marks and colours the screen shows (#5232).
pub revisions: wordcraft_layout::display::MarkupOptions,
/// A PDF or page image is written only if nothing in it is silently missing (a character no
/// face can draw, a picture that is missing or can't be decoded); else the save fails with
/// `strict: …` (#6005). Ignored for other formats.
@@ -729,6 +732,94 @@ pub fn read_file_head(path: &str, max: u64) -> Result<Vec<u8>, String> {
Ok(head)
}
/// Web fallback for [`read_file_capped`] and [`read_file_head`], returning an error explaining
/// that files are opened through the browser on the web.
pub fn wasm_read_file_fallback(path: &str) -> Result<Vec<u8>, String> {
Err(format!("{path}: files are opened through the browser on the web"))
}
/// Web fallback for [`read_file_capped`].
#[cfg(target_arch = "wasm32")]
pub fn read_file_capped(path: &str, _max: u64, _what: &str) -> Result<Vec<u8>, String> {
wasm_read_file_fallback(path)
}
/// Web fallback for [`read_file_head`].
#[cfg(target_arch = "wasm32")]
pub fn read_file_head(path: &str, _max: u64) -> Result<Vec<u8>, String> {
wasm_read_file_fallback(path)
}
/// Classification of file validation errors for configuration settings.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FileCheckError {
/// Automation access violation or I/O error.
Access(String),
/// The target path is a directory instead of a regular file.
IsDirectory(String),
/// The target path is a symbolic link instead of a regular file.
IsSymlink(String),
/// The path does not exist or is not a regular file.
NotFound(String),
/// The file exceeds the permitted size limit.
TooLarge(String),
}
impl std::fmt::Display for FileCheckError {
/// Format the file check error message.
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Access(s) | Self::IsDirectory(s) | Self::IsSymlink(s) | Self::NotFound(s) | Self::TooLarge(s) => f.write_str(s),
}
}
}
/// Check that `path` is an accessible regular file within `max` bytes.
///
/// Ensures the path is within automation read and write roots, exists, is not a symbolic link,
/// is not a directory, is a regular writable file, and does not exceed `max` bytes.
#[cfg(not(target_arch = "wasm32"))]
pub fn check_regular_file_setting(path: &std::path::Path, max: u64, key: &str) -> Result<(), FileCheckError> {
crate::file_access::check_read(&path.to_string_lossy()).map_err(FileCheckError::Access)?;
crate::file_access::check_write(&path.to_string_lossy()).map_err(FileCheckError::Access)?;
let sym_meta = match std::fs::symlink_metadata(path) {
Ok(m) => m,
Err(e) => return Err(FileCheckError::Access(format!("{}: {e}", path.display()))),
};
if sym_meta.file_type().is_symlink() {
return Err(FileCheckError::IsSymlink(format!("`{key}`: {} is a symbolic link, not a regular file", path.display())));
}
let meta = match std::fs::metadata(path) {
Ok(m) => m,
Err(e) => return Err(FileCheckError::Access(format!("{}: {e}", path.display()))),
};
if meta.is_dir() {
return Err(FileCheckError::IsDirectory(format!("`{key}`: {} is a folder, not a file", path.display())));
}
if !meta.is_file() {
return Err(FileCheckError::NotFound(format!("no file at {}", path.display())));
}
if meta.len() > max {
return Err(FileCheckError::TooLarge(format!("{} is larger than the custom dictionary limit", path.display())));
}
if meta.permissions().readonly() {
return Err(FileCheckError::Access(format!("{}: file is read-only", path.display())));
}
let mut open = std::fs::OpenOptions::new();
open.write(true);
// A named pipe swapped in after the metadata check would block `open`; non-blocking fails it at once.
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::custom_flags(&mut open, libc::O_NONBLOCK);
open.open(path).map_err(|e| FileCheckError::Access(format!("{}: {e}", path.display())))?;
Ok(())
}
/// Web fallback for [`check_regular_file_setting`].
#[cfg(target_arch = "wasm32")]
pub fn check_regular_file_setting(path: &std::path::Path, _max: u64, _key: &str) -> Result<(), FileCheckError> {
Err(FileCheckError::Access(format!("{}: files are opened through the browser on the web", path.display())))
}
/// An entry of [`list_dir`]: a file or folder (links followed).
#[cfg(not(target_arch = "wasm32"))]
#[derive(Clone, Debug)]
+56 -2
View File
@@ -98,6 +98,15 @@ pub fn save(ext: &str, doc: &Document, opts: &crate::io::ExportOptions) -> Optio
}
}
/// How a page image is drawn: the printed page, headers and footers at full strength, tracked
/// changes marked as Track Changes Options mark them. One place for `file.exportPng`,
/// `file.strictReport`'s page check and a downloaded page image.
pub(crate) fn page_image_options(opts: &crate::io::ExportOptions) -> wordcraft_render::RenderOptions {
let mut ro = wordcraft_render::RenderOptions { display: crate::strict::png_display(), ..Default::default() };
ro.display.revisions = opts.revisions.clone();
ro
}
/// Render page `page` as PNG at `scale` px/pt. With Print Markup's comments the page has its
/// markup area with the comments in balloons (page images always show tracked changes).
pub fn render_png(doc: &Document, page: usize, scale: f32, opts: &crate::io::ExportOptions) -> Result<Vec<u8>, String> {
@@ -105,6 +114,7 @@ pub fn render_png(doc: &Document, page: usize, scale: f32, opts: &crate::io::Exp
let doc = out.as_ref().unwrap_or(doc);
let lo = wordcraft_layout::LayoutOptions {
comment_balloons: opts.markup && opts.comments,
hide_marked: opts.revisions.hidden_deletions(),
numeral: opts.numeral,
output_page_refs: true,
bookmark_error: crate::locale::bookmark_error(),
@@ -113,11 +123,55 @@ pub fn render_png(doc: &Document, page: usize, scale: f32, opts: &crate::io::Exp
let l = wordcraft_layout::layout(doc, &mut wordcraft_layout::LayoutCache::new(), &lo);
let p = l.pages.get(page).ok_or_else(|| format!("no page {}", page + 1))?;
if opts.strict {
let report = crate::strict::strict_report(doc, &l, &crate::strict::png_display(), Some(page..=page), wordcraft_layout::StrictOutput::Png);
let display = page_image_options(opts).display;
let report = crate::strict::strict_report(doc, &l, &display, Some(page..=page), wordcraft_layout::StrictOutput::Png);
if !report.passed() {
return Err(report.refusal());
}
}
let img = wordcraft_render::render_page(doc, p, scale, &Default::default());
let img = wordcraft_render::render_page(doc, p, scale, &page_image_options(opts));
Ok(img.to_png())
}
#[cfg(test)]
mod tests {
use super::*;
/// A page image is the printed page: headers and footers draw at full strength (#6267).
#[test]
fn a_page_image_draws_headers_at_full_strength() {
let opts = crate::io::ExportOptions::default();
let ro = page_image_options(&opts);
assert!(!ro.display.dim_header, "a page image is the printed page");
assert_eq!(ro.display.revisions, opts.revisions, "the Track Changes Options reach the image");
let mut d = Document::from_text("body");
let png = wordcraft_geom::picture::encode_format(
&image::DynamicImage::from(image::RgbaImage::from_pixel(4, 4, image::Rgba([200, 0, 0, 255]))),
image::ImageFormat::Png,
)
.unwrap();
let media = d.add_media(png, "png");
let mut hp = wordcraft_doc::Paragraph::new();
let obj = wordcraft_doc::para::InlineObject::Image {
media,
w: 40.0,
h: 40.0,
alt: String::new(),
float: Default::default(),
crop: [0.0; 4],
fx: Default::default(),
ole: None,
};
hp.insert_object(0, obj, &Default::default()).unwrap();
let id = d.add_part(wordcraft_doc::PartKind::Header, vec![wordcraft_doc::para_block(hp)]);
d.last_section.headers.default = Some(id);
let rendered = render_png(&d, 0, 1.0, &opts).unwrap();
let l = wordcraft_layout::layout(&d, &mut wordcraft_layout::LayoutCache::new(), &wordcraft_layout::LayoutOptions::default());
let full = wordcraft_render::render_page(&d, &l.pages[0], 1.0, &ro).to_png();
let dimmed = wordcraft_render::render_page(&d, &l.pages[0], 1.0, &wordcraft_render::RenderOptions::default()).to_png();
assert_eq!(rendered, full, "render_png draws headers at full strength");
assert_ne!(rendered, dimmed, "render_png does not dim headers");
}
}
+1
View File
@@ -8,6 +8,7 @@
pub mod catalog;
pub mod cmd;
pub mod custom_dict;
pub(crate) mod doc_state;
pub mod file_access;
pub(crate) mod ime;
+5
View File
@@ -41,6 +41,9 @@ pub struct Prefs {
/// Language, #1063): an app started from Finder or the Dock doesn't see
/// `WORDCRAFT_DICTIONARIES`. `None` means no configured folder.
pub dictionaries_folder: Option<String>,
/// A custom dictionary file (.dic or plain text) used for custom words (File › Options › Proofing, #5840).
/// `None`: the default `custom-dictionary.txt` in the settings folder.
pub custom_dictionary: Option<String>,
/// The user templates folder File › New lists personal templates from and Save as Word
/// Template starts in (File › Options › Advanced › File locations, #2852). `None`: the app's
/// own `Templates` folder in its settings folder.
@@ -65,6 +68,7 @@ pub struct Prefs {
}
impl Default for Prefs {
/// Default preference values.
fn default() -> Self {
Prefs {
paper_color: Default::default(),
@@ -77,6 +81,7 @@ impl Default for Prefs {
units: Default::default(),
region: None,
dictionaries_folder: None,
custom_dictionary: None,
user_templates_folder: None,
marks: Default::default(),
mark_grammar: true,
+4 -1
View File
@@ -221,7 +221,7 @@ impl Session {
let markup = crate::cmd::file::export_options(self, v);
let out = crate::cmd::references::output_fields(&self.doc);
let doc = out.as_ref().unwrap_or(&self.doc);
let lay = self.export_layout_of(doc, markup.markup);
let lay = self.output_layout_of(doc, markup.markup, !markup.markup);
let plan = plan(v, lay.pages.len(), self.current_pages(&lay))?;
let mut single = v.clone();
single["copies"] = json!(1);
@@ -238,6 +238,9 @@ impl Session {
comments: markup.comments,
paper,
links,
numeral: markup.numeral,
revisions: markup.revisions.clone(),
compress: p::bool(v, "compress").unwrap_or(true),
..Default::default()
};
let bytes = wordcraft_pdf::export_layout(doc, &lay, &opts).map_err(|e| CmdError::Failed(e.to_string()))?;
+8
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>,
@@ -63,6 +68,9 @@ pub struct Session {
/// `None`, so an agent's words stay in memory and never change the person's dictionary.
/// Add to Dictionary and File › Options › Proofing save through it (#40).
pub user_dict_path: Option<std::path::PathBuf>,
/// The default user dictionary path wired up by the host (usually `custom-dictionary.txt` in
/// the settings directory), used when [`Prefs::custom_dictionary`] is reset to auto (#5840).
pub default_user_dict_path: Option<std::path::PathBuf>,
pub clipboard: Option<Fragment>,
/// A tracked cut the next paste can turn into a move (see `cmd::moves`).
pub pending_move: Option<crate::cmd::moves::PendingMove>,
+6
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: _,
@@ -250,6 +253,7 @@ impl Session {
// Names the document it belongs to, so it never applies to another one.
review_style: _,
user_dict_path: _,
default_user_dict_path: _,
clipboard: _,
clipboard_text: _,
clipboard_html: _,
@@ -303,6 +307,7 @@ impl Session {
sel,
view,
pending,
pending_at,
path,
file_name,
dirty,
@@ -352,6 +357,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));
+20 -4
View File
@@ -168,16 +168,32 @@ impl Session {
/// area with the comments in balloons. Fields Word fills in for output show their fresh
/// results ([`crate::cmd::references::output_fields`]).
pub fn export_layout_with(&self, markup: bool) -> Arc<DocLayout> {
let out = crate::cmd::references::output_fields(&self.doc);
self.export_layout_of(out.as_ref().unwrap_or(&self.doc), markup)
self.output_layout(markup, false)
}
/// [`Session::export_layout_with`] of `doc`, this document as it is output.
pub(crate) fn export_layout_of(&self, doc: &Document, markup: bool) -> Arc<DocLayout> {
/// The layout a print job draws ([`Session::print_pdf`]): with `markup` as
/// [`Session::export_layout_with`]; without it the final text, as Word's "No Markup", so tracked
/// deletions, which the job doesn't draw, take no space either, whatever Track Changes
/// Options say. Page images keep [`Session::export_layout_with`]: they always show markup.
pub fn print_layout(&self, markup: bool) -> Arc<DocLayout> {
self.output_layout(markup, !markup)
}
/// The print-view layout for output; `final_text` leaves tracked deletions out.
fn output_layout(&self, markup: bool, final_text: bool) -> Arc<DocLayout> {
let out = crate::cmd::references::output_fields(&self.doc);
self.output_layout_of(out.as_ref().unwrap_or(&self.doc), markup, final_text)
}
/// [`Session::output_layout`] of `doc`, this document as it is output; `final_text` leaves tracked deletions out.
pub(crate) fn output_layout_of(&self, doc: &Document, markup: bool, final_text: bool) -> Arc<DocLayout> {
let (fn_name, fn_path) = self.resolved_filenames();
let opts = LayoutOptions {
view: ViewMode::Print,
hide_deleted: final_text,
comment_balloons: markup && self.prefs.markup.comments,
// Deletions Track Changes Options mark Hidden take no space, as on screen.
hide_marked: self.prefs.markup.hidden_deletions(),
numeral: self.view.numeral.resolve(SYSTEM_LOCALE.get().map(String::as_str)),
filename: Some(Arc::from(fn_name.as_str())),
filepath: Some(Arc::from(fn_path.as_str())),
+4 -1
View File
@@ -22,7 +22,7 @@ impl Session {
let name = path.to_string_lossy();
if let Err(e) = crate::file_access::check_read(&name)
.and_then(|()| crate::file_access::check_write(&name))
.and_then(|()| wordcraft_proof::save_user_dictionary(path, removed).map_err(|e| e.to_string()))
.and_then(|()| crate::custom_dict::save_custom_dictionary(path, removed))
{
log::warn!("custom dictionary: save failed: {e}");
}
@@ -41,6 +41,7 @@ impl Session {
sel,
view,
pending,
pending_at,
path,
file_name,
dirty,
@@ -91,10 +92,12 @@ impl Session {
sel,
view,
pending,
pending_at,
last_highlight: wordcraft_doc::props::Highlight::Yellow,
path,
file_name,
user_dict_path: None,
default_user_dict_path: None,
dirty,
clipboard: None,
pending_move,
+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,
+12 -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,12 +72,14 @@ impl Session {
doc,
sel,
view: _,
pending: _,
pending,
pending_at,
last_highlight: _,
path: _,
file_name: _,
// The custom dictionary file, like the file path: host wiring, not an edit.
user_dict_path: _,
default_user_dict_path: _,
dirty,
clipboard: _,
// Like the clipboard: what the next paste can make a move of.
@@ -181,6 +184,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 +201,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 +230,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,
+1
View File
@@ -197,6 +197,7 @@ pub(crate) fn pdf_options(opts: &ExportOptions) -> wordcraft_pdf::PdfOptions {
include_markup: opts.markup,
comments: opts.markup && opts.comments,
numeral: opts.numeral,
revisions: opts.revisions.clone(),
bookmark_error: crate::locale::bookmark_error(),
..Default::default()
}
+349
View File
@@ -265,6 +265,7 @@ fn reset_shortcuts_remove_direct_formatting_but_keep_styles() {
#[test]
fn custom_dictionary_words_persist_through_their_file() {
let _guard = crate::custom_dict::DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
// #40: adding a word through a command writes it to the session's file, and loading
// that file makes the word known (only the desktop app wires this up).
let dir = std::env::temp_dir().join(format!("wc-engdict-{}", std::process::id()));
@@ -292,6 +293,7 @@ fn custom_dictionary_words_persist_through_their_file() {
#[test]
fn confined_sessions_neither_save_the_dictionary_nor_choose_folders_outside_their_roots() {
let _guard = crate::custom_dict::DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
// #3737 (findings 34 and WC-35): the custom dictionary file and the folder settings are
// held to the automation roots like any other path.
let base = scratch_dir("dict-roots");
@@ -305,6 +307,7 @@ fn confined_sessions_neither_save_the_dictionary_nor_choose_folders_outside_thei
let confined = |s: &mut Session, cmd: &str, v: serde_json::Value| crate::file_access::confine(roots.as_ref(), || s.run(cmd, &v));
assert!(confined(&mut s, "review.addToDictionary", json!({"word": "zxqengconfined"})).is_ok());
assert!(wordcraft_proof::user_dictionary().contains(&"zxqengconfined".to_string()), "kept in memory");
wordcraft_proof::remove_word("zxqengconfined");
assert!(!outside.exists(), "nothing written outside the write root");
for key in ["dictionariesFolder", "userTemplatesFolder"] {
assert!(confined(&mut s, "file.options", json!({key: base.join("outside").to_string_lossy()})).is_err(), "{key}");
@@ -319,6 +322,7 @@ fn confined_sessions_neither_save_the_dictionary_nor_choose_folders_outside_thei
#[test]
fn add_to_dictionary_takes_only_words_the_file_keeps() {
let _guard = crate::custom_dict::DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
// #40: the same rule as loading the dictionary file, so nothing added is dropped on the next load.
let mut s = s();
for bad in ["two words", "tab\tword", "bell\u{7}", &"x".repeat(65)] {
@@ -327,6 +331,202 @@ fn add_to_dictionary_takes_only_words_the_file_keeps() {
}
run(&mut s, "review.addToDictionary", json!({"word": " zxqengtrimmed "}));
assert!(wordcraft_proof::user_dictionary().contains(&"zxqengtrimmed".to_string()));
wordcraft_proof::remove_word("zxqengtrimmed");
}
/// #5840: WordCraft supports choosing a freestanding custom.dic dictionary file (including
/// UTF-16LE with BOM as written by Microsoft Word), using it in conjunction with the main
/// dictionary, and persisting additions back to it in the same encoding.
#[test]
fn custom_dictionary_freestanding_file_option() {
let _guard = crate::custom_dict::DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let dir = crate::custom_dict::TestDir::new("custom-dic");
let dic_path = dir.path().join("custom.dic");
// Write a freestanding UTF-16LE dictionary file with BOM, as Word saves it on Windows.
let mut initial_bytes = vec![0xFF, 0xFE];
for u in "freestandingword\r\nmameui\r\n".encode_utf16() {
initial_bytes.extend_from_slice(&u.to_le_bytes());
}
std::fs::write(&dic_path, &initial_bytes).unwrap();
let mut s = s();
let default_path = dir.path().join("default.txt");
s.default_user_dict_path = Some(default_path.clone());
s.user_dict_path = Some(default_path.clone());
// Seed default dictionary with a default word.
std::fs::write(&default_path, "defaultword\n").unwrap();
crate::custom_dict::load_custom_dictionary(&default_path).unwrap();
assert!(wordcraft_proof::is_correct("defaultword"));
// Before binding, the word is unknown.
assert!(!wordcraft_proof::is_correct("freestandingword"));
// Set customDictionary in file.options: removes previous words and loads custom.dic.
let res = s.run("file.options", &json!({"customDictionary": dic_path.to_string_lossy()})).unwrap();
assert_eq!(res["customDictionary"], json!(dic_path.to_string_lossy()));
assert_eq!(s.prefs.custom_dictionary.as_deref(), Some(dic_path.to_string_lossy().as_ref()));
assert_eq!(s.user_dict_path.as_ref(), Some(&dic_path));
assert!(!wordcraft_proof::is_correct("defaultword"), "previous words removed on switch");
assert!(wordcraft_proof::is_correct("freestandingword"));
assert!(wordcraft_proof::is_correct("mameui"));
// Add a new word via review.addToDictionary: it persists back to custom.dic in UTF-16LE.
run(&mut s, "review.addToDictionary", json!({"word": "zxqaddedword"}));
let saved_raw = std::fs::read(&dic_path).unwrap();
assert_eq!(saved_raw[0..2], [0xFF, 0xFE], "persists as UTF-16LE with BOM");
let decoded = crate::custom_dict::decode_dictionary_bytes(&saved_raw).unwrap();
assert!(decoded.contains("freestandingword"));
assert!(decoded.contains("zxqaddedword"));
// Revert to "auto": removes custom dictionary words and restores default path.
s.run("file.options", &json!({"customDictionary": "auto"})).unwrap();
assert_eq!(s.prefs.custom_dictionary, None);
assert_eq!(s.user_dict_path.as_ref(), Some(&default_path));
assert!(!wordcraft_proof::is_correct("freestandingword"), "freestanding words removed on revert");
assert!(!wordcraft_proof::is_correct("zxqaddedword"));
assert!(wordcraft_proof::is_correct("defaultword"), "default words restored");
// Setting customDictionary to "auto" when user_dict_path is already default_path
// updates s.prefs.custom_dictionary even if it previously held a stale path.
s.prefs.custom_dictionary = Some("/stale/nonexistent.dic".to_string());
s.run("file.options", &json!({"customDictionary": "auto"})).unwrap();
assert_eq!(s.prefs.custom_dictionary, None);
// Clean up test words from proofing dictionary
wordcraft_proof::remove_word("defaultword");
// Reject nonexistent files, folders, relative paths, or oversized files.
assert!(s.run("file.options", &json!({"customDictionary": dir.path().join("missing.dic").to_string_lossy()})).is_err());
let dir_err = s.run("file.options", &json!({"customDictionary": dir.path().to_string_lossy()})).unwrap_err();
assert!(format!("{dir_err:?}").contains("is a folder, not a file"));
let rel_err = s.run("file.options", &json!({"customDictionary": "relative/custom.dic"})).unwrap_err();
assert!(format!("{rel_err:?}").contains("isn't a full path"));
// Accept ~/ path expansion when HOME points to a directory.
if let Some(home) = std::env::var_os("HOME").filter(|h| !h.is_empty()) {
let home_dir = std::path::PathBuf::from(home);
let test_name = format!(".wordcraft-test-tilde-{}.dic", std::process::id());
let tilde_file = home_dir.join(&test_name);
struct CleanFile(std::path::PathBuf);
impl Drop for CleanFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
let mut opts = std::fs::OpenOptions::new();
opts.write(true).create_new(true);
if let Ok(mut f) = opts.open(&tilde_file) {
use std::io::Write;
let _ = f.write_all(b"tildeword\n");
let _cleaner = CleanFile(tilde_file.clone());
let tilde_res = s.run("file.options", &json!({"customDictionary": format!("~/{test_name}")}));
assert!(tilde_res.is_ok(), "tilde expansion succeeds: {:?}", tilde_res.err());
assert_eq!(s.prefs.custom_dictionary.as_deref(), Some(tilde_file.to_string_lossy().as_ref()));
assert!(wordcraft_proof::is_correct("tildeword"));
s.run("file.options", &json!({"customDictionary": "auto"})).unwrap();
wordcraft_proof::remove_word("tildeword");
wordcraft_proof::remove_word("defaultword");
}
}
let huge_dic = dir.path().join("huge.dic");
std::fs::write(&huge_dic, vec![b'a'; (crate::custom_dict::MAX_CUSTOM_FILE_BYTES + 1024) as usize]).unwrap();
assert!(s.run("file.options", &json!({"customDictionary": huge_dic.to_string_lossy()})).is_err());
assert_eq!(s.prefs.custom_dictionary, None, "oversized dictionary rejects without changing prefs");
wordcraft_proof::remove_word("defaultword");
}
/// #5840 review: a dictionary that passes the metadata and access checks but can't be decoded
/// refuses the whole `file.options` call before any setting is applied, so a combined call leaves
/// the preferences, the bound path and the proofing words as they were.
#[test]
fn refused_custom_dictionary_leaves_every_other_option_unchanged() {
let _guard = crate::custom_dict::DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let dir = crate::custom_dict::TestDir::new("custom-dic-refused");
let bound = dir.path().join("custom.dic");
std::fs::write(&bound, "boundword\n").unwrap();
// A lone 0xFF byte is neither UTF-8 nor a UTF-16LE BOM pair: the file is a readable, writable
// regular file, so only decoding refuses it.
let bad = dir.path().join("bad.dic");
std::fs::write(&bad, [b'h', b'i', 0xFF]).unwrap();
let mut s = s();
s.default_user_dict_path = Some(dir.path().join("custom-dictionary.txt"));
run(
&mut s,
"file.options",
json!({
"author": "Ada",
"initials": "AL",
"units": "centimeters",
"region": "pl-PL",
"dictionariesFolder": dir.path().to_string_lossy(),
"customDictionary": bound.to_string_lossy(),
"markGrammar": true,
"checkSpelling": true,
}),
);
assert!(wordcraft_proof::is_correct("boundword"));
let before = cmd::options::current(&s);
let err = s
.run(
"file.options",
&json!({
"author": "Grace",
"initials": "GH",
"units": "inches",
"region": "en-US",
"dictionariesFolder": "auto",
"customDictionary": bad.to_string_lossy(),
"markGrammar": false,
"checkSpelling": false,
"addWords": ["zxqrefusedword"],
}),
)
.unwrap_err();
assert!(format!("{err:?}").contains("malformed"), "reports the decode failure: {err:?}");
assert_eq!(cmd::options::current(&s), before, "a refused dictionary changes no setting");
assert_eq!(s.user_dict_path.as_ref(), Some(&bound), "the bound dictionary stays");
assert!(!wordcraft_proof::is_correct("zxqrefusedword"), "the refused call adds no words");
// `auto` decodes the default file before applying too, so a malformed default file is refused
// the same way and its companion settings stay as they were.
let default_path = dir.path().join("custom-dictionary.txt");
std::fs::write(&default_path, [b'x', 0xFF]).unwrap();
let before = cmd::options::current(&s);
let err = s.run("file.options", &json!({"customDictionary": "auto", "units": "points"})).unwrap_err();
assert!(format!("{err:?}").contains("malformed"), "reports the decode failure: {err:?}");
assert_eq!(cmd::options::current(&s), before, "a malformed default dictionary changes no setting");
assert_eq!(s.prefs.custom_dictionary.as_deref(), Some(bound.to_string_lossy().as_ref()));
wordcraft_proof::remove_word("boundword");
}
#[cfg(unix)]
#[test]
fn custom_dictionary_rejects_symlink_and_readonly_files() {
let _guard = crate::custom_dict::DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let dir = crate::custom_dict::TestDir::new("custom-dic-symlink");
let dic_path = dir.path().join("custom.dic");
std::fs::write(&dic_path, "word\n").unwrap();
let mut s = s();
let symlink_path = dir.path().join("symlink.dic");
let _ = std::os::unix::fs::symlink(&dic_path, &symlink_path);
let link_err = s.run("file.options", &json!({"customDictionary": symlink_path.to_string_lossy()})).unwrap_err();
assert!(format!("{link_err:?}").contains("is a symbolic link"));
let ro_path = dir.path().join("readonly.dic");
std::fs::write(&ro_path, "word\n").unwrap();
let mut perms = std::fs::metadata(&ro_path).unwrap().permissions();
perms.set_readonly(true);
let _ = std::fs::set_permissions(&ro_path, perms);
let ro_err = s.run("file.options", &json!({"customDictionary": ro_path.to_string_lossy()})).unwrap_err();
let ro_msg = format!("{ro_err:?}");
assert!(ro_msg.contains("read-only") || ro_msg.contains("Permission denied"));
}
#[test]
@@ -1675,6 +1875,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
@@ -6500,6 +6720,21 @@ fn file_capped_read_refuses_content_over_the_cap() {
assert_eq!(whole.unwrap().len(), 100);
}
/// Web fallback for `read_file_capped` and `read_file_head` returns the expected browser error.
#[test]
fn wasm_read_file_fallback_returns_browser_error() {
let err = crate::io::wasm_read_file_fallback("sample.dic").unwrap_err();
assert!(err.contains("files are opened through the browser on the web"));
}
/// #5840: On wasm32 targets, `read_file_capped` and `read_file_head` return the browser fallback error.
#[cfg(target_arch = "wasm32")]
#[test]
fn wasm_target_read_file_capped_and_head_return_browser_error() {
assert!(crate::io::read_file_capped("test.dic", 1024, "dictionary").unwrap_err().contains("browser on the web"));
assert!(crate::io::read_file_head("test.dic", 1024).unwrap_err().contains("browser on the web"));
}
/// #3666: `read_regular_file_within` (Paste Special's copied picture file) reads a file of up to
/// `limit` bytes whole and refuses one whose handle reports more, before reading any of it.
#[cfg(not(target_arch = "wasm32"))]
@@ -8580,6 +8815,113 @@ fn insert_icon_places_a_picture_of_the_requested_size_that_saves_and_recolours()
assert!(s.run("picture.iconColor", &json!({})).is_err());
}
/// #5232: a PDF with markup (file.exportPdf, file.printPdf) marks tracked changes in the Track
/// Changes Options colours, not always by author.
#[test]
fn markup_pdf_takes_the_track_changes_option_colours() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Governed by Kansas law."));
s.run("review.trackChanges", &json!({"value": true})).unwrap();
s.run("select.text", &json!({"text": "Kansas"})).unwrap();
s.run("text.insert", &json!({"text": "Missouri"})).unwrap();
let markup = json!({"markup": true});
let uncompressed_markup = json!({"markup": true, "compress": false});
let pdf = |s: &Session| crate::io::save_bytes_opts("x.pdf", &s.doc, &cmd::file::export_options(s, &markup)).unwrap();
let print = |s: &Session| s.print_pdf(&markup).unwrap().0;
let (by_author, printed_by_author) = (pdf(&s), print(&s));
// Exports are deterministic, so differences are solely due to the colours.
assert_eq!(pdf(&s), by_author, "pdf export must be deterministic");
assert_eq!(print(&s), printed_by_author, "print_pdf must be deterministic");
let has = |t: &[&str], op: &str| {
let want: Vec<_> = op.split_ascii_whitespace().collect();
t.windows(want.len()).any(|w| w == want.as_slice())
};
let by_author_print_uncompressed = s.print_pdf(&uncompressed_markup).unwrap().0;
let by_author_print_raw = String::from_utf8_lossy(&by_author_print_uncompressed);
let by_author_print_tokens: Vec<_> = by_author_print_raw.split_ascii_whitespace().collect();
assert!(!has(&by_author_print_tokens, "0 0 1 rg") && !has(&by_author_print_tokens, "1 0 0 rg"), "by-author print has no pure blue or red");
s.run("review.trackingOptions", &json!({"insertColor": "0000FF", "deleteColor": "FF0000"})).unwrap();
let opts = cmd::file::export_options(&s, &markup);
assert_eq!(opts.revisions.insert_color, Some(wordcraft_doc::props::Rgb(0, 0, 255)));
assert_eq!(opts.revisions.delete_color, Some(wordcraft_doc::props::Rgb(255, 0, 0)));
let coloured_pdf = pdf(&s);
let coloured_print = print(&s);
assert_ne!(coloured_pdf, by_author, "file.exportPdf ignores the tracking colours");
assert_ne!(coloured_print, printed_by_author, "file.printPdf ignores the tracking colours");
let coloured_print_uncompressed = s.print_pdf(&uncompressed_markup).unwrap().0;
let print_raw = String::from_utf8_lossy(&coloured_print_uncompressed);
let print_tokens: Vec<_> = print_raw.split_ascii_whitespace().collect();
assert!(has(&print_tokens, "0 0 1 rg"), "coloured print_pdf has blue operator for insertion");
assert!(has(&print_tokens, "1 0 0 rg"), "coloured print_pdf has red operator for deletion");
}
/// #5232 review: File › Print without Print Markup leaves out tracked deletions in layout,
/// so the page count matches the PDF export and deletions take no blank space.
#[test]
fn print_jobs_without_markup_lay_out_the_final_text() {
let text: Vec<String> = (0..200).map(|i| format!("Line {i} of the original agreement")).collect();
let mut s = Session::new(wordcraft_doc::Document::from_text(&text.join("\n")));
s.run("review.trackChanges", &json!({"value": true})).unwrap();
s.run("select.all", &json!({})).unwrap();
s.run("text.insert", &json!({"text": "Replaced"})).unwrap();
// With markup: 200 deleted lines take space in print.
let (marked_pdf, marked_plan) = s.print_pdf(&json!({"markup": true})).unwrap();
assert!(marked_plan.chosen > 1);
assert!(marked_pdf.starts_with(b"%PDF-"));
// Without markup: final text only, 1 page.
let (plain_pdf, plain_plan) = s.print_pdf(&json!({"markup": false})).unwrap();
assert_eq!(plain_plan.chosen, 1);
assert!(plain_pdf.starts_with(b"%PDF-"));
}
/// #5232 review: page images (render_png and file.exportPng) respect Track Changes Options
/// colours and hidden deletions.
#[test]
fn markup_png_takes_the_track_changes_option_colours() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Governed by Kansas law."));
s.run("review.trackChanges", &json!({"value": true})).unwrap();
s.run("select.text", &json!({"text": "Kansas"})).unwrap();
s.run("text.insert", &json!({"text": "Missouri"})).unwrap();
let markup_opts = json!({"markup": true});
let by_author_opts = cmd::file::export_options(&s, &markup_opts);
let by_author_png = crate::io_ext::render_png(&s.doc, 0, 1.0, &by_author_opts).unwrap();
// Change tracking options to blue insertions / red deletions.
s.run("review.trackingOptions", &json!({"insertColor": "0000FF", "deleteColor": "FF0000"})).unwrap();
let coloured_opts = cmd::file::export_options(&s, &markup_opts);
let coloured_png = crate::io_ext::render_png(&s.doc, 0, 1.0, &coloured_opts).unwrap();
assert_ne!(by_author_png, coloured_png, "PNG export must reflect tracking colours");
// Also verify via file.exportPng command.
struct TempDir(std::path::PathBuf);
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
let dir = TempDir(std::env::temp_dir().join(format!("wordcraft-tracking-png-{}", std::process::id())));
std::fs::create_dir_all(&dir.0).unwrap();
let p1 = dir.0.join("by_author.png");
let p2 = dir.0.join("coloured.png");
s.run("review.trackingOptions", &json!({"insertColor": "byAuthor", "deleteColor": "byAuthor"})).unwrap();
s.run("file.exportPng", &json!({"path": p1.to_string_lossy(), "markup": true, "scale": 1.0})).unwrap();
s.run("review.trackingOptions", &json!({"insertColor": "0000FF", "deleteColor": "FF0000"})).unwrap();
s.run("file.exportPng", &json!({"path": p2.to_string_lossy(), "markup": true, "scale": 1.0})).unwrap();
assert_ne!(std::fs::read(&p1).unwrap(), std::fs::read(&p2).unwrap());
assert_eq!(std::fs::read(&p1).unwrap(), by_author_png);
assert_eq!(std::fs::read(&p2).unwrap(), coloured_png);
// Verify hidden deletions take no space in PNG export.
s.run("review.trackingOptions", &json!({"deleteMark": "hidden"})).unwrap();
let hidden_opts = cmd::file::export_options(&s, &markup_opts);
let hidden_png = crate::io_ext::render_png(&s.doc, 0, 1.0, &hidden_opts).unwrap();
assert_ne!(hidden_png, coloured_png, "hidden deletions must affect PNG pixels/layout");
}
/// Print Markup (#589): `file.printMarkup` or a command's `markup` puts the comments into PDFs
/// (balloons beside the scaled page) and at the end of HTML, Markdown and text copies.
#[test]
@@ -13229,6 +13571,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]
+1
View File
@@ -220,6 +220,7 @@ impl Exporter<'_> {
}
}
/// Draws the content of a single page (background, watermark, headers, footers, body items, and comments) onto the surface.
pub(crate) fn page(&mut self, s: &mut Surface, page: &Page, w: f32, h: f32) {
if let Some(c) = self.doc.settings.page_color
&& let Some(p) = rect_path(&Rect::new(0.0, 0.0, w, h))
+6
View File
@@ -50,6 +50,9 @@ pub struct PdfOptions {
/// How [`export`] shows digits (the Numeral setting; callers resolve `System`, see
/// [`NumeralMode::resolve`]). [`export_layout`] keeps the layout it is given.
pub numeral: NumeralMode,
/// How tracked changes are marked (Track Changes Options): the insertion and deletion marks
/// and colours the screen shows (#5232). Default: marks as on screen, colours by author.
pub revisions: wordcraft_layout::display::MarkupOptions,
/// What [`export`] shows for a page reference to a bookmark the document doesn't have, in the
/// interface language (`None`: Word's English "Error! Bookmark not defined."). [`export_layout`]
/// keeps the layout it is given.
@@ -70,6 +73,7 @@ impl PdfOptions {
dim_body: false,
markup: self.include_markup,
placeholders: false,
revisions: self.revisions.clone(),
..Default::default()
}
}
@@ -79,6 +83,7 @@ impl PdfOptions {
pub fn layout_options(&self) -> wordcraft_layout::LayoutOptions {
wordcraft_layout::LayoutOptions {
hide_deleted: !self.include_markup,
hide_marked: self.revisions.hidden_deletions(),
comment_balloons: self.comments,
numeral: self.numeral,
output_page_refs: true,
@@ -105,6 +110,7 @@ impl Default for PdfOptions {
links: true,
paper: None,
numeral: NumeralMode::Arabic,
revisions: wordcraft_layout::display::MarkupOptions::default(),
bookmark_error: None,
}
}
+143
View File
@@ -4,6 +4,7 @@ use wordcraft_doc::para::InlineObject;
use wordcraft_doc::picfx::PicFx;
use wordcraft_doc::props::NumRef;
use wordcraft_doc::{Block, CharProps, Document, ListKind, Paragraph, Table, Watermark, para_block};
use wordcraft_layout::display::{DeleteMark, MarkupOptions};
use crate::*;
use wordcraft_layout::LayoutOptions;
@@ -167,6 +168,65 @@ fn extract_text(bytes: &[u8]) -> Vec<String> {
.collect()
}
/// Extract text runs with their RGB fill colour from `bytes`.
fn extract_colored_text(bytes: &[u8]) -> Vec<(String, [u8; 3])> {
use hayro_interpret::font::Glyph;
use hayro_interpret::{
BlendMode, ClipPath, Context, Device, GlyphDrawMode, Image, InterpreterCache, InterpreterSettings, Paint, PathDrawMode, SoftMask,
interpret_page,
};
use hayro_syntax::Pdf;
/// A testing device that records extracted text runs along with their RGB fill colour.
struct Ex(Vec<(String, [u8; 3])>);
impl Device<'_> for Ex {
/// Ignore soft masks during text extraction.
fn set_soft_mask(&mut self, _: Option<SoftMask<'_>>) {}
/// Ignore blend modes during text extraction.
fn set_blend_mode(&mut self, _: BlendMode) {}
/// Ignore paths during text extraction.
fn draw_path(&mut self, _: &kurbo::BezPath, _: kurbo::Affine, _: &Paint<'_>, _: &PathDrawMode) {}
/// Ignore clip paths during text extraction.
fn push_clip_path(&mut self, _: &ClipPath) {}
/// Ignore transparency groups during text extraction.
fn push_transparency_group(&mut self, _: f32, _: Option<SoftMask<'_>>, _: BlendMode) {}
/// Records glyph text with its non-stroking RGB color, merging adjacent glyphs of identical color.
fn draw_glyph(&mut self, g: &Glyph<'_>, _: kurbo::Affine, _: kurbo::Affine, paint: &Paint<'_>, mode: &GlyphDrawMode) {
if matches!(mode, GlyphDrawMode::Stroke(_)) {
return;
}
let Paint::Color(color) = paint else { return };
let rgba = color.to_rgba().to_rgba8();
let rgb = [rgba[0], rgba[1], rgba[2]];
let ch = match g.as_unicode() {
Some(hayro_cmap::BfString::Char(c)) => c.to_string(),
Some(hayro_cmap::BfString::String(s)) => s.to_string(),
None => "\u{FFFD}".to_string(),
};
if let Some((last_text, last_rgb)) = self.0.last_mut()
&& *last_rgb == rgb
{
last_text.push_str(&ch);
return;
}
self.0.push((ch, rgb));
}
/// Ignore images during text extraction.
fn draw_image(&mut self, _: Image<'_, '_>, _: kurbo::Affine) {}
/// Ignore clip path pop during text extraction.
fn pop_clip_path(&mut self) {}
/// Ignore transparency group pop during text extraction.
fn pop_transparency_group(&mut self) {}
}
let pdf = Pdf::new(bytes.to_vec()).expect("parse");
let cache = InterpreterCache::new();
let mut ex = Ex(Vec::new());
for page in pdf.pages().iter() {
let mut ctx = Context::new(kurbo::Affine::IDENTITY, kurbo::Rect::new(0.0, 0.0, 1.0, 1.0), &cache, pdf.xref(), InterpreterSettings::default());
interpret_page(page, &mut ctx, &mut ex);
}
ex.0
}
fn squash(s: &str) -> String {
s.split_whitespace().collect::<Vec<_>>().join(" ")
}
@@ -293,6 +353,89 @@ fn tracked_deletions_are_left_out_without_markup() {
assert_eq!(text, "Keep DELETEDTEXT INSERTED");
}
/// #5232: the Track Changes Options colours (blue insertions, red deletions) reach the PDF instead
/// of every revision taking its author's colour.
#[test]
fn markup_takes_the_track_changes_option_colours() {
use wordcraft_doc::props::Rgb;
use wordcraft_doc::{Revision, RevisionKind};
let mut d = Document::new();
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Ada".into(), date: String::new(), move_name: None });
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None });
let mut p = Paragraph::with_text("Keep ", CharProps::default());
let n = p.len();
p.insert_text(n, "Kansas ", &CharProps { del: Some(0), ..Default::default() }).unwrap();
let n = p.len();
p.insert_text(n, "Missouri", &CharProps { ins: Some(1), ..Default::default() }).unwrap();
d.body = vec![para_block(p)];
// By author: both revisions take Ada's colour (#B01E8F = [176, 30, 143]), no pure blue or red.
let by_author_bytes = export(&d, &PdfOptions { include_markup: true, compress: false, ..Default::default() }).unwrap();
let by_author_runs = extract_colored_text(&by_author_bytes);
let kansas_author = by_author_runs.iter().find(|(s, _)| s.contains("Kansas")).map(|(_, c)| *c).expect("Kansas present");
let missouri_author = by_author_runs.iter().find(|(s, _)| s.contains("Missouri")).map(|(_, c)| *c).expect("Missouri present");
assert_eq!(kansas_author, missouri_author, "by-author colours must match for the same author");
assert_ne!(kansas_author, [255, 0, 0], "by-author is not red");
assert_ne!(missouri_author, [0, 0, 255], "by-author is not blue");
// With explicit Track Changes colours: insertions are blue, deletions are red.
let blue = Rgb(0, 0, 255);
let red = Rgb(255, 0, 0);
let coloured_opts = PdfOptions {
include_markup: true,
compress: false,
revisions: MarkupOptions { insert_color: Some(blue), delete_color: Some(red), ..Default::default() },
..Default::default()
};
let coloured_bytes = export(&d, &coloured_opts).unwrap();
let coloured_runs = extract_colored_text(&coloured_bytes);
let kansas_color = coloured_runs.iter().find(|(s, _)| s.contains("Kansas")).map(|(_, c)| *c).expect("Kansas present");
let missouri_color = coloured_runs.iter().find(|(s, _)| s.contains("Missouri")).map(|(_, c)| *c).expect("Missouri present");
assert_eq!(kansas_color, [255, 0, 0], "deleted Kansas must be red");
assert_eq!(missouri_color, [0, 0, 255], "inserted Missouri must be blue");
// Also assert the PDF content stream has the corresponding color operators preceding each run.
let raw = String::from_utf8_lossy(&coloured_bytes);
let tokens: Vec<_> = raw.split_ascii_whitespace().collect();
let has = |op: &str| {
let want: Vec<_> = op.split_ascii_whitespace().collect();
tokens.windows(want.len()).any(|w| w == want.as_slice())
};
assert!(has("1 0 0 rg"), "raw PDF stream contains red non-stroking operator");
assert!(has("0 0 1 rg"), "raw PDF stream contains blue non-stroking operator");
}
/// #5232: deletions marked Hidden in Track Changes Options take no space and are omitted from
/// the exported PDF with markup.
#[test]
fn hidden_deletions_stay_out_of_markup_pdf() {
use wordcraft_doc::{Revision, RevisionKind};
let mut d = Document::new();
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Ada".into(), date: String::new(), move_name: None });
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None });
let mut p = Paragraph::with_text("Keep ", CharProps::default());
let n = p.len();
p.insert_text(n, "Kansas ", &CharProps { del: Some(0), ..Default::default() }).unwrap();
let n = p.len();
p.insert_text(n, "Missouri", &CharProps { ins: Some(1), ..Default::default() }).unwrap();
d.body = vec![para_block(p)];
// Strikethrough: deleted Kansas is included in markup PDF.
let strike_opts = PdfOptions {
include_markup: true,
revisions: MarkupOptions { delete_mark: DeleteMark::Strikethrough, ..Default::default() },
..Default::default()
};
let strike_text = squash(&extract_text(&export(&d, &strike_opts).unwrap()).concat());
assert_eq!(strike_text, "Keep Kansas Missouri");
// Hidden: deleted Kansas is omitted from markup PDF.
let hidden_opts =
PdfOptions { include_markup: true, revisions: MarkupOptions { delete_mark: DeleteMark::Hidden, ..Default::default() }, ..Default::default() };
let hidden_text = squash(&extract_text(&export(&d, &hidden_opts).unwrap()).concat());
assert_eq!(hidden_text, "Keep Missouri");
}
#[test]
fn deleted_heading_text_stays_out_of_bookmarks_and_tags() {
use wordcraft_doc::{Revision, RevisionKind};
+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()));
}
}
+10 -4
View File
@@ -52,10 +52,16 @@ impl WordApp {
self.session.author = author;
}
self.session.initials = std::mem::take(&mut self.ui.initials).chars().take(wordcraft_engine::cmd::options::MAX_INITIALS_CHARS).collect();
for w in std::mem::take(&mut self.ui.dictionary).iter().take(MAX_DICTIONARY) {
let w = w.trim();
if !w.is_empty() && w.chars().count() <= wordcraft_engine::cmd::options::MAX_WORD_CHARS {
wordcraft_engine::proof::add_word(w);
// A bound custom dictionary file is the source of truth: `load_user_dictionary` reads it
// at start-up. Restoring the `ui.json` copy first would let a missing or unreadable file's
// words reach the default `custom-dictionary.txt` on the next Add to Dictionary (#5840).
let saved_words = std::mem::take(&mut self.ui.dictionary);
if self.ui.editing.custom_dictionary.is_none() {
for w in saved_words.iter().take(MAX_DICTIONARY) {
let w = w.trim();
if !w.is_empty() && w.chars().count() <= wordcraft_engine::cmd::options::MAX_WORD_CHARS {
wordcraft_engine::proof::add_word(w);
}
}
}
self.session.prefs = std::mem::take(&mut self.ui.editing);
+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;
}
+22 -19
View File
@@ -374,25 +374,28 @@ fn shortcut_text_is_swallowed_once() {
frames(&mut h, 4);
h
};
// The shortcut and its text in one frame.
let mut h = fresh();
h.event(key(egui::Key::Q, true));
h.event(egui::Event::Text("q".into()));
frames(&mut h, 3);
// The app is in Focus, where the title bar's Search box is hidden, so the dialog takes the request (#5398).
assert!(is_open(h.state(), "commands"), "Alt+Q opens the palette");
assert_eq!(query(&h), "", "Alt+Q's q, same frame");
// The text a frame late; then typing.
let mut h = fresh();
h.event(key(egui::Key::Q, true));
frames(&mut h, 1);
h.event(egui::Event::Text("q".into()));
frames(&mut h, 1);
assert_eq!(query(&h), "", "the q a frame late");
h.event(key(egui::Key::B, false));
h.event(egui::Event::Text("b".into()));
frames(&mut h, 2);
assert_eq!(query(&h), "b", "then typing lands");
// Alt+Q is the command search off macOS only (Option+Q types a character there; `tools.search` has no key).
if !cfg!(target_os = "macos") {
// The shortcut and its text in one frame.
let mut h = fresh();
h.event(key(egui::Key::Q, true));
h.event(egui::Event::Text("q".into()));
frames(&mut h, 3);
// The app is in Focus, where the title bar's Search box is hidden, so the dialog takes the request (#5398).
assert!(is_open(h.state(), "commands"), "Alt+Q opens the palette");
assert_eq!(query(&h), "", "Alt+Q's q, same frame");
// The text a frame late; then typing.
let mut h = fresh();
h.event(key(egui::Key::Q, true));
frames(&mut h, 1);
h.event(egui::Event::Text("q".into()));
frames(&mut h, 1);
assert_eq!(query(&h), "", "the q a frame late");
h.event(key(egui::Key::B, false));
h.event(egui::Event::Text("b".into()));
frames(&mut h, 2);
assert_eq!(query(&h), "b", "then typing lands");
}
// A palette opened by a click takes typing.
let mut h = fresh();
open_named(&mut h, "commands", json!({}));
+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"));
}
}
+3 -1
View File
@@ -239,8 +239,10 @@ impl<'a> Exempt<'a> {
fn allows(&self, app: &WordApp, text: &str) -> bool {
let plain = unmarked(text);
let plain = plain.trim().trim_end_matches(" —").trim();
// A chord is `Ctrl+Shift+K` or, on macOS, the modifiers' symbols run into the key (`⌥⌘Space`, `⇧⌘K`).
let chord = |s: &str| {
s.split('+').all(|k| matches!(k, "Ctrl" | "Shift" | "Alt" | "Cmd" | "Esc" | "Tab" | "Enter" | "Space") || k.chars().count() <= 3)
let key = |k: &str| matches!(k, "Ctrl" | "Shift" | "Alt" | "Cmd" | "Esc" | "Tab" | "Enter" | "Space") || k.chars().count() <= 3;
s.split('+').all(|k| key(k) || key(k.trim_start_matches(['⌃', '⌥', '⇧', '⌘'])))
};
let is_shortcut = || chord(plain);
// A command's hover hint, drawn as one text: its marked label, name and location, so what is left is the
+21 -7
View File
@@ -432,12 +432,13 @@ pub fn for_command(id: &str) -> IconSpec<'static> {
Some((_, icon)) => Cow::Borrowed(icon),
None => Cow::Owned(id.rsplit('.').next().unwrap_or(id).to_owned()),
};
let name = match OWN_OVER_CATALOG.iter().find(|(plain, _)| *plain == name) {
Some((_, own)) => Cow::Borrowed(*own),
None => name,
};
match glyphs::ICONS.iter().find(|icon| icon.0 == name) {
Some(icon) => IconSpec::glyph(icon),
// A text glyph is found by the plain name (`pilcrow`); the app's own SVG of a catalog name
// (`wordcraft.pilcrow`) applies only to the SVG fallback.
if let Some(icon) = glyphs::ICONS.iter().find(|icon| icon.0 == name) {
return IconSpec::glyph(icon);
}
match OWN_OVER_CATALOG.iter().find(|(plain, _)| *plain == name) {
Some((_, own)) => IconSpec::svg(IconId::new(own)),
None => IconSpec::svg(IconId::from(name)),
}
}
@@ -512,6 +513,13 @@ mod tests {
assert_eq!(undo, "wordcraft.undo");
}
/// QAT and custom-group buttons draw `view.marks` as the pilcrow text glyph, as the ribbon does, not the
/// app's SVG of the same name.
#[test]
fn for_command_picks_the_text_glyph_before_the_own_svg() {
assert!(matches!(for_command("view.marks").source, craft::ui::primitives::IconSource::Glyph(_)));
}
/// #6768: the Insert › Shapes Arrow tile is the block arrow that tile inserts, outlined as the
/// document draws it, not a thin line with a head.
#[test]
@@ -544,13 +552,18 @@ mod tests {
register();
let mut files = Vec::new();
rs_files(&std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"), &mut files);
let (mut seen, mut missing) = (0, Vec::new());
let (mut seen, mut missing, mut svg_only) = (0, Vec::new(), Vec::new());
for file in files.iter().filter(|f| !f.ends_with("icons.rs")) {
let text = std::fs::read_to_string(file).unwrap_or_default();
for call in ["IconId::new(\"", "icons::id(\"", "icons::spec(\""] {
for part in text.split(call).skip(1) {
let Some(name) = part.split('"').next() else { continue };
seen += 1;
// A text glyph resolves only through `icons::spec`; the SVG-only calls draw its SVG instead.
if call != "icons::spec(\"" && glyphs::ICONS.iter().any(|g| g.0 == name) {
svg_only.push(format!("{name} ({}): use icons::spec", file.display()));
continue;
}
let known = match call {
"IconId::new(\"" => craft::ui::primitives::has_icon(&IconId::from(Cow::Owned(name.to_owned()))),
_ => {
@@ -569,5 +582,6 @@ mod tests {
}
assert!(seen > 200, "the scan found only {seen} names");
assert!(missing.is_empty(), "icons used but not in the app set or the catalog: {missing:?}");
assert!(svg_only.is_empty(), "text glyphs passed through the SVG-only IconId::new / icons::id: {svg_only:?}");
}
}
+62 -2
View File
@@ -83,7 +83,11 @@ pub(super) struct TextIcon(pub(super) &'static str);
impl Glyph for TextIcon {
fn paint(&self, painter: &Painter, tokens: &UiTokens, rect: Rect, color: Color32, _mirrored: bool) {
let pen = Pen { p: painter, r: rect, c: color, a: rgba_color(tokens.color.accent.solid), w: 1.25 };
// The framework passes `text.disabled` as `color` to a disabled button, and a glyph has no other way
// to learn that; then both inks go grey (the accent ink would stay bright on a disabled button).
let disabled = color == rgba_color(tokens.color.text.disabled);
let accent = if disabled { color } else { rgba_color(tokens.color.accent.solid) };
let pen = Pen { p: painter, r: rect, c: color, a: accent, w: 1.25 };
paint(&pen, self.0);
}
}
@@ -149,7 +153,7 @@ impl Pen<'_> {
}
}
/// Draws `name`; false when it is not one of [`NAMES`].
/// Draws `name`; false when it is not one of [`ICONS`].
fn paint(pen: &Pen, name: &str) -> bool {
let (c, a) = (pen.c, pen.a);
let red = Color32::from_rgb(0xD1, 0x3B, 0x3B);
@@ -408,4 +412,60 @@ mod tests {
out.textures_delta.clear();
assert_eq!(ICONS.len(), 65);
}
/// Every colour the shapes of `shape` paint with.
fn ink_of(shape: &Shape, out: &mut Vec<Color32>) {
match shape {
Shape::Vec(v) => v.iter().for_each(|s| ink_of(s, out)),
Shape::LineSegment { stroke, .. } => out.push(stroke.color),
Shape::Path(p) => {
out.push(p.fill);
if let egui::epaint::ColorMode::Solid(c) = p.stroke.color {
out.push(c);
}
}
Shape::Circle(c) => out.extend([c.stroke.color, c.fill]),
Shape::Rect(r) => out.extend([r.stroke.color, r.fill]),
Shape::Text(t) => {
out.push(t.fallback_color);
out.extend(t.galley.job.sections.iter().map(|s| s.format.color));
}
_ => {}
}
}
/// A disabled button hands its glyph `text.disabled` as the colour: no shape may then be in the accent
/// colour (production painted both inks grey). Enabled, the glyphs do use the accent.
#[test]
fn a_disabled_text_glyph_paints_no_accent_colour() {
use craft::theme::{Appearance, Contrast, Mode, Size, TextSize};
let themes = craft::theme::builtins();
let theme = themes.iter().find(|theme| theme.id.as_str() == craft::theme::SUITE_DEFAULT).unwrap();
let appearance = Appearance {
mode: Mode::Light,
contrast: Contrast::Standard,
size: Size::Compact,
text_size: TextSize::default(),
reduced_motion: false,
};
let tokens = UiTokens::new(std::sync::Arc::new(craft::theme::resolve(theme, appearance, None).tokens), Contrast::Standard, Size::Compact);
let (accent, disabled, normal) =
(rgba_color(tokens.color.accent.solid), rgba_color(tokens.color.text.disabled), rgba_color(tokens.color.text.normal));
assert_ne!(accent, disabled);
let inks = |color: Color32| {
let mut out = Vec::new();
let ctx = egui::Context::default();
let mut run = ctx.run_ui(egui::RawInput::default(), |ui| {
let painter = ui.painter().clone();
for icon in ICONS {
icon.paint(&painter, &tokens, Rect::from_min_size(pos2(0.0, 0.0), vec2(20.0, 20.0)), color, false);
}
});
run.textures_delta.clear();
run.shapes.iter().for_each(|clipped| ink_of(&clipped.shape, &mut out));
out
};
assert!(inks(normal).contains(&accent), "an enabled glyph uses the accent ink");
assert!(!inks(disabled).contains(&accent), "a disabled glyph painted in the accent colour");
}
}
+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
+41 -3
View File
@@ -113,6 +113,16 @@ fn batch_frame(h: &mut H, events: Vec<egui::Event>) {
crate::test_harness::frame(h);
}
/// The modifiers of the platform's Mod key as egui reports them: Cmd on macOS (`mac_cmd` with `command`, and no
/// Control), Ctrl elsewhere.
fn mod_held() -> Modifiers {
if cfg!(target_os = "macos") {
Modifiers { mac_cmd: true, command: true, ..Default::default() }
} else {
Modifiers { ctrl: true, command: true, ..Default::default() }
}
}
/// One frame with `modifiers` held, then `events`.
fn mods_frame(h: &mut H, modifiers: Modifiers, events: Vec<egui::Event>) {
let events = std::iter::once(egui::Event::ModifiersChanged(modifiers)).chain(events).collect();
@@ -224,7 +234,7 @@ fn user_assignments_become_overrides() {
/// bold HTML, whichever of Shift and V is released first.
#[test]
fn mod_shift_v_released_shift_first_pastes_once() {
let chord = Modifiers { ctrl: true, command: true, shift: true, ..Default::default() };
let chord = Modifiers { shift: true, ..mod_held() };
let ctrl = Modifiers { shift: false, ..chord };
let mut h = alt_frame_app();
run(&mut h, "text.insert", json!({"text": "source target"}));
@@ -241,7 +251,7 @@ fn mod_shift_v_released_shift_first_pastes_once() {
#[test]
fn a_global_mod_shift_v_leaves_the_next_mod_v_picture_paste_alone() {
let mut h = picture_app();
let chord = Modifiers { ctrl: true, command: true, shift: true, ..Default::default() };
let chord = Modifiers { shift: true, ..mod_held() };
mods_frame(&mut h, chord, vec![key_event(Key::V, true, chord)]);
let ctrl = Modifiers { shift: false, ..chord };
mods_frame(&mut h, ctrl, vec![key_event(Key::V, false, ctrl)]);
@@ -296,7 +306,7 @@ fn key_event(key: Key, pressed: bool, modifiers: Modifiers) -> egui::Event {
/// whether V or Ctrl is released first, and a plain V is no paste.
#[test]
fn mod_v_released_mod_first_pastes_the_clipboard_picture() {
let ctrl = Modifiers { ctrl: true, command: true, ..Default::default() };
let ctrl = mod_held();
let mut h = alt_frame_app();
run(&mut h, "text.insert", json!({"text": "x"}));
@@ -888,6 +898,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 -1
View File
@@ -173,7 +173,7 @@ pub(crate) fn members(app: &mut WordApp, ui: &mut Ui, preview: bool) {
}
for (id, icon) in [("format.growFont", "grow"), ("format.shrinkFont", "shrink")] {
let b = IconButton::command(crate::icons::id(icon), CommandRef::new(id)).show(ui);
let b = IconButton::command(crate::icons::spec(icon), CommandRef::new(id)).show(ui);
preview_on_hover(app, b.hover, b.response.enabled(), id, json!({}), preview);
}
});
+32 -2
View File
@@ -5,7 +5,7 @@
//! setting an agent changes and the same setting changed here take one path. Settings the app keeps
//! outside the engine are written directly by [`OptionsModel::set`].
use craft::behavior::{MotionMode, keyed};
use craft::behavior::{EditEvent, MotionMode, keyed};
use craft::ui::buttons::Button;
use craft::ui::contract::{Bind, Entry, Props as _, Show, ShowCollection, ShowContainer};
use craft::ui::display::{Elide, Shade, Text};
@@ -268,6 +268,7 @@ impl<'a> OptionsModel<'a> {
("proofing.ignoreInternet", Bool(prefs.ignore_internet)),
("proofing.checkSpelling", Bool(view.proofing)),
("proofing.markGrammar", Bool(prefs.mark_grammar)),
("proofing.customDictionaryFile", Text(String::new())),
],
"save" => vec![("save.removePersonalInfo", Bool(false)), ("save.removeDateTime", Bool(false))],
"language" => vec![("language.interface", Choice(crate::i18n::AUTO.to_string())), ("language.dictionariesFolder", Text(String::new()))],
@@ -426,7 +427,14 @@ impl PreferencesModel for OptionsModel<'_> {
b("proofing.markGrammar", tl!("Mark grammar errors as you type"), prefs.mark_grammar).enabled(app.session.view.proofing),
],
),
GroupSpec::new(Some(tl!("Custom dictionary")), vec![custom("proofing.customDictionary", tl!("Custom dictionary"))]),
GroupSpec::new(
Some(tl!("Custom dictionary")),
vec![
RowSpec::new("proofing.customDictionaryFile", tl!("Dictionary file:"), RowKind::Custom)
.help(tl!("A custom-word dictionary file (.dic or plain text) used in conjunction with the main dictionary. Empty uses custom-dictionary.txt.")),
custom("proofing.customDictionary", tl!("Custom dictionary")),
],
),
],
);
@@ -666,6 +674,10 @@ impl PreferencesModel for OptionsModel<'_> {
("save.removePersonalInfo", Bool(v)) => self.run("file.privacyOptions", json!({"removePersonalInfo": v})),
("save.removeDateTime", Bool(v)) => self.run("file.privacyOptions", json!({"removeDateTime": v})),
("language.interface", Choice(c)) => self.run("ui.language", json!({"value": c})),
("proofing.customDictionaryFile", Text(t)) => {
let t = t.trim();
self.options(json!({"customDictionary": if t.is_empty() { "auto" } else { t }}));
}
("language.dictionariesFolder", Text(t)) => {
let t = t.trim();
self.options(json!({"dictionariesFolder": if t.is_empty() { "auto" } else { t }}));
@@ -701,6 +713,7 @@ impl PreferencesModel for OptionsModel<'_> {
self.run("tools.autocorrect", json!({}));
}
}
"proofing.customDictionaryFile" => self.custom_dictionary_file(ui),
"proofing.customDictionary" => self.custom_dictionary(ui),
"language.proofingLanguage" => {
Text::new(self.strings.proofing_language.clone()).role(TypeRole::Caption).shade(Shade::Faint).show(ui);
@@ -744,6 +757,23 @@ const CUSTOM_WORDS_SHOWN: u16 = 8;
struct NewWord(String);
impl OptionsModel<'_> {
/// The Dictionary file field. A text row reports every typed draft, and each would bind (and
/// later write to) whatever file the half-typed path names, so the path is committed only on
/// Enter or focus loss. The field is given the saved path and never writes it: the framework
/// holds the draft while an edit is open and drops it when the saved path changes (an agent's
/// `file.options`) or the page is left, so no edit open always shows the saved path.
fn custom_dictionary_file(&mut self, ui: &mut Ui) {
let saved = self.app.session.prefs.custom_dictionary.clone().unwrap_or_default();
let out = TextField::new(tl!("Dictionary file:"), Bind::given(saved)).limit(None).show(ui);
let committed = out.events.into_iter().find_map(|event| match event {
EditEvent::Commit { after, .. } => Some(after),
_ => None,
});
if let Some(path) = committed {
self.set("proofing.customDictionaryFile", PrefValue::Text(path));
}
}
/// The custom dictionary: the words Add to Dictionary kept, each with a Remove button, and a
/// field to add one.
fn custom_dictionary(&mut self, ui: &mut Ui) {
+182
View File
@@ -258,3 +258,185 @@ fn screen_paper_color_options_round_trip_and_work_without_a_document() {
with_model(&mut b, true, |m| m.set("general.paperColor", PrefValue::Choice("cream".into())));
assert_eq!(b.session.prefs.paper_color, PaperColor::Cream);
}
/// #5840: File › Options › Proofing has the Dictionary file setting.
#[test]
fn proofing_custom_dictionary_file_setting_is_visible() {
let mut a = app();
let found = with_model(&mut a, true, |m| {
m.pages().iter().flat_map(|p| p.groups.iter()).flat_map(|g| g.rows.iter()).any(|r| r.key == "proofing.customDictionaryFile")
});
assert!(found);
}
/// #5840: File › Options › Proofing sets, clears and validates the custom dictionary path.
#[test]
fn proofing_custom_dictionary_interaction() {
let dir = std::env::temp_dir().join(format!("wc-ui-dict-{}", std::process::id()));
let _ = std::fs::create_dir_all(&dir);
let valid_path = dir.join("ui_custom.dic");
std::fs::write(&valid_path, "uiword\n").unwrap();
let valid_path_str = valid_path.to_string_lossy().into_owned();
let mut a = app();
// An invalid path is refused and not applied to the preferences.
with_model(&mut a, true, |m| m.set("proofing.customDictionaryFile", PrefValue::Text("/invalid/path/nonexistent.dic".into())));
assert_eq!(a.session.prefs.custom_dictionary, None, "invalid path was not applied to prefs");
let path = valid_path_str.clone();
with_model(&mut a, true, move |m| m.set("proofing.customDictionaryFile", PrefValue::Text(path)));
assert_eq!(a.session.prefs.custom_dictionary.as_deref(), Some(&valid_path_str[..]));
// Empty reverts to the default dictionary.
with_model(&mut a, true, |m| m.set("proofing.customDictionaryFile", PrefValue::Text(String::new())));
assert_eq!(a.session.prefs.custom_dictionary, None, "empty reverts custom dictionary to default");
let _ = std::fs::remove_dir_all(&dir);
}
/// #5840: a bound custom dictionary file is the source of truth. The saved word copy must not
/// be restored first, or words from a missing file would reach the default dictionary on the next
/// Add to Dictionary.
#[test]
fn a_bound_custom_dictionary_does_not_restore_saved_backup_words() {
let saved = Prefs {
dictionary: vec!["zqxbackupword".to_string()],
editing: wordcraft_engine::Prefs { custom_dictionary: Some("/nonexistent/custom.dic".to_string()), ..Default::default() },
..Default::default()
};
let mut a = app();
a.apply_prefs(saved);
assert!(!wordcraft_engine::proof::user_dictionary().contains(&"zqxbackupword".to_string()), "backup words stay out of memory");
assert_eq!(a.session.prefs.custom_dictionary.as_deref(), Some("/nonexistent/custom.dic"), "the file setting is kept");
}
/// #5840: the Dictionary file field commits the path on Enter, not on every keystroke. Typing
/// `notes.dic` passes through `notes`, a file that exists, which must not be bound on the way.
#[test]
fn typing_the_custom_dictionary_path_binds_it_only_on_enter() {
use egui_kittest::kittest::Queryable;
let dir = std::env::temp_dir().join(format!("wc-ui-dict-typing-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("notes"), "partway\n").unwrap();
let target = dir.join("notes.dic");
std::fs::write(&target, "uiword\n").unwrap();
let target_str = target.to_string_lossy().into_owned();
let mut a = app();
a.run("ui.backstage", json!({"value": true, "page": "options", "pane": "proofing"})).unwrap();
let mut h = crate::test_harness::builder().build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
a,
);
options_frames(&mut h, 3);
h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Dictionary file:").focus();
options_frames(&mut h, 2);
for c in target_str.chars() {
h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Dictionary file:").type_text(&c.to_string());
options_frames(&mut h, 2);
assert_eq!(h.state().session.prefs.custom_dictionary, None, "typing {c:?} bound a path");
}
h.key_press(egui::Key::Enter);
options_frames(&mut h, 3);
assert_eq!(h.state().session.prefs.custom_dictionary.as_deref(), Some(target_str.as_str()));
let _ = std::fs::remove_dir_all(&dir);
}
/// A harness over the real Options page, Proofing pane, with two dictionary files on disk.
fn dictionary_harness(tag: &str) -> (egui_kittest::Harness<'static, WordApp>, std::path::PathBuf, String, String) {
let dir = std::env::temp_dir().join(format!("wc-ui-dict-{tag}-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let one = dir.join("one.dic");
let two = dir.join("two.dic");
std::fs::write(&one, "oneword\n").unwrap();
std::fs::write(&two, "twoword\n").unwrap();
let mut a = app();
a.run("ui.backstage", json!({"value": true, "page": "options", "pane": "proofing"})).unwrap();
let mut h = crate::test_harness::builder().build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
a,
);
options_frames(&mut h, 3);
(h, dir, one.to_string_lossy().into_owned(), two.to_string_lossy().into_owned())
}
fn dictionary_field_text(h: &egui_kittest::Harness<'static, WordApp>) -> String {
use egui_kittest::kittest::Queryable;
h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Dictionary file:").value().unwrap_or_default()
}
fn type_into_dictionary_field(h: &mut egui_kittest::Harness<'static, WordApp>, text: &str) {
use egui_kittest::kittest::Queryable;
h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Dictionary file:").focus();
options_frames(h, 2);
h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Dictionary file:").type_text(text);
options_frames(h, 2);
}
/// #5899: a path typed but not committed yields to a saved path an agent sets meanwhile: the field
/// shows the agent's value (the framework ends the edit when the value changes outside it), and a
/// later Enter does not write the abandoned draft over it.
#[test]
fn an_outside_change_replaces_a_path_being_typed() {
let (mut h, dir, one, two) = dictionary_harness("outside");
type_into_dictionary_field(&mut h, &one);
assert_eq!(h.state().session.prefs.custom_dictionary, None, "typing binds nothing");
h.state_mut().run("file.options", json!({"customDictionary": two})).unwrap();
options_frames(&mut h, 3);
assert_eq!(h.state().session.prefs.custom_dictionary.as_deref(), Some(two.as_str()));
assert_eq!(dictionary_field_text(&h), two, "the field shows the agent's path");
h.key_press(egui::Key::Enter);
options_frames(&mut h, 3);
assert_eq!(h.state().session.prefs.custom_dictionary.as_deref(), Some(two.as_str()), "Enter did not overwrite it");
let _ = std::fs::remove_dir_all(&dir);
}
/// #5899: an uncommitted draft does not outlive its pane: back on Proofing the field shows the saved path.
#[test]
fn leaving_the_pane_drops_an_uncommitted_path() {
let (mut h, dir, one, two) = dictionary_harness("leave");
h.state_mut().run("file.options", json!({"customDictionary": two})).unwrap();
options_frames(&mut h, 3);
type_into_dictionary_field(&mut h, &one);
h.state_mut().run("ui.backstage", json!({"value": false})).unwrap();
options_frames(&mut h, 3);
h.state_mut().run("ui.backstage", json!({"value": true, "page": "options", "pane": "proofing"})).unwrap();
options_frames(&mut h, 3);
assert_eq!(dictionary_field_text(&h), two, "the field shows the saved path");
assert_eq!(h.state().session.prefs.custom_dictionary.as_deref(), Some(two.as_str()));
let _ = std::fs::remove_dir_all(&dir);
}
/// #5899: focus leaving the field commits the typed path.
#[test]
fn focus_loss_commits_the_custom_dictionary_path() {
use egui_kittest::kittest::Queryable;
let (mut h, dir, one, _two) = dictionary_harness("blur");
type_into_dictionary_field(&mut h, &one);
assert_eq!(h.state().session.prefs.custom_dictionary, None);
h.get_by_role_and_label(egui::accesskit::Role::TextInput, "New word").focus();
options_frames(&mut h, 3);
assert_eq!(h.state().session.prefs.custom_dictionary.as_deref(), Some(one.as_str()));
let _ = std::fs::remove_dir_all(&dir);
}
/// #5899: Escape abandons the typed path: nothing binds, and the field shows the saved path again.
#[test]
fn escape_does_not_commit_the_custom_dictionary_path() {
let (mut h, dir, one, _two) = dictionary_harness("escape");
type_into_dictionary_field(&mut h, &one);
h.key_press(egui::Key::Escape);
options_frames(&mut h, 3);
assert_eq!(h.state().session.prefs.custom_dictionary, None);
assert_eq!(dictionary_field_text(&h), "", "the field shows the saved (empty) path");
let _ = std::fs::remove_dir_all(&dir);
}
+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
+69 -7
View File
@@ -144,15 +144,24 @@ pub(crate) const PAGES_PER_SHEET: [(&str, &str); 8] = [
("bookletReverse", "Booklet (right binding)"),
];
/// What the preview's layout is made from besides the document's text: the revision, Print
/// Markup, the file name and path FILENAME fields show (#6282: Save As and Rename change them
/// without an edit), and the font database generation the app has seen (#6283:
/// `WordApp::watch_fonts` moves it when fonts are added or removed).
type LayoutKey = (u64, bool, (String, String), u64);
/// The settings that decide how tracked changes and comments look in the print preview:
/// Print Markup and Track Changes Options.
type MarkupKey = (bool, wordcraft_layout::display::MarkupOptions);
/// The [`MarkupKey`] now.
fn markup_key(app: &WordApp) -> MarkupKey {
(app.session.prefs.print_markup, app.session.prefs.markup.clone())
}
/// What the preview's layout is made from besides the document's text: the document id, the
/// revision, Print Markup and Track Changes Options, the file name and path FILENAME fields show
/// (#6282: Save As and Rename change them without an edit), and the font database generation the
/// app has seen (#6283: `WordApp::watch_fonts` moves it when fonts are added or removed).
type LayoutKey = (u64, u64, MarkupKey, (String, String), u64);
/// The [`LayoutKey`] now.
fn layout_key(app: &WordApp) -> LayoutKey {
(app.session.rev(), app.session.prefs.print_markup, app.session.resolved_filenames(), app.font_generation)
(app.session.document_id(), app.session.rev(), markup_key(app), app.session.resolved_filenames(), app.font_generation)
}
/// The output layout, kept in `cache` while what it is made from ([`LayoutKey`]) is unchanged.
@@ -164,11 +173,21 @@ fn layout_of(app: &WordApp, cache: &mut Option<(LayoutKey, Arc<DocLayout>)>) ->
{
return l.clone();
}
let l = app.session.export_layout_with(app.session.prefs.print_markup);
let l = app.session.print_layout(app.session.prefs.print_markup);
*cache = Some((key, l.clone()));
l
}
/// How the preview draws a page: tracked changes marked as the print job marks them, headers and
/// footers at full strength (the preview is the printed page, not the editing view).
pub(super) fn preview_options(app: &WordApp) -> wordcraft_render::RenderOptions {
let mut opts = wordcraft_render::RenderOptions::default();
opts.display.markup = app.session.prefs.print_markup;
opts.display.revisions = app.session.prefs.markup.clone();
opts.display.dim_header = false;
opts
}
/// One choice list over `(id, label)` pairs, named `label`; true when the choice changed.
fn choice(ui: &mut Ui, label: &str, salt: &str, current: &mut String, items: &[(&str, &str)]) -> bool {
let mut changed = false;
@@ -584,4 +603,47 @@ mod tests {
let (sparse, dense) = (at(1.0), at(2.0));
assert!(sparse > 0 && dense > sparse * 2, "{dense} {sparse}");
}
/// The preview pages as the print job does (#5269 review): without Print Markup tracked
/// deletions take no space, whatever Track Changes Options mark them with.
#[test]
fn the_preview_pages_as_the_print_job() {
let text: Vec<String> = (0..200).map(|i| format!("Line {i} of the old text")).collect();
let doc = wordcraft_doc::Document::from_text(&text.join("\n"));
let mut app = crate::WordApp::new(wordcraft_engine::Session::new(doc), Default::default());
let mut cache = None;
app.run("review.trackChanges", json!({"value": true})).unwrap();
app.run("select.all", json!({})).unwrap();
app.run("text.insert", json!({"text": "Kept"})).unwrap();
// The preview is the printed page: headers and footers draw at full strength (#6267).
assert!(!preview_options(&app).display.dim_header);
let mut pages = |app: &crate::WordApp| (layout_of(app, &mut cache).pages.len(), app.session.print_pdf(&json!({})).unwrap().1.chosen);
app.run("file.printMarkup", json!({"value": true})).unwrap();
let (marked, job) = pages(&app);
assert!(marked > 1 && marked == job, "{marked} vs {job}");
app.run("file.printMarkup", json!({"value": false})).unwrap();
assert_eq!(pages(&app), (1, 1));
// The cached layout follows the Delete mark option too (it changes the layout with markup).
app.run("file.printMarkup", json!({"value": true})).unwrap();
app.run("review.trackingOptions", json!({"deleteMark": "hidden"})).unwrap();
assert_eq!(pages(&app), (1, 1));
// Changing revision colours refreshes the preview revision even on the same page count.
let rev_before = preview::inputs(&app);
app.run("review.trackingOptions", json!({"insertColor": "0000FF", "deleteColor": "FF0000"})).unwrap();
let rev_after = preview::inputs(&app);
assert_ne!(rev_before, rev_after, "tracking colours refresh preview revision");
}
/// Two documents at the same revision drawn in one window's context (#5270 review): each
/// preview gets its own layout, not the other's cached one.
#[test]
fn the_preview_cache_tells_documents_apart() {
let long: Vec<String> = (0..200).map(|i| format!("Line {i}")).collect();
let app = |text: &str| crate::WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text(text)), Default::default());
let (long, short) = (app(&long.join("\n")), app("One line"));
assert_eq!(long.session.rev(), short.session.rev(), "the test needs equal revisions");
let mut cache = None;
assert!(layout_of(&long, &mut cache).pages.len() > 1);
assert_eq!(layout_of(&short, &mut cache).pages.len(), 1);
}
}
+2 -2
View File
@@ -13,7 +13,7 @@ use craft::ui::primitives::textures::{Priority, Revision, TextureState, ThumbRen
use egui::{Color32, ColorImage, Ui};
use wordcraft_layout::DocLayout;
use super::{PrintPage, layout_key};
use super::{PrintPage, layout_key, preview_options};
use crate::WordApp;
/// The salt of the preview's thumbnail store.
@@ -68,7 +68,7 @@ impl ThumbSource<usize> for SheetSource<'_> {
}
let x0 = ((slot.x + (slot.width - pg.w * k) / 2.0) * scale).round() as i64;
let y0 = ((slot.y + (slot.height - pg.h * k) / 2.0) * scale).round() as i64;
let page = wordcraft_render::render_page(&self.app.session.doc, pg, page_scale, &Default::default());
let page = wordcraft_render::render_page(&self.app.session.doc, pg, page_scale, &preview_options(self.app));
let straight = page.to_straight();
let row_len = (page.width as usize).max(1) * 4;
for (row, line) in straight.chunks_exact(row_len).enumerate() {
+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());
}
}
+1 -1
View File
@@ -75,7 +75,7 @@ pub(super) fn draw(row: &mut RibbonRow<'_>, app: &mut WordApp) {
})),
)
.label(crate::tl!("Color"))
.icon(IconSpec::from(IconId::new("fontcolor")).with_mark(IconMark::bar(DataColor::new(ink))))
.icon(crate::icons::spec("fontcolor").with_mark(IconMark::bar(DataColor::new(ink))))
.show(ui);
menu_button(
ui,
+7 -7
View File
@@ -24,7 +24,7 @@ use crate::colors::{Remember, Target};
/// A ribbon group titled `title`, with the Dialog Launcher `launcher` when it has one.
fn ribbon_group(key: &'static str, title: &str, icon: &'static str, launcher: Option<&str>) -> RibbonGroup<'static> {
let group = RibbonGroup::new(key, tl!(title).to_string(), crate::icons::id(icon).into());
let group = RibbonGroup::new(key, tl!(title).to_string(), crate::icons::spec(icon));
match launcher {
Some(id) => group.launcher(CommandRef::new(id)),
None => group,
@@ -193,7 +193,7 @@ pub(super) fn home(row: &mut RibbonRow<'_>, app: &mut WordApp) {
let _ = app.run("format.size", json!({"size": x}));
}
for (icon, tip, id) in [("grow", "Increase Font Size", "format.growFont"), ("shrink", "Decrease Font Size", "format.shrinkFont")] {
IconButton::command(crate::icons::id(icon), CommandRef::new(id))
IconButton::command(crate::icons::spec(icon), CommandRef::new(id))
.label(tl!(tip).to_string())
.tooltip(tl!(tip).to_string())
.show(ui);
@@ -211,7 +211,7 @@ pub(super) fn home(row: &mut RibbonRow<'_>, app: &mut WordApp) {
}
});
for (icon, tip, id) in [("clear", "Clear All Formatting", "format.clear"), ("phonetic", "Phonetic Guide", "format.phonetic")] {
IconButton::command(crate::icons::id(icon), CommandRef::new(id))
IconButton::command(crate::icons::spec(icon), CommandRef::new(id))
.label(tl!(tip).to_string())
.tooltip(tl!(tip).to_string())
.show(ui);
@@ -247,7 +247,7 @@ pub(super) fn home(row: &mut RibbonRow<'_>, app: &mut WordApp) {
.tooltip(tl!(tip).to_string())
.show(ui);
}
IconButton::command(IconId::new("enclose"), CommandRef::new("format.enclose"))
IconButton::command(crate::icons::spec("enclose"), CommandRef::new("format.enclose"))
.label(tl!("Enclose Characters").to_string())
.tooltip(tl!("Enclose Characters").to_string())
.show(ui);
@@ -338,13 +338,13 @@ pub(super) fn home(row: &mut RibbonRow<'_>, app: &mut WordApp) {
for (icon, tip, id) in
[("outdent", "Decrease Indent", "para.outdent"), ("indent", "Increase Indent", "para.indent"), ("sort", "Sort", "para.sort")]
{
IconButton::command(crate::icons::id(icon), CommandRef::new(id))
IconButton::command(crate::icons::spec(icon), CommandRef::new(id))
.label(tl!(tip).to_string())
.tooltip(tl!(tip).to_string())
.show(ui);
}
ToggleButton::command(CommandRef::new("view.marks"))
.icon(IconId::new("wordcraft.pilcrow"))
.icon(crate::icons::spec("pilcrow"))
.icon_only()
.selected(marks)
.tooltip(tl!("Show/Hide ¶").to_string())
@@ -413,7 +413,7 @@ pub(super) fn home(row: &mut RibbonRow<'_>, app: &mut WordApp) {
// whole document with Ctrl+A first (the commands take `scope: "all"` for that as well).
row.group(ribbon_group("paragraphTools", "Paragraph Tools", "pilcrow", None), |ui| {
let face = Button::new(tl!("Paragraph\nTools").to_string())
.icon(IconId::new("wordcraft.pilcrow"))
.icon(crate::icons::spec("pilcrow"))
.tooltip(tl!("Paragraph Tools").to_string())
.arrangement(Arrangement::Stacked);
menu_button(ui, face, tl!("Paragraph Tools").to_string(), None, |ui, _| {
+1 -1
View File
@@ -199,7 +199,7 @@ pub(super) fn developer(row: &mut RibbonRow<'_>, app: &mut WordApp) {
for cells in rows {
Row::new().show(ui, |ui, _| {
for (icon_name, id) in cells {
IconButton::command(crate::icons::id(icon_name), CommandRef::new(id)).show(ui);
IconButton::command(crate::icons::spec(icon_name), CommandRef::new(id)).show(ui);
}
});
}
+11 -3
View File
@@ -1911,6 +1911,7 @@ fn window_close_save_as_that_fails_says_so_and_keeps_the_document() {
/// #1445: the prompt that comes back after a failed save shows the reason on screen.
#[test]
fn save_prompt_shows_why_the_save_failed() {
use egui_kittest::kittest::NodeT;
let dir = scratch("prompt-reason");
let blocker = dir.join("folder");
std::fs::write(&blocker, b"not a folder").unwrap();
@@ -1923,7 +1924,13 @@ fn save_prompt_shows_why_the_save_failed() {
h.run_steps(4);
// The prompt shows it, and so does the status line the failed save wrote it to (`prompt_message` above is the prompt's own).
assert!(h.query_all_by_label(reason.as_str()).next().is_some(), "the reason is in the prompt");
assert!(h.query_by_label("Save").is_some(), "Save again is offered");
// The accepting button: the platform's word for Save (the framework asks Yes, No, Cancel off macOS). macOS also
// keeps a hidden, greyed Save in the title bar, so ask for the one on screen.
let accept = if cfg!(target_os = "macos") { "Save" } else { "Yes" };
let offered = h
.query_all_by_role_and_label(egui::accesskit::Role::Button, accept)
.any(|n| !n.accesskit_node().is_hidden() && !n.accesskit_node().is_disabled());
assert!(offered, "{accept} again is offered");
let _ = std::fs::remove_dir_all(&dir);
}
@@ -2012,8 +2019,9 @@ fn the_default_app_button_shows_only_with_the_hosts_hook() {
);
h.run_steps(4);
assert!(h.query_by_label("Show the community button in the title bar").is_some(), "hook {hook}: the Options page rendered");
// The framework's button and the row that holds it can both carry the label.
assert_eq!(h.query_all_by_label(LABEL).next().is_some(), hook, "hook {hook}: the button");
// The row carries the label too (macOS shows it, with Finder's steps instead of a button): ask for the button.
let button = h.query_all_by_role_and_label(egui::accesskit::Role::Button, LABEL).next().is_some();
assert_eq!(button, hook, "hook {hook}: the button");
if hook {
// The button itself, not the row that carries its label.
h.get_by_role_and_label(egui::accesskit::Role::Button, LABEL).click();
+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
+3 -1
View File
File diff suppressed because one or more lines are too long
+16 -1
View File
@@ -1,6 +1,6 @@
# Installing languages and spelling dictionaries
> **Last reviewed:** 2026-10-16 · **Last updated:** 2026-11-03 · **Change:** trivial (Language packs are installed from Your languages and Add a language…; the Dictionaries folder is in Options › Language); previously trivial (Language packs: the missing-pack bar works on a fresh install and counts the caret's language); previously trivial (Language packs: language-packs-2 is published and pinned: 75 packs, adding Danish, German (Germany, Austria, Switzerland), Esperanto, Estonian, Persian, Croatian, Hungarian, Norwegian (Bokmål, Nynorsk), Dutch and Swedish (Sweden, Finland); Mongolian and Thai aren't packs yet); previously trivial (Language packs: the first set, language-packs-1, is published and pinned: 61 languages, and which aren't packs yet); previously minor (Language packs: install a language's spelling and hyphenation from File › Options › Language, or from the bar a document in that language shows; they are searched after the dictionaries folder and before the system's dictionaries; previously trivial: the Flatpak's own dictionaries folder; previously trivial: WordCraft's own dictionaries folder is searched on macOS and Linux too, as on Windows, so a dictionary dropped there works without a setting; previously minor: ISO 8859-9 Turkish dictionaries are read, #3692; previously minor: Spanish: `es_ES`, `es_MX`, `es_419` and `es_UY` with their fallbacks, #3360, #3553; previously trivial: every Hunspell language shows (no dictionary), not only Polish and Portuguese, and Indonesian is listed, #3150; previously trivial: ISO 8859-1 dictionaries are read, #2824)
> **Last reviewed:** 2026-10-16 · **Last updated:** 2026-11-20 · **Change:** trivial (The Dictionary file field in File › Options › Proofing shows the saved path whenever no edit is open: a path typed but not committed is dropped when the saved path changes or the pane is left, #5899); previously trivial (Freestanding custom dictionary file support in File › Options › Proofing, supporting plain UTF-8 and Word CUSTOM.DIC UTF-16LE with BOM; other encodings are refused without touching the file, #5840); previously trivial (Language packs are installed from Your languages and Add a language…; the Dictionaries folder is in Options › Language); previously trivial (Language packs: the missing-pack bar works on a fresh install and counts the caret's language); previously trivial (Language packs: language-packs-2 is published and pinned: 75 packs, adding Danish, German (Germany, Austria, Switzerland), Esperanto, Estonian, Persian, Croatian, Hungarian, Norwegian (Bokmål, Nynorsk), Dutch and Swedish (Sweden, Finland); Mongolian and Thai aren't packs yet); previously trivial (Language packs: the first set, language-packs-1, is published and pinned: 61 languages, and which aren't packs yet); previously minor (Language packs: install a language's spelling and hyphenation from File › Options › Language, or from the bar a document in that language shows; they are searched after the dictionaries folder and before the system's dictionaries; previously trivial: the Flatpak's own dictionaries folder; previously trivial: WordCraft's own dictionaries folder is searched on macOS and Linux too, as on Windows, so a dictionary dropped there works without a setting; previously minor: ISO 8859-9 Turkish dictionaries are read, #3692; previously minor: Spanish: `es_ES`, `es_MX`, `es_419` and `es_UY` with their fallbacks, #3360, #3553; previously trivial: every Hunspell language shows (no dictionary), not only Polish and Portuguese, and Indonesian is listed, #3150; previously trivial: ISO 8859-1 dictionaries are read, #2824)
English spelling works out of the box. Polish, Russian, Portuguese, Czech, Italian, Croatian,
Turkish, Indonesian and Spanish spelling use a standard **Hunspell** dictionary (an `.aff` and a `.dic` file) that
@@ -172,6 +172,19 @@ Other languages work the same way: replace `pt_BR` with the language's folder an
from the LibreOffice repository (for example `it_IT/it_IT.aff`; the Spanish ones are all in
`es/`, for example `es/es_MX.aff`).
## Custom word dictionary (custom.dic)
Words added via **Add to Dictionary** or through `review.addToDictionary` are kept in a custom dictionary.
By default, WordCraft saves them to `custom-dictionary.txt` in the settings folder.
To use an existing freestanding custom dictionary (such as Microsoft Word's `CUSTOM.DIC`):
1. Open **File › Options › Proofing**.
2. Under **Custom dictionary**, set **Dictionary file** to the path of your `.dic` or text file and press **Enter** (or click out of the field). The path is saved then, not while you type. Absolute paths or `~/` paths (expanded via `HOME` or `USERPROFILE`) are supported.
3. Words in that dictionary are checked in conjunction with the main dictionary, and new additions persist back to the file. Switching dictionaries clears previously loaded custom words from memory and loads the words from the newly selected file.
4. Emptying the field and pressing **Enter** (or setting `"customDictionary": "auto"`) means automatic: it reverts to the default settings folder, reloading the words from `custom-dictionary.txt`.
WordCraft supports plain UTF-8 word lists as well as UTF-16LE with BOM (`[0xFF, 0xFE]`), UTF-16BE with BOM (`[0xFE, 0xFF]`), and UTF-8 with BOM, preserving the file's original encoding when saving additions or removals. Lines that do not conform to valid single words (such as comments or malformed entries) are ignored during spellchecking, but existing lines are preserved verbatim when saving back so that custom dictionaries shared with Word retain non-word lines, comments, and original casing. Files in another encoding (for example Windows-1252/ANSI) are refused with an error and left untouched rather than guessed: convert such a file to UTF-8 once and select it again. The chosen file must also be a regular, writable file within the automation roots; symbolic links and read-only files are refused. If a save is refused at run time, the new word stays in the in-memory dictionary for the session and the reason is written to the log, so Add to Dictionary never fails or loses the word mid-session.
## Checking that it works
- Restart WordCraft. The status bar no longer says **(no dictionary)**, and a misspelled word
@@ -193,6 +206,8 @@ Never commit dictionary files to this repository: they stay on the user's system
| Date | Change | Summary |
|---|---|---|
| 2026-11-20 | trivial | The Dictionary file field shows the saved path whenever no edit is open: a typed path that was not committed does not survive a change to the saved path (an agent's `file.options`) or leaving the pane, and Enter does not overwrite the new value (#5899) |
| 2026-11-07 | trivial | Freestanding custom dictionary file support in File › Options › Proofing, supporting plain UTF-8 and Word CUSTOM.DIC UTF-16LE with BOM; other encodings are refused without touching the file (#5840) |
| 2026-11-03 | trivial | Language packs (CP4.3): the missing-pack bar offers a language before the list is fetched and gets the list, then the pack, on Install; a missing or stale list is fetched once while downloading is on; the caret's typing language counts |
| 2026-11-03 | trivial | Language packs: install from Your languages or Add a language… in Options › Language; the Dictionaries folder is in Options › Language, not Proofing |
| 2026-11-03 | trivial | Language packs: language-packs-2 is published and pinned (75 languages, adding the compounding languages); Mongolian and Thai aren't packs yet, and why |
+3 -2
View File
@@ -1,6 +1,6 @@
# WordCraft parity with Microsoft Word
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** trivial (Equations: `\int` + Space leaves ∫ waiting for its limits, `_a^b` then Space builds them, and the operand typed next goes inside, observed in Word for Windows on #4938, #4917; no percentage change; previously trivial: Tables row: Table Properties applies to the selected rows, columns and cells, #4857; no percentage change); previously trivial (Tables row: tables nest 18 deep at most, so a .json save reads back, #3618); previously trivial (Tables row: Table Properties applies to the selected rows, columns and cells, #4857; no percentage change); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (Insert Table of Figures lists any caption label, #3013; previously trivial: Performance row: typing no longer starts render threads on every repaint, #3027; previously trivial: shapes inserted in a row are all kept, #2019; previously trivial: East Asian typography: `w:eastAsianLayout` kept on save, not laid out; previously trivial: Ink to Shape recognises arrows; previously trivial: Windows Magnifier follows the caret onto a new line, #1119; previously trivial: table border drags with Ctrl and Alt, from the left edge and of selected cells, #711; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: all 12 bibliography styles, #383; previously trivial: formatting revisions landed, #41; previously trivial: Draw Table and Eraser landed, #303; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; replaces the parity tables that lived in ROADMAP.md) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** trivial (Proofing: freestanding custom dictionary file support, #5840; previously trivial: Equations: `\int` + Space leaves ∫ waiting for its limits, `_a^b` then Space builds them, and the operand typed next goes inside, observed in Word for Windows on #4938, #4917; no percentage change; previously trivial: Tables row: Table Properties applies to the selected rows, columns and cells, #4857; no percentage change); previously trivial (Tables row: tables nest 18 deep at most, so a .json save reads back, #3618); previously trivial (Tables row: Table Properties applies to the selected rows, columns and cells, #4857; no percentage change); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (Insert Table of Figures lists any caption label, #3013; previously trivial: Performance row: typing no longer starts render threads on every repaint, #3027; previously trivial: shapes inserted in a row are all kept, #2019; previously trivial: East Asian typography: `w:eastAsianLayout` kept on save, not laid out; previously trivial: Ink to Shape recognises arrows; previously trivial: Windows Magnifier follows the caret onto a new line, #1119; previously trivial: table border drags with Ctrl and Alt, from the left edge and of selected cells, #711; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: all 12 bibliography styles, #383; previously trivial: formatting revisions landed, #41; previously trivial: Draw Table and Eraser landed, #303; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; replaces the parity tables that lived in ROADMAP.md) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4
The authoritative assessment of how close WordCraft is to Microsoft Word. [`ROADMAP.md`](../ROADMAP.md)
summarizes it; [`gaps.md`](gaps.md) itemizes every shortfall; the deep checklists are
@@ -68,7 +68,7 @@ full parity for the area.
| Footnotes and endnotes | 3 | 60% | 60% | 3–5 | Placed and editable, numbers from Word files (#103); long notes continue onto the next page under the continuation separator (#352). Footnote and Endnote dialog with options per section: below text, end of section, number format, start at, restart each section or page, custom mark, convert (#385). |
| References (TOC, citations, bibliography, captions, index, TOA) | 5 | 65% | 60% | 12–20 | Working first versions, Zotero integration (#189), Zotero/Mendeley `ADDIN` fields round-trip. Caption, Index, Mark Entry, Custom TOC, Table of Figures and Create/Edit Source dialogs; updates honour the TOC (`\o \u \t \f \n \p \h`), table of figures (`\c \a \n \p`, any caption label, so a list of tables sits beside a list of figures; #3013), INDEX (`\c \e \h \r`), XE (`\b \i \t \r`) and SEQ/STYLEREF chapter switches (#402); Insert Caption… on the right-click menu of pictures, shapes, text boxes and charts (#1230). All 12 of Word's bibliography styles (APA, MLA, Chicago, IEEE, Harvard, ISO 690 author-date and numerical, Turabian, GB/T 7714, GOST name and title sort, SIST02; #383); bibliography sources saved in DOCX (#790). Manage Sources imports Word's bibliography file (`b:Sources`, `Sources.xml`, #2640). |
| Review (proofing UI, comments, track changes, compare, protect) | 8 | 72% | 75% | 15–25 | Comment balloons, tracked insert/delete incl. paragraph marks (#244, #125), Compare / Combine with comparison settings (case, white space, formatting, tables, word or character level, #412), Restrict Editing pane with formatting and editing restrictions, exceptions for everyone and a password (#412). Formatting revisions (#41): kept in DOCX, recorded while tracking, accepted/rejected, "Formatted: …" balloons and change bars. Moves (#400): kept in DOCX, recorded on a tracked cut and paste, accepted/rejected at either end, green markup and "Moved from/to" balloons. Show revisions in balloons takes tracked deletions in the body out of the text into "Deleted: …" balloons (insertions stay inline, as in Word; deletions in headers, footers, notes and text boxes, and in print and PDF, stay inline). Missing: drag-and-drop moves, insert/delete balloons, Translate, Block Authors, modern comment threads/mentions. Lowered: these gaps are confirmed by source (no `rPrChange` anywhere). |
| Proofing (spelling, grammar, thesaurus, languages) | 5 | 44% | (in Review) | 20–40 | English, Polish, Portuguese, Italian and Czech (system Hunspell, #1048), chosen per run from its language (`w:lang`): English word list (Moby plus our supplement of modern words such as "desktop", #520) and rule-based grammar; Polish against the installed Hunspell dictionary through a Hunspell-style affix engine, Polish grammar rules and TeX hyphenation patterns (2026-10-10); Portuguese (pt-BR) against the installed VERO Hunspell dictionary — the affix engine reads its `FLAG UTF-8` flags, continuation classes and forbidden spellings — with accent-first suggestions, conservative grammar rules and TeX patterns (2026-10-12); Italian (it-IT) against the installed Hunspell dictionary through the same affix engine, with accent-first suggestions and conservative grammar rules. Other languages are left unmarked. The custom dictionary persists across sessions (#40). Word ships 120 proofing tools for ~50 languages plus Editor (style refinements, similarity). Issues #25, #40, #100. |
| Proofing (spelling, grammar, thesaurus, languages) | 5 | 44% | (in Review) | 20–40 | English, Polish, Portuguese, Italian and Czech (system Hunspell, #1048), chosen per run from its language (`w:lang`): English word list (Moby plus our supplement of modern words such as "desktop", #520) and rule-based grammar; Polish against the installed Hunspell dictionary through a Hunspell-style affix engine, Polish grammar rules and TeX hyphenation patterns (2026-10-10); Portuguese (pt-BR) against the installed VERO Hunspell dictionary — the affix engine reads its `FLAG UTF-8` flags, continuation classes and forbidden spellings — with accent-first suggestions, conservative grammar rules and TeX patterns (2026-10-12); Italian (it-IT) against the installed Hunspell dictionary through the same affix engine, with accent-first suggestions and conservative grammar rules. Other languages are left unmarked. The custom dictionary persists across sessions (#40), and freestanding custom dictionary files (such as Microsoft Word's CUSTOM.DIC in UTF-16LE with BOM) can be selected in File › Options › Proofing (#5840). Word ships 120 proofing tools for ~50 languages plus Editor (style refinements, similarity). Issues #25, #40, #100. |
| Mailings | 2 | 70% | 70% | 6–10 | Mail merge from CSV, fields, rules (IF, SKIPIF, NEXT, NEXTIF, evaluated alike in preview and merge), fields in headers/footers (one section per letter), preview, envelopes, labels. Select Recipients takes a typed list or CSV (#247); no Excel/Outlook/Contacts data sources, no email merge. |
| Pictures, shapes, text boxes, WordArt | 6 | 60% | 60% | 20–30 | Insert, crop, recolour, styles, floating placement like Word (#136), wrap (square/top-bottom/behind/front), text boxes edit and overflow (#46), VML text boxes (#242), free rotation and flips with a rotation handle (#332), WordArt: text fill (solid, gradient, none), outline, shadow, glow and reflection with our own styles, and Transform warps along arch, circle, wave, slant, inflate/deflate, chevron and triangle (other presets kept and drawn flat), connectors (straight, elbow, curved, arrowheads) glued to shapes' connection sites and re-routed when those move (#416). Missing: tight/through contour wrap, rotated text-box text, group (#267 open), shape effects, WordArt 3-D/bevel and editing text in its bent form, connector routing around shapes, Drawing Canvas, Icons, online pictures, screenshot. |
| Mailings | 2 | 70% | 70% | 6–10 | Mail merge from CSV, fields, rules (IF, SKIPIF, NEXT, NEXTIF, evaluated alike in preview and merge), fields in headers/footers (one section per letter), preview, envelopes, labels. Select Recipients takes a typed list, CSV (#247) or a sheet of an Excel (.xlsx/.xlsm) or OpenDocument (.ods) workbook, with Select Table to pick the sheet (#334); no Outlook/Contacts/Access data sources, no email merge. |
@@ -324,3 +324,4 @@ can be used without committing Word output.
| 2026-10-10 | major | Created from ROADMAP.md's "Parity by area" and "Estimate to 100%" sections; full re-measure against Word for Mac 16.113.4 (bundle listing, catalog diff from source, issue tracker); split into feature depth (67%) and ready for real work (60%); added proofing, East Asian, accessibility areas and the dimension table; hours re-calibrated from PR history |
| 2026-10-06 | major | First estimate in ROADMAP.md: ~62% real feature parity, 120–150 h to 100% |
| 2026-10-29 | trivial | Tables row: Table Properties' row, column and cell settings apply to the selection, as in Word (#4857); no percentage change |
| 2026-11-07 | trivial | Proofing: freestanding custom dictionary file support (plain UTF-8 and Word CUSTOM.DIC UTF-16LE with BOM) in File › Options › Proofing (#5840); no percentage change |
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