Compare commits

...
6 Commits
Author SHA1 Message Date
Martin Ball 0360a71277 Merge branch 'main' into land/5186 2026-11-17 06:19:13 +01:00
ljkxandClaude Opus 5.5 93bf14883c #3773: a WordCraft process saves only the preferences it changed (#5258)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 06:06:04 +01:00
Marc 0cb315edaf fix(ui): Recent shortens long names and paths to the row (#5212) (#5321) 2026-11-17 05:53:08 +01:00
.CooCoo 2dd0f9a67b Field dialog: text fields have a Format list for capitalization (#5062) 2026-11-17 05:37:06 +01:00
Mex 739cdcad0b M15: correct English proofing credits in README (#6681) 2026-11-17 05:15:46 +01:00
395a0c9895 Layout › Paragraph: dragging an Indent or Spacing box is one undo step (#5171) (#5186)
Lands #5186 by @D13GOOOO (approved by @benandez), rebased onto main; only the docs conflicts in ROADMAP.md, docs/ui-parity.md were resolved, keeping both sides.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: D13GOOOO <106814760+D13GOOOO@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCXtSjB6e5jmy9Uq7u8
2026-11-17 02:42:00 +00:00
13 changed files with 1492 additions and 52 deletions
+4 -2
View File
@@ -451,8 +451,10 @@ Copyright (c) 2026 ArtCraft Team and the WordCraft contributors. Required notice
Bundled fonts, icons, images and other assets keep their own open licenses; each one is listed
with its author, source and license in [ATTRIBUTION.md](ATTRIBUTION.md).
The English spelling dictionary and hyphenation come from Grady Ward's public-domain Moby
Hyphenator II word list. Polish spelling reads the Hunspell `pl_PL` dictionary installed on the system (not bundled), as
English spelling first tries a matching Hunspell dictionary from the Dictionaries folder.
Otherwise it uses dialect-specific SCOWL 2026 dictionaries when built with language data;
without it, spelling falls back to system Hunspell dictionaries or Grady Ward's public-domain
Moby Hyphenator II word list. English hyphenation uses the Moby list and patterns trained from it. Polish spelling reads the Hunspell `pl_PL` dictionary installed on the system (not bundled), as
do Russian, Portuguese, Czech, Italian, Croatian and Turkish spelling (how to install them:
[docs/spelling-dictionaries.md](docs/spelling-dictionaries.md)), and
Polish hyphenation the TeX patterns by Hanna Kołodziejska, Bogusław Jackowski and Marek Ryćko (MIT
+5 -1
View File
File diff suppressed because one or more lines are too long
+164 -16
View File
@@ -23,6 +23,7 @@ mod graphics;
mod logging;
#[cfg(all(unix, not(target_os = "macos")))]
mod portal_save;
mod prefs_merge;
mod print;
mod region;
#[cfg(target_os = "macos")]
@@ -222,31 +223,44 @@ fn user_dict_path() -> Option<std::path::PathBuf> {
wordcraft_control_key::settings_dir().map(|b| b.join(wordcraft_engine::Session::USER_DICT_FILE))
}
fn load_user_dictionary(app: &mut WordApp) {
if !prefs_enabled() {
return;
}
if let Some(p) = user_dict_path() {
wordcraft_proof::load_user_dictionary(&p);
app.session.user_dict_path = Some(p);
}
}
/// Runs without preferences (`WORDCRAFT_NO_PREFS`, agents' test runs) neither read nor write them.
fn prefs_enabled() -> bool {
std::env::var_os("WORDCRAFT_NO_PREFS").is_none()
}
/// The preferences as this process last loaded or saved them, which `save_prefs` compares with
/// to write only what this process changed since (#3773, see `prefs_merge`).
static LOADED_PREFS: std::sync::Mutex<Option<serde_json::Value>> = std::sync::Mutex::new(None);
/// Apply the saved preferences (`ui.json`) and the user dictionary to `app`, and remember the
/// result for `save_prefs`. Runs without preferences neither read nor keep them.
fn load_prefs(app: &mut WordApp) {
if !prefs_enabled() {
return;
}
if let Some(p) = prefs_path()
&& let Ok(bytes) = std::fs::read(&p)
let loaded = load_prefs_from(app, prefs_path().as_deref(), user_dict_path());
if let Ok(mut slot) = LOADED_PREFS.lock() {
*slot = loaded;
}
}
/// Apply the preferences saved at `prefs` to `app`, then load the user dictionary at `dict`
/// (`custom-dictionary.txt`, #40), and give back the preferences as `prefs()` does after both:
/// the words only the dictionary file has are part of what was loaded, so a word another process
/// removes from `ui.json` isn't written back as one added here (#3773).
fn load_prefs_from(app: &mut WordApp, prefs: Option<&std::path::Path>, dict: Option<std::path::PathBuf>) -> Option<serde_json::Value> {
if let Some(p) = prefs
&& let Ok(bytes) = std::fs::read(p)
&& let Some(ui) = UiState::from_json(&bytes)
{
app.apply_prefs(ui);
}
if let Some(p) = dict {
wordcraft_proof::load_user_dictionary(&p);
app.session.user_dict_path = Some(p);
}
// As `prefs()` gives them back, so a setting nobody touched compares equal at exit.
serde_json::to_value(app.prefs()).ok()
}
/// Fonts the user added (#582) live in `fonts` in the settings folder: load them, and store fonts
@@ -332,6 +346,8 @@ fn x11_libraries() -> Result<(), String> {
if missing.is_empty() { Ok(()) } else { Err(missing.join("; ")) }
}
/// Write `app`'s preferences to `ui.json`, merged with what other processes saved since this one
/// loaded it (`merged_prefs`).
fn save_prefs(app: &WordApp) {
if let Err(e) = try_save_prefs(app) {
log::warn!("preferences: {e}");
@@ -348,11 +364,79 @@ fn try_save_prefs(app: &WordApp) -> Result<bool, String> {
if let Some(dir) = p.parent() {
std::fs::create_dir_all(dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
}
let bytes = serde_json::to_vec_pretty(&app.prefs()).map_err(|e| format!("cannot serialize: {e}"))?;
write_prefs(&p, &bytes).map_err(|e| format!("cannot save {}: {e}", p.display()))?;
let ours = serde_json::to_value(app.prefs()).map_err(|e| format!("cannot serialize: {e}"))?;
let mut base = LOADED_PREFS.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
save_merged(&p, &mut base, ours)?;
Ok(true)
}
/// Writes `ours` to `path`, merged with what other WordCraft processes saved there since this one
/// loaded or saved `base` (`merged_prefs`), and makes `ours` the new `base`: a setting changed here
/// before this save and by another process after it then takes the other's value at the next save.
/// Holds `lock_prefs` from the read to the rename.
fn save_merged(path: &std::path::Path, base: &mut Option<serde_json::Value>, ours: serde_json::Value) -> Result<(), String> {
let _lock = lock_prefs(path);
let merged = merged_prefs(path, base.as_ref(), ours.clone());
let bytes = serde_json::to_vec_pretty(&merged).map_err(|e| format!("cannot serialize: {e}"))?;
write_prefs(path, &bytes).map_err(|e| format!("cannot save {}: {e}", path.display()))?;
*base = Some(ours);
Ok(())
}
/// `ours` with what other WordCraft processes saved to `path` since this one loaded or saved
/// `base`, for the settings this one left alone (#3773, see `prefs_merge`). `ours` as it is when
/// there's no `base`, or the file is missing or isn't preferences now.
fn merged_prefs(path: &std::path::Path, base: Option<&serde_json::Value>, ours: serde_json::Value) -> serde_json::Value {
let Some(base) = base else { return ours };
let disk = match std::fs::read(path) {
Ok(bytes) => prefs_merge::as_read(&bytes),
Err(e) => {
if e.kind() != std::io::ErrorKind::NotFound {
log::debug!("preferences: cannot read {} to merge, saving this process's: {e}", path.display());
}
return ours;
}
};
match disk {
Some(disk) => prefs_merge::merge(base, ours, &disk),
None => {
log::debug!("preferences: {} isn't preferences, saving this process's", path.display());
ours
}
}
}
/// How long a save waits for another process's save to finish before going ahead anyway: a save
/// takes milliseconds, and a process stuck holding the lock mustn't stop this one from saving.
const PREFS_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(2);
/// An advisory lock beside `path` (`.ui.json.lock`), held while it is returned, so that two
/// processes saving at once (logging out closes every window together) take turns at reading,
/// merging and replacing `ui.json` instead of one losing the other's changes. `None` (save
/// unlocked) when the lock file can't be opened or the lock isn't free within [`PREFS_LOCK_WAIT`].
fn lock_prefs(path: &std::path::Path) -> Option<std::fs::File> {
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "ui.json".into());
let lock = path.with_file_name(format!(".{name}.lock"));
let file = match std::fs::OpenOptions::new().create(true).truncate(false).write(true).open(&lock) {
Ok(f) => f,
Err(e) => {
log::debug!("preferences: cannot open {}, saving without it: {e}", lock.display());
return None;
}
};
let start = std::time::Instant::now();
loop {
match file.try_lock() {
Ok(()) => return Some(file),
Err(std::fs::TryLockError::WouldBlock) if start.elapsed() < PREFS_LOCK_WAIT => std::thread::sleep(std::time::Duration::from_millis(10)),
Err(e) => {
log::warn!("preferences: {} is held, saving without it: {e}", lock.display());
return None;
}
}
}
}
/// Writes `bytes` to a sibling temporary file and renames it over `path`, so a failed or
/// interrupted write leaves the previous preferences in place.
fn write_prefs(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
@@ -626,7 +710,6 @@ fn main() -> eframe::Result {
if updates_unsafe {
app.disable_self_update();
}
load_user_dictionary(&mut app);
// Language packs from the suite's font store; an Install click is the person's own.
wordcraft_engine::packs::use_font_store(true);
// A region chosen in File › Options replaces the system's for the first blank
@@ -839,7 +922,72 @@ mod launch_arg_tests {
#[cfg(test)]
mod prefs_tests {
use super::write_prefs;
use serde_json::{Value, json};
use wordcraft_ui_egui::{UiState, theme::Appearance};
use super::{load_prefs_from, lock_prefs, prefs_merge, save_merged, write_prefs};
/// The preferences saved with `theme` (every other setting at its default).
fn with_theme(theme: &str) -> Value {
prefs_merge::as_read(&serde_json::to_vec(&json!({"theme": theme})).unwrap()).unwrap()
}
/// The theme the next process loads from `path`.
fn saved_theme(path: &std::path::Path) -> Appearance {
UiState::from_json(&std::fs::read(path).unwrap()).unwrap().theme
}
#[test]
fn a_setting_changed_by_another_process_after_a_save_here_keeps_its_value() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("ui.json");
std::fs::write(&path, serde_json::to_vec(&with_theme("light")).unwrap()).unwrap();
// A loads Light, switches to Dark and saves before exiting (taking a document off the
// recent list does).
let mut a = Some(with_theme("light"));
save_merged(&path, &mut a, with_theme("dark")).unwrap();
assert_eq!(saved_theme(&path), Appearance::Dark);
// B starts, loads Dark, switches to Light and exits.
save_merged(&path, &mut Some(with_theme("dark")), with_theme("light")).unwrap();
// A exits without touching the theme since its save: B's choice, made later, stays.
save_merged(&path, &mut a, with_theme("dark")).unwrap();
assert_eq!(saved_theme(&path), Appearance::Light);
}
#[test]
fn the_loaded_preferences_include_the_words_of_the_dictionary_file() {
// A word only `custom-dictionary.txt` has is loaded, not added here: if another process
// removes it from `ui.json`, this one mustn't write it back.
let dir = tempfile::tempdir().unwrap();
let (prefs, dict) = (dir.path().join("ui.json"), dir.path().join("custom-dictionary.txt"));
std::fs::write(&prefs, br#"{"dictionary": ["zqxinjson"]}"#).unwrap();
std::fs::write(&dict, "zqxinfile\n").unwrap();
let mut app = wordcraft_ui_egui::WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
let loaded = load_prefs_from(&mut app, Some(&prefs), Some(dict)).unwrap();
let words = loaded["dictionary"].as_array().unwrap();
for word in ["zqxinjson", "zqxinfile"] {
assert!(words.contains(&json!(word)), "{word}: {words:?}");
}
wordcraft_engine::proof::remove_word("zqxinjson");
wordcraft_engine::proof::remove_word("zqxinfile");
}
#[test]
fn a_save_waits_for_another_process_saving_at_the_same_moment() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("ui.json");
// Another process is between reading and replacing `ui.json`.
let held = lock_prefs(&path).expect("the lock is free");
let saver = {
let path = path.clone();
std::thread::spawn(move || save_merged(&path, &mut None, with_theme("dark")))
};
std::thread::sleep(std::time::Duration::from_millis(200));
assert!(!path.exists(), "saved while another process held the lock");
drop(held);
saver.join().unwrap().unwrap();
assert_eq!(saved_theme(&path), Appearance::Dark);
}
#[test]
fn failed_preferences_write_keeps_the_old_file_and_reports_the_error() {
+550
View File
@@ -0,0 +1,550 @@
//! Several WordCraft processes share one `ui.json` (opening a file from the file manager starts
//! another). Each reads it at start-up and writes it at exit (and when a change must survive a
//! crash, like taking a document off the recent list), so without a merge the process that writes
//! last writes back what it loaded and loses the others' changes (#3773).
//!
//! The policy: when saving, read `ui.json` again as this version reads it ([`as_read`]: a setting
//! of the wrong type reads as its default, and keys it doesn't know or reads only to migrate are
//! left out), and write it with only what this process changed since it last loaded or saved its
//! preferences (`base`). Every other setting keeps what the file holds now, including the absence
//! of one another process removed (a shortcut, a task pane's place).
//!
//! - A setting both changed takes this process's value.
//! - Groups of settings (editing options, AutoCorrect's switches, keyboard shortcuts, the ribbon,
//! task pane places) merge entry by entry ([`rule`]). Any other object is one setting: the
//! window's size and place, or one task pane's place, are never mixed from two processes.
//! - Lists of user entries (AutoCorrect entries by the text they replace, its exceptions, removed
//! built-in shortcuts, ribbon tabs by name, Quick Access Toolbar commands, caption labels, pens,
//! custom dictionary words) merge entry by entry too ([`merge_entries`]): entries either process
//! added are kept, entries either process removed stay removed, and an entry both changed takes
//! this process's version. A ribbon or toolbar left as it comes counts as its default entries.
//! - Recent lists (documents, symbols, colours, fonts) take the entries this process added or used
//! again first, then the file's, without duplicates, without the entries this process removed,
//! and within each list's limit ([`merge_recent`]).
//! - Any other list (the task panes' order, a floating pane's rectangle) is one setting.
//!
//! What this process changed is found by comparing with `base`, not by recording each change: a
//! setting changed and then changed back counts as untouched, so the file's value stays, and a
//! recent entry used again without moving (it was already first) counts as not used.
use std::collections::{HashMap, HashSet};
use serde_json::{Map, Value};
use wordcraft_engine::ribbon::{DEFAULT_QAT, RibbonLayout};
use wordcraft_ui_egui::{MAX_RECENT, MAX_RECENT_FONTS, UiState, colors, dialogs_insert};
/// Whether two entries of a recent list are the same entry.
type Same = fn(&Value, &Value) -> bool;
/// What tells an entry of a list of user entries from the others. Entries with the same key are
/// told apart by their order ([`ids`]).
type Key = fn(&Value) -> String;
/// How a setting this process changed merges with the file's.
#[derive(Clone, Copy)]
enum Rule {
/// A group of settings: each entry on its own.
Group,
/// A recent list, most recent first: how many entries it keeps, and when two are the same.
Recent(usize, Same),
/// A list of user entries: each entry on its own.
Entries(Key),
/// One setting: this process's value.
Whole,
}
/// The rule for the setting at `path` (`ui.json`'s keys from the top).
fn rule(path: &[&str]) -> Rule {
match path {
[] | ["editing" | "keyboard" | "ribbon" | "panePlaces"] | ["editing", "markup" | "marks" | "autocorrect"] | ["keyboard", "assigned"] => {
Rule::Group
}
["recent"] => Rule::Recent(MAX_RECENT, same_entry),
["recentSymbols"] => Rule::Recent(dialogs_insert::RECENT_SYMBOLS, same_entry),
["recentColors"] => Rule::Recent(colors::RECENT_MAX, same_entry),
["recentFonts"] => Rule::Recent(MAX_RECENT_FONTS, same_font),
["editing", "autocorrect", "entries"] => Rule::Entries(replaced_text),
["ribbon", "tabs"] => Rule::Entries(tab_name),
["editing", "autocorrect", "removed" | "exceptions" | "exceptionsRemoved" | "initialCapsExceptions"]
| ["keyboard", "removed"]
| ["ribbon", "qat"]
| ["captionLabels" | "inkPens" | "dictionary"] => Rule::Entries(whole_entry),
_ => Rule::Whole,
}
}
/// What a setting saved only when it isn't its default stands for when it is missing: the
/// default ribbon tabs and Quick Access Toolbar, so that two processes customizing them from the
/// default merge entry by entry.
fn when_missing(path: &[&str]) -> Option<Value> {
match path {
["ribbon", "tabs"] => serde_json::to_value(RibbonLayout::default().tabs()).ok(),
["ribbon", "qat"] => serde_json::to_value(DEFAULT_QAT).ok(),
_ => None,
}
}
/// Entries saved alike (colours are saved normalised, `colors::push_recent`).
fn same_entry(a: &Value, b: &Value) -> bool {
a == b
}
/// Font names ignoring case, as `push_recent_font` compares them.
fn same_font(a: &Value, b: &Value) -> bool {
match (a.as_str(), b.as_str()) {
(Some(a), Some(b)) => a.to_lowercase() == b.to_lowercase(),
_ => a == b,
}
}
/// The entry as saved.
fn whole_entry(v: &Value) -> String {
v.to_string()
}
/// An AutoCorrect entry `[from, to]` by the text it replaces.
fn replaced_text(v: &Value) -> String {
v.get(0).unwrap_or(v).to_string()
}
/// A ribbon tab by its name, ignoring case as the ribbon does.
fn tab_name(v: &Value) -> String {
v.get("name").and_then(Value::as_str).map_or_else(|| v.to_string(), str::to_lowercase)
}
/// `ui.json`'s bytes as this version reads them, saved again: `None` when they aren't
/// preferences at all.
pub fn as_read(bytes: &[u8]) -> Option<Value> {
serde_json::to_value(UiState::from_json(bytes)?).ok()
}
/// The preferences to write: `ours` (this process's, now), with every value it left as it was in
/// `base` (what it last loaded or saved) taken from `disk` (what `ui.json` holds now, [`as_read`]).
pub fn merge(base: &Value, ours: Value, disk: &Value) -> Value {
let fallback = ours.clone();
merge_setting(&mut Vec::new(), Some(base), Some(ours), Some(disk)).unwrap_or(fallback)
}
/// One setting, at `path`. `None` for a setting left out (this process removed it, or it left it
/// alone and another process removed it).
fn merge_setting(path: &mut Vec<String>, base: Option<&Value>, ours: Option<Value>, disk: Option<&Value>) -> Option<Value> {
if base == ours.as_ref() {
// Unchanged here: whatever the file holds now.
return disk.cloned();
}
let ours = ours?;
let keys: Vec<&str> = path.iter().map(String::as_str).collect();
Some(match (rule(&keys), ours, base, disk) {
(Rule::Group, Value::Object(ours), Some(Value::Object(base)), Some(Value::Object(disk))) => {
Value::Object(merge_group(path, base, ours, disk))
}
(Rule::Recent(cap, same), Value::Array(ours), Some(Value::Array(base)), Some(Value::Array(disk))) => {
Value::Array(merge_recent(base, ours, disk, cap, same))
}
(Rule::Entries(key), Value::Array(ours), Some(Value::Array(base)), Some(Value::Array(disk))) => {
Value::Array(merge_entries(base, &ours, disk, key))
}
(_, ours, ..) => ours,
})
}
/// A group of settings, entry by entry: this process's entries in their order, then those only
/// the file or `base` has.
fn merge_group(path: &mut Vec<String>, base: &Map<String, Value>, mut ours: Map<String, Value>, disk: &Map<String, Value>) -> Map<String, Value> {
let mut names: Vec<String> = ours.keys().cloned().collect();
let mut seen: HashSet<String> = names.iter().cloned().collect();
for k in disk.keys().chain(base.keys()) {
if seen.insert(k.clone()) {
names.push(k.clone());
}
}
let mut merged = Map::new();
for k in names {
path.push(k.clone());
let keys: Vec<&str> = path.iter().map(String::as_str).collect();
let missing = when_missing(&keys);
let base_v = base.get(&k).cloned().or_else(|| missing.clone());
let disk_v = disk.get(&k).cloned().or_else(|| missing.clone());
let ours_v = ours.remove(&k).or_else(|| missing.clone());
let v = merge_setting(path, base_v.as_ref(), ours_v, disk_v.as_ref());
path.pop();
// A setting saved only when it isn't its default is left out when it is.
if let Some(v) = v.filter(|v| Some(v) != missing.as_ref()) {
merged.insert(k, v);
}
}
merged
}
/// A list entry: its key, and how many entries before it have the same key.
type Id = (String, usize);
/// The entries of `list` told apart by `key`, in order.
fn ids(list: &[Value], key: Key) -> Vec<Id> {
let mut seen: HashMap<String, usize> = HashMap::new();
list.iter()
.map(|v| {
let k = key(v);
let n = seen.entry(k.clone()).or_default();
*n += 1;
(k, *n - 1)
})
.collect()
}
/// A list of user entries, entry by entry. An entry either process added is kept, one either
/// removed stays removed, and one this process changed takes its version (else the file's). The
/// order is this process's if it reordered the entries it loaded, else the file's; an entry only
/// the other list has goes after the entry it follows there.
fn merge_entries(base: &[Value], ours: &[Value], disk: &[Value], key: Key) -> Vec<Value> {
let (base_ids, ours_ids, disk_ids) = (ids(base, key), ids(ours, key), ids(disk, key));
let index = |ids: &[Id], list: &[Value]| -> HashMap<Id, Value> { ids.iter().cloned().zip(list.iter().cloned()).collect() };
let (b, o, d) = (index(&base_ids, base), index(&ours_ids, ours), index(&disk_ids, disk));
let value = |id: &Id| -> Option<&Value> {
match (b.get(id), o.get(id), d.get(id)) {
// Left alone here: the file's, or gone if the other process removed it.
(Some(b), Some(o), d) if b == o => d,
// Added or changed here.
(_, Some(o), _) => Some(o),
// Removed here.
(Some(_), None, _) => None,
// Added there.
(None, None, d) => d,
}
};
let common = |ids: &[Id], other: &HashMap<Id, Value>| -> Vec<Id> { ids.iter().filter(|id| other.contains_key(*id)).cloned().collect() };
let reordered = common(&ours_ids, &b) != common(&base_ids, &o);
let (first, second) = if reordered { (&ours_ids, &disk_ids) } else { (&disk_ids, &ours_ids) };
let in_first: HashSet<&Id> = first.iter().collect();
let kept: HashSet<&Id> = first.iter().filter(|id| value(id).is_some()).collect();
// Entries only `second` has, by the kept entry they follow there (`None`: at the start).
let mut after: HashMap<Option<&Id>, Vec<&Id>> = HashMap::new();
let mut anchor = None;
for id in second {
if kept.contains(id) {
anchor = Some(id);
} else if !in_first.contains(id) && value(id).is_some() {
after.entry(anchor).or_default().push(id);
}
}
let mut merged = Vec::new();
let mut emit = |ids: &[&Id]| merged.extend(ids.iter().filter_map(|id| value(id).cloned()));
emit(after.get(&None).map_or(&[], Vec::as_slice));
for id in first.iter().filter(|id| kept.contains(id)) {
emit(&[id]);
emit(after.get(&Some(id)).map_or(&[], Vec::as_slice));
}
merged
}
/// The entries this process put at the front of `ours` ([`touched_len`]), then `disk`'s, leaving
/// out what this process removed (in `base` but no longer in `ours`), without duplicates and at
/// most `cap` entries. Entries are told apart by `same`.
fn merge_recent(base: &[Value], ours: Vec<Value>, disk: &[Value], cap: usize, same: Same) -> Vec<Value> {
let has = |list: &[Value], v: &Value| list.iter().any(|x| same(x, v));
let removed = |v: &Value| has(base, v) && !has(&ours, v);
let touched = &ours[..touched_len(base, &ours, same)];
let mut merged: Vec<Value> = Vec::new();
for v in touched.iter().cloned().chain(disk.iter().filter(|v| !removed(v)).cloned()) {
if merged.len() == cap {
break;
}
if !has(&merged, &v) {
merged.push(v);
}
}
merged
}
/// How many of `ours`'s first entries this process added or used again. Each use moves an entry
/// to the front of a recent list, so what it left alone is a tail of `ours` in `base`'s order: the
/// longest such tail is untouched, and everything before it (new entries, and entries that moved
/// ahead of one loaded before them) was touched. A use that leaves the order as it was loaded
/// (the first entry used again) can't be told from no use, and merges as none.
fn touched_len(base: &[Value], ours: &[Value], same: Same) -> usize {
let mut end = base.len();
for (i, v) in ours.iter().enumerate().rev() {
match base[..end].iter().rposition(|b| same(b, v)) {
Some(at) => end = at,
None => return i + 1,
}
}
0
}
#[cfg(test)]
mod tests {
use serde_json::{Value, json};
use wordcraft_ui_egui::UiState;
use super::{as_read, merge};
/// The preferences a process holds after loading a `ui.json` with `settings` (every other
/// setting at its default), as it saves them.
fn prefs(settings: Value) -> Value {
as_read(&serde_json::to_vec(&settings).unwrap()).unwrap()
}
/// What the next process loads from the merged preferences.
fn reloaded(merged: &Value) -> UiState {
UiState::from_json(&serde_json::to_vec(merged).unwrap()).unwrap()
}
/// `ui.json` after B and then A, which both loaded `loaded`, save `b` and `a`.
fn b_then_a(loaded: &Value, b: Value, a: Value) -> Value {
let after_b = merge(loaded, b, loaded);
merge(loaded, a, &after_b)
}
#[test]
fn two_processes_keep_each_others_changes() {
// #3773: A and B both start from the same file.
let loaded =
json!({"theme": "light", "author": "Ann", "recent": ["a.docx", "b.docx"], "editing": {"smartQuotes": true, "autoCapitalize": true}});
// B changes the theme and opens c.docx, then exits first.
let b = json!({"theme": "dark", "author": "Ann", "recent": ["c.docx", "a.docx", "b.docx"], "editing": {"smartQuotes": false, "autoCapitalize": true}});
// A changes the author name and opens d.docx, then exits.
let a = json!({"theme": "light", "author": "Bo", "recent": ["d.docx", "a.docx", "b.docx"], "editing": {"smartQuotes": true, "autoCapitalize": false}});
assert_eq!(
b_then_a(&loaded, b, a),
json!({"theme": "dark", "author": "Bo", "recent": ["d.docx", "c.docx", "a.docx", "b.docx"], "editing": {"smartQuotes": false, "autoCapitalize": false}})
);
}
#[test]
fn a_process_that_changed_nothing_writes_the_file_back_as_it_is() {
let loaded = json!({"theme": "light", "recent": ["a.docx"]});
let disk = json!({"theme": "dark", "recent": ["b.docx", "a.docx"]});
assert_eq!(merge(&loaded, loaded.clone(), &disk), disk);
}
#[test]
fn this_process_wins_a_setting_both_changed() {
let loaded = json!({"theme": "light"});
assert_eq!(merge(&loaded, json!({"theme": "system"}), &json!({"theme": "dark"})), json!({"theme": "system"}));
}
#[test]
fn a_setting_changed_and_changed_back_counts_as_untouched() {
// Changes are found by comparing with what was loaded: A switched to dark and back.
let loaded = json!({"theme": "light"});
assert_eq!(merge(&loaded, json!({"theme": "light"}), &json!({"theme": "dark"})), json!({"theme": "dark"}));
}
#[test]
fn a_recent_entry_removed_here_stays_removed() {
let loaded = json!({"recent": ["a.docx", "b.docx"]});
let ours = json!({"recent": ["b.docx"]});
let disk = json!({"recent": ["c.docx", "a.docx", "b.docx"]});
assert_eq!(merge(&loaded, ours, &disk), json!({"recent": ["c.docx", "b.docx"]}));
// Clear Recent clears what the other process had added too only if it was loaded here.
assert_eq!(merge(&loaded, json!({"recent": []}), &json!({"recent": ["c.docx", "a.docx", "b.docx"]})), json!({"recent": ["c.docx"]}));
}
#[test]
fn a_recent_entry_used_again_here_moves_to_the_front() {
// Applying a font already in Recently Used Fonts moves it to the front without adding one.
let loaded = json!({"recentFonts": ["A", "B"]});
assert_eq!(merge(&loaded, json!({"recentFonts": ["B", "A"]}), &loaded), json!({"recentFonts": ["B", "A"]}));
// Here C was used again, D opened and A removed; the other process used B again and added E.
let loaded = json!({"recent": ["a.docx", "b.docx", "c.docx"]});
let ours = json!({"recent": ["d.docx", "c.docx", "b.docx"]});
let disk = json!({"recent": ["e.docx", "b.docx", "a.docx", "c.docx"]});
assert_eq!(merge(&loaded, ours, &disk), json!({"recent": ["d.docx", "c.docx", "e.docx", "b.docx"]}));
// Entries this process only kept, in the order it loaded them, don't override the file's order.
let loaded = json!({"recentSymbols": ["x", "y", "z"]});
let ours = json!({"recentSymbols": ["w", "x", "z"]});
let disk = json!({"recentSymbols": ["z", "x", "y"]});
assert_eq!(merge(&loaded, ours, &disk), json!({"recentSymbols": ["w", "z", "x"]}));
}
#[test]
fn recent_fonts_are_one_entry_whatever_their_case() {
// Recently Used Fonts ignores case (`push_recent_font`): Arial applied here as `arial` and
// there as `ARIAL` is one entry, and doesn't push a distinct font out of the ten.
let loaded = json!({"recentFonts": ["A", "B", "C", "D", "E", "F", "G", "H", "I", "Arial"]});
let ours = json!({"recentFonts": ["arial", "A", "B", "C", "D", "E", "F", "G", "H", "I"]});
let disk = json!({"recentFonts": ["ARIAL", "A", "B", "C", "D", "E", "F", "G", "H", "I"]});
assert_eq!(merge(&loaded, ours, &disk), json!({"recentFonts": ["arial", "A", "B", "C", "D", "E", "F", "G", "H", "I"]}));
// Other lists compare their entries as saved.
let loaded = json!({"recent": ["a.docx"]});
assert_eq!(merge(&loaded, json!({"recent": ["A.docx", "a.docx"]}), &loaded), json!({"recent": ["A.docx", "a.docx"]}));
}
#[test]
fn merged_recent_lists_keep_their_limit() {
// Recently Used Fonts keeps ten.
let loaded = json!({"recentFonts": ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]});
let ours = json!({"recentFonts": ["X", "A", "B", "C", "D", "E", "F", "G", "H", "I"]});
let disk = json!({"recentFonts": ["Y", "A", "B", "C", "D", "E", "F", "G", "H", "I"]});
assert_eq!(merge(&loaded, ours, &disk), json!({"recentFonts": ["X", "Y", "A", "B", "C", "D", "E", "F", "G", "H"]}));
}
#[test]
fn a_bad_recent_entry_in_the_file_is_not_carried_forward() {
// A non-string entry makes the whole list read as empty (`options::lenient` falls back per
// setting). Merging it in would keep Recent empty in every later session; instead the
// list reads as this version reads it, and the next save heals it.
let loaded = prefs(json!({"recent": []}));
let ours = prefs(json!({"recent": ["x.docx"]}));
let disk = as_read(br#"{"recent": [{"path": "y.docx"}, "z.docx"]}"#).unwrap();
let merged = merge(&loaded, ours, &disk);
assert_eq!(merged["recent"], json!(["x.docx"]));
assert_eq!(loaded_recent(&merged), ["x.docx"]);
// Same for recent symbols.
let ours = prefs(json!({"recentSymbols": [{"ch": "§", "font": "Arial"}]}));
let disk = as_read(r#"{"recentSymbols": [{"ch": "¶", "font": "Arial"}, 7]}"#.as_bytes()).unwrap();
assert_eq!(reloaded(&merge(&prefs(json!({})), ours, &disk)).recent_symbols.len(), 1);
}
/// The recent documents the next process loads.
fn loaded_recent(merged: &Value) -> Vec<String> {
reloaded(merged).recent
}
#[test]
fn only_keys_this_version_writes_are_kept() {
// A legacy key read once to migrate, and junk, are not written back, even from the file.
let loaded = prefs(json!({"theme": "light"}));
let disk = as_read(br#"{"theme": "light", "dark": true, "interfaceSize": 120, "junk": 1}"#).unwrap();
let merged = merge(&loaded, loaded.clone(), &disk);
for gone in ["dark", "interfaceSize", "junk"] {
assert!(merged.get(gone).is_none(), "{gone}");
}
assert_eq!(merged["theme"], "light");
}
#[test]
fn a_file_another_process_damaged_gives_way_to_ours() {
let loaded = json!({"theme": "light", "recent": ["a.docx"]});
let ours = json!({"theme": "dark", "recent": ["a.docx"]});
// Not preferences at all: everything comes from this process.
assert_eq!(as_read(b"\"garbage\""), None);
assert_eq!(merge(&loaded, ours.clone(), &json!("garbage")), ours);
// A list replaced by something else keeps ours.
assert_eq!(merge(&loaded, json!({"recent": ["b.docx", "a.docx"]}), &json!({"recent": 3})), json!({"recent": ["b.docx", "a.docx"]}));
}
#[test]
fn autocorrect_entries_and_exceptions_from_both_processes_are_kept() {
let loaded = prefs(json!({"editing": {"autocorrect": {"entries": [["teh", "the"]], "exceptions": ["approx."]}}}));
// B adds an entry and an exception; A adds another entry, changes `teh`'s replacement and
// removes `approx.`. Each added entry follows the entry it was added after.
let b = prefs(json!({"editing": {"autocorrect": {"entries": [["teh", "the"], ["teh2", "the"]], "exceptions": ["approx.", "fig."]}}}));
let a = prefs(json!({"editing": {"autocorrect": {"entries": [["teh", "THE"], ["adn", "and"]], "exceptions": []}}}));
let ac = reloaded(&b_then_a(&loaded, b, a)).editing.autocorrect;
let entries: Vec<(&str, &str)> = ac.entries.iter().map(|(f, t)| (f.as_str(), t.as_str())).collect();
assert_eq!(entries, [("teh", "THE"), ("adn", "and"), ("teh2", "the")]);
assert_eq!(ac.exceptions, ["fig."]);
}
#[test]
fn keyboard_customisations_merge_key_by_key() {
let loaded = prefs(json!({"keyboard": {"assigned": {"Mod+Shift+K": "format.bold"}, "removed": []}}));
// B takes Ctrl+B off Bold and deletes its own Mod+Shift+K; A takes Ctrl+I off Italic and
// assigns Mod+Shift+J.
let b = prefs(json!({"keyboard": {"assigned": {}, "removed": ["Mod+B"]}}));
let a = prefs(json!({"keyboard": {"assigned": {"Mod+Shift+K": "format.bold", "Mod+Shift+J": "format.italic"}, "removed": ["Mod+I"]}}));
let keys = reloaded(&b_then_a(&loaded, b, a)).keyboard;
assert_eq!(keys.assigned.into_iter().collect::<Vec<_>>(), [("Mod+Shift+J".to_string(), "format.italic".to_string())]);
assert_eq!(keys.removed.into_iter().collect::<Vec<_>>(), ["Mod+B", "Mod+I"]);
}
#[test]
fn ribbon_changes_from_both_processes_are_kept() {
// Both start from the default ribbon. B hides Draw; A adds a custom tab after Home.
let loaded = prefs(json!({}));
let b = prefs(json!({"ribbon": {"tabs": hide(default_tabs(), "Draw")}}));
let mut a_tabs = default_tabs();
a_tabs.insert(1, json!({"name": "Mine", "custom": true}));
let a = prefs(json!({"ribbon": {"tabs": a_tabs}}));
let mut want = hide(default_tabs(), "Draw");
want.insert(1, json!({"name": "Mine", "custom": true}));
assert_eq!(serde_json::to_value(loaded_ribbon(&b_then_a(&loaded, b, a)).tabs).unwrap(), Value::Array(want));
}
#[test]
fn a_toolbar_reset_by_one_process_stays_reset() {
// B resets its custom Quick Access Toolbar to the default; A, which left it alone, adds a
// custom tab. The toolbar stays the default.
let loaded = prefs(json!({"ribbon": {"qat": ["file.save", "format.bold"]}}));
let b = prefs(json!({}));
let mut a_tabs = default_tabs();
a_tabs.push(json!({"name": "Mine", "custom": true}));
let a = prefs(json!({"ribbon": {"tabs": a_tabs, "qat": ["file.save", "format.bold"]}}));
let merged = b_then_a(&loaded, b, a);
assert!(merged["ribbon"].get("qat").is_none(), "{}", merged["ribbon"]);
let ribbon = loaded_ribbon(&merged);
assert_eq!(ribbon.qat, None);
assert!(ribbon.tabs.iter().any(|t| t.name == "Mine"));
// Two processes customizing the default toolbar: both commands, Save removed by A gone.
let loaded = prefs(json!({}));
let b = prefs(json!({"ribbon": {"qat": ["file.save", "edit.undo", "edit.redo", "format.bold"]}}));
let a = prefs(json!({"ribbon": {"qat": ["edit.undo", "edit.redo", "format.italic"]}}));
assert_eq!(loaded_ribbon(&b_then_a(&loaded, b, a)).qat.unwrap(), ["edit.undo", "edit.redo", "format.italic", "format.bold"]);
}
/// The default ribbon tabs, as saved once the ribbon is customized.
fn default_tabs() -> Vec<Value> {
serde_json::from_value(serde_json::to_value(wordcraft_engine::RibbonLayout::default().tabs()).unwrap()).unwrap()
}
/// `tabs` with the tab `name` hidden.
fn hide(mut tabs: Vec<Value>, name: &str) -> Vec<Value> {
for t in &mut tabs {
if t["name"] == name {
t["hidden"] = json!(true);
}
}
tabs
}
/// The ribbon the next process loads.
fn loaded_ribbon(merged: &Value) -> wordcraft_engine::RibbonLayout {
reloaded(merged).ribbon
}
#[test]
fn a_pane_order_changed_by_the_other_process_is_kept() {
// `paneOrder` is saved only when it isn't the default. B reorders; A leaves it alone and
// switches to dark.
let loaded = prefs(json!({}));
let order = json!(["styles", "navigation"]);
let b = prefs(json!({"paneOrder": order}));
let merged = b_then_a(&loaded, b, prefs(json!({"theme": "dark"})));
assert_eq!((&merged["paneOrder"], &merged["theme"]), (&order, &json!("dark")));
// B goes back to the default order; A, which loaded B's order and left it, doesn't bring
// it back.
let loaded = prefs(json!({"paneOrder": order}));
let merged = b_then_a(&loaded, prefs(json!({})), prefs(json!({"paneOrder": order, "theme": "dark"})));
assert!(merged.get("paneOrder").is_none(), "{merged}");
assert_eq!(merged["theme"], "dark");
}
#[test]
fn the_window_and_a_pane_place_are_one_setting_each() {
// A moved its window and B resized its own: the window is A's, not A's place with B's size.
let window = |x: f32, width: f32| json!({"window": {"position": [x, 10.0], "width": width, "height": 600.0, "maximized": false}});
let loaded = prefs(window(0.0, 800.0));
let merged = b_then_a(&loaded, prefs(window(0.0, 1000.0)), prefs(window(300.0, 800.0)));
assert_eq!(merged["window"], prefs(window(300.0, 800.0))["window"]);
}
#[test]
fn pens_labels_and_dictionary_words_from_both_processes_are_kept() {
let pen = |color: &str| json!({"kind": "pen", "color": color, "width": 1.0});
let loaded = prefs(json!({"inkPens": [pen("FF0000"), pen("FF0000")], "captionLabels": ["Plate"], "dictionary": ["foo", "bar"]}));
// B adds a third red pen, a label and a word; A adds a blue pen, removes `bar` and adds a
// label of its own. Identical pens stay apart, by their order.
let b = prefs(
json!({"inkPens": [pen("FF0000"), pen("FF0000"), pen("FF0000")], "captionLabels": ["Plate", "Chart"], "dictionary": ["foo", "bar", "baz"]}),
);
let a = prefs(json!({"inkPens": [pen("FF0000"), pen("FF0000"), pen("0000FF")], "captionLabels": ["Plate", "Map"], "dictionary": ["foo"]}));
let merged = b_then_a(&loaded, b, a);
let ui = reloaded(&merged);
let colors: Vec<String> = ui.ink_pens.iter().map(|p| serde_json::to_value(p).unwrap()["color"].as_str().unwrap().to_string()).collect();
assert_eq!(colors, ["FF0000", "FF0000", "0000FF", "FF0000"]);
assert_eq!(ui.caption_labels, ["Plate", "Map", "Chart"]);
assert_eq!(merged["dictionary"], json!(["foo", "baz"]));
}
}
+3 -2
View File
@@ -107,7 +107,8 @@ fn condition(s: &Session, t: &str, row: usize) -> (bool, Vec<String>) {
let op: String = rest.trim_start().chars().take_while(|c| matches!(c, '<'..='>')).collect();
let mut texts = field_words(rest).into_iter().filter(|(_, q)| *q).map(|(w, _)| w);
let cmp = texts.next().unwrap_or_default();
let v = value(s, row, &field);
let tested = t.split_once('{').and_then(|(_, r)| r.split('}').next()).unwrap_or("");
let v = wordcraft_layout::fields::apply_case_switch(tested, value(s, row, &field));
// Numbers compare as numbers (Word: "7" = "7.0"), everything else as text.
let ord = match (v.trim().parse::<f64>(), cmp.trim().parse::<f64>()) {
(Ok(a), Ok(b)) => a.partial_cmp(&b),
@@ -134,7 +135,7 @@ fn keyword(instr: &str) -> String {
fn act(s: &Session, instr: &str, row: usize) -> Option<Act> {
let t = instr.trim();
if let Some(n) = mergefield_name(t) {
return Some(Act::Text(value(s, row, &n)));
return Some(Act::Text(wordcraft_layout::fields::apply_case_switch(t, value(s, row, &n))));
}
Some(match keyword(t).as_str() {
"ADDRESSBLOCK" => Act::Text(address_block(s, row)),
+27
View File
@@ -147,6 +147,33 @@ fn merge_field_types_ignore_case() {
assert_eq!(s.doc.plain_text(StoryRef::Body), "Alpha\nBeta (b)");
}
/// A merge field's capitalization switch (`\* Upper`, `\* Lower`, `\* Caps`, `\* FirstCap`)
/// applies to the record's value in Preview Results and Finish & Merge.
#[test]
fn merge_fields_apply_their_capitalization_switch() {
let mut s = Session::new(Document::new());
s.run("mailings.recipients", &json!({"rows": [{"City": "new york", "Name": "ADA lovelace"}]})).unwrap();
s.run("insert.field", &json!({"instr": r"MERGEFIELD City \* Upper \* MERGEFORMAT", "result": ""})).unwrap();
s.run("text.insert", &json!({"text": " "})).unwrap();
s.run("insert.field", &json!({"instr": r#"MERGEFIELD "Name" \* Lower"#, "result": ""})).unwrap();
s.run("mailings.preview", &json!({"value": true})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "NEW YORK ada lovelace");
s.run("mailings.finish", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "NEW YORK ada lovelace");
}
/// An IF, NEXTIF or SKIPIF compares the tested merge field after its capitalization switch.
#[test]
fn rule_conditions_apply_the_tested_fields_capitalization_switch() {
let mut s = Session::new(Document::new());
s.run("mailings.recipients", &json!({"rows": [{"City": "new york"}, {"City": "paris"}]})).unwrap();
s.run("insert.field", &json!({"instr": r#"IF { MERGEFIELD City \* Upper } = "NEW YORK" "match" "other""#, "result": ""})).unwrap();
s.run("mailings.preview", &json!({"value": true})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "match");
s.run("mailings.next", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "other");
}
/// An IF is a merge rule only when the field it tests is a MERGEFIELD: the word in a quoted
/// value doesn't make `IF { PAGE } = "mergefield" …` one.
#[test]
+67 -5
View File
@@ -635,17 +635,27 @@ fn open_list(app: &mut WordApp, ui: &mut Ui) {
let shown = app.ui.recent.iter().take(app.ui.recent_shown()).cloned().collect::<Vec<_>>();
let file_name = |p: &str| std::path::Path::new(p).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or(p.to_string());
let names = shown.iter().map(|p| file_name(p)).collect::<Vec<_>>();
let (mut focused, mut hovered) = (None, None);
use egui::epaint::text::TextDirection;
for (p, name) in shown.iter().zip(&names) {
// #2716: each row carries its own Remove, as Word's context menu does. The × is a button
// of its own at the trailing end, so it never opens the document; clicking the rest of the
// row opens it as before.
let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width().min(700.0) - REMOVE_W, 40.0), Sense::click());
// The row shows a name and a path that may not fit: the path in full is its tooltip.
let resp = resp.on_hover_text(crate::i18n::isolate_path(p));
// Two documents with the same file name are told apart by their path, as on screen.
let spoken = if names.iter().filter(|n| *n == name).count() > 1 { format!("{name}, {p}") } else { name.clone() };
let twin = names.iter().filter(|n| *n == name).count() > 1;
let spoken = if twin { format!("{name}, {p}") } else { name.clone() };
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), &spoken));
// Only one row shows its path as a tooltip, so every row gives a screen reader the path
// itself, unless its label already says it.
if !twin {
ui.ctx().accesskit_node_builder(resp.id, |node| node.set_description(crate::i18n::isolate_path(p)));
}
if resp.has_focus() {
focused = Some((resp.clone(), p));
}
if resp.hovered() {
hovered = Some((resp.clone(), p));
ui.painter().rect_filled(r, 4.0, t.hover);
}
// Names and paths are set apart (a right-to-left line would scramble their marks and
@@ -659,8 +669,25 @@ fn open_list(app: &mut WordApp, ui: &mut Ui) {
t.accent,
);
let side = crate::rtl::lead_center(rtl);
ui.painter().text(pos2(crate::rtl::lead_x(rtl, r, 40.0), r.min.y + 13.0), side, crate::i18n::isolate(name), medium(13.0), t.text);
ui.painter().text(pos2(crate::rtl::lead_x(rtl, r, 40.0), r.min.y + 29.0), side, crate::i18n::isolate_path(p), regular(11.0), t.text_dim);
// A wide row on Home can push the row past the visible area at small window sizes, so the
// text stops at the visible edge and its ellipsis stays in view. Only its far end does: it
// starts at the row's start, in view or not.
let clip = ui.clip_rect();
let room = if rtl { r.max.x - r.min.x.max(clip.min.x) } else { r.max.x.min(clip.max.x) - r.min.x };
let text_w = (room - 48.0).max(0.0);
let fit = |text: String, direction: TextDirection, font: egui::FontId, color: egui::Color32, y: f32| {
let mut job = egui::text::LayoutJob::simple_singleline(text, font, color);
job.direction = direction;
job.wrap = egui::text::TextWrapping::truncate_at_width(text_w);
let g = ui.painter().layout_job(job);
let at = side.anchor_size(pos2(crate::rtl::lead_x(rtl, r, 40.0), y), g.size()).min;
ui.painter().galley(at, g, color);
};
// An isolate hides a right-to-left name's direction from its line, which would put the
// ellipsis beside the name's first letters.
let direction = if wordcraft_doc::bidi::first_strong_is_rtl(name) { TextDirection::RightToLeft } else { TextDirection::Auto };
fit(crate::i18n::isolate(name), direction, medium(13.0), t.text, r.min.y + 13.0);
fit(crate::i18n::isolate_path(p), TextDirection::Auto, regular(11.0), t.text_dim, r.min.y + 29.0);
let xr = Rect::from_min_max(pos2(r.max.x + 2.0, r.min.y + 4.0), pos2(r.max.x + REMOVE_W, r.max.y - 4.0));
// Right-to-left: the × sits on the left, past the row's trailing edge.
let xr = if rtl { xr.translate(vec2(-(r.width() + REMOVE_W + 2.0), 0.0)) } else { xr };
@@ -691,6 +718,41 @@ fn open_list(app: &mut WordApp, ui: &mut Ui) {
{
let _ = app.run("ui.recentClear", json!({}));
}
// A row shows a name and a path that may not fit: the path in full is its tooltip, for the
// hovered row or, after a key press, the focused one. egui shows one tooltip per layer, so
// only one of them is drawn, and the focus tooltip lets the pointer through to the rows below.
let keyboard = recent_keyboard_last(ui);
match (focused, hovered) {
(Some((resp, p)), hovered) if keyboard || hovered.is_none() => {
egui::Tooltip::for_widget(&resp).show(|ui| ui.label(crate::i18n::isolate_path(p)));
}
(_, Some((resp, p))) => {
resp.on_hover_text(crate::i18n::isolate_path(p));
}
_ => {}
}
}
/// Was a key pressed more recently than the pointer moved? Kept across passes, so a focused
/// Recent row keeps its tooltip while the pointer rests on another row.
fn recent_keyboard_last(ui: &Ui) -> bool {
let id = egui::Id::unique("backstage_recent_keyboard_last");
let now = ui.input(|i| {
if i.pointer.delta() != egui::Vec2::ZERO {
Some(false)
} else if i.events.iter().any(|e| matches!(e, egui::Event::Key { pressed: true, .. })) {
Some(true)
} else {
None
}
});
match now {
Some(keyboard) => {
ui.ctx().data_mut(|d| d.insert_temp(id, keyboard));
keyboard
}
None => ui.ctx().data(|d| d.get_temp(id)).unwrap_or(false),
}
}
/// Stable storage id for the Recent list's open error.
+283
View File
@@ -75,6 +75,289 @@ fn opening_a_missing_recent_file_keeps_file_open_with_the_error() {
assert!(app.ui.backstage, "File stays open");
}
/// Opens File > Home in a window of `size` with one long Recent entry; returns its name and path.
fn long_recent_harness(size: egui::Vec2) -> (egui_kittest::Harness<'static, WordApp>, String, String) {
let name = format!("{}.docx", "AVeryLongDocumentName".repeat(8));
let path = format!("C:/Users/Someone/{}/{name}", "LongFolderName".repeat(20));
(recent_harness(std::slice::from_ref(&path), size), name, path)
}
/// Opens File > Home in a window of `size` with `recent` as the Recent list.
fn recent_harness(recent: &[String], size: egui::Vec2) -> egui_kittest::Harness<'static, WordApp> {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Services::default());
a.ui.recent = recent.to_vec();
a.run("ui.backstage", json!({"value": true, "page": "home"})).unwrap();
let mut h = egui_kittest::Harness::builder().with_size(size).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
a,
);
h.run_steps(4);
h
}
/// Collects every text shape, including those nested in shape lists.
fn collect_text<'a>(s: &'a egui::Shape, out: &mut Vec<&'a egui::epaint::TextShape>) {
match s {
egui::Shape::Text(ts) => out.push(ts),
egui::Shape::Vec(v) => {
for child in v {
collect_text(child, out);
}
}
_ => {}
}
}
/// Returns the painted bounds and clip rect of the Recent entry's name and path texts, and
/// whether each ends with an ellipsis.
fn recent_text_bounds(h: &egui_kittest::Harness<'_, WordApp>) -> Vec<(String, egui::Rect, egui::Rect, bool)> {
let mut found = Vec::new();
for cs in &h.output().shapes {
let mut texts = Vec::new();
collect_text(&cs.shape, &mut texts);
for ts in texts {
let text = ts.galley.text();
if text.contains("C:/Users/Someone") || text.contains("AVeryLongDocumentName") {
let ellipsis = ts.galley.rows.first().and_then(|row| row.glyphs.last()).is_some_and(|g| g.chr == '\u{2026}');
found.push((text.to_owned(), ts.visual_bounding_rect(), cs.clip_rect, ellipsis));
}
}
}
found
}
/// #5212: long names and paths in File > Home > Recent shorten to fit their row and show on hover.
#[test]
fn recent_shortens_a_long_name_and_path_to_its_row() {
let (mut h, name, path) = long_recent_harness(egui::vec2(1440.0, 900.0));
let row = h.get_by_label(&name).rect();
let texts = recent_text_bounds(&h);
assert_eq!(texts.len(), 2, "both file name and path shapes must be found");
for (text, bounds, _, ellipsis) in &texts {
assert!(*ellipsis, "text '{text}' must end with an ellipsis");
assert!(bounds.max.x <= row.max.x + 0.5, "text '{text}' bounds.max.x ({}) > row.max.x + 0.5 ({})", bounds.max.x, row.max.x + 0.5);
}
h.event(egui::Event::PointerMoved(row.center()));
h.run_steps(4);
h.get_by_label(&path);
}
/// #5212: at the smallest window width the shortened texts end inside the visible area, so the
/// ellipsis is not cut off.
#[test]
fn recent_texts_end_inside_the_visible_area_at_the_smallest_window() {
let (h, _, _) = long_recent_harness(egui::vec2(760.0, 480.0));
let texts = recent_text_bounds(&h);
assert_eq!(texts.len(), 2, "both file name and path shapes must be found");
for (text, bounds, clip, ellipsis) in &texts {
assert!(*ellipsis, "text '{text}' must end with an ellipsis");
assert!(bounds.max.x <= clip.max.x + 0.5, "text '{text}' ends at {} past the visible edge {}", bounds.max.x, clip.max.x);
}
}
/// #5212: a Recent row focused with the keyboard shows its full path, as hovering does.
#[test]
fn recent_shows_the_full_path_when_a_row_has_keyboard_focus() {
let (mut h, name, path) = long_recent_harness(egui::vec2(1440.0, 900.0));
assert!(h.query_by_label(&path).is_none(), "the full path must not show before focus");
h.get_by_label(&name).focus();
h.run_steps(4);
h.get_by_label(&path);
}
/// #5212: the focus tooltip lets the pointer through, so the Recent row under it still gets
/// hovered, shows its own path and opens on click.
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn recent_focus_tooltip_does_not_block_the_row_below() {
let dir = std::env::temp_dir().join(format!("wordcraft-5212-{}", std::process::id()));
let paths = ["one.docx", "two.docx"].map(|n| dir.join(n).to_string_lossy().to_string());
let mut h = recent_harness(&paths, egui::vec2(1440.0, 900.0));
h.get_by_label("one.docx").focus();
h.run_steps(4);
let tip = h.get_by_label(&paths[0]).rect();
let below = tip.intersect(h.get_by_label("two.docx").rect());
assert!(below.is_positive(), "the focus tooltip must cover part of the next row: tip={tip:?}");
h.event(egui::Event::PointerMoved(below.center()));
h.run_steps(4);
h.get_by_label(&paths[1]);
for pressed in [true, false] {
h.event(egui::Event::PointerButton { pos: below.center(), button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE });
h.run_steps(1);
}
h.run_steps(3);
let error = h.ctx.data(|d| d.get_temp::<String>(super::open_error_id())).unwrap_or_default();
assert!(error.contains("two.docx"), "the click must reach two.docx and try to open it, got error '{error}'");
}
/// #5212: every Recent row gives a screen reader its full path, not only the hovered or
/// focused row that shows the path as a tooltip.
#[test]
fn recent_rows_describe_their_full_path_without_hover_or_focus() {
use egui_kittest::kittest::NodeT;
let dir = std::env::temp_dir().join("wordcraft-5212-describe");
let paths = ["one.docx", "two.docx"].map(|n| dir.join(n).to_string_lossy().to_string());
let mut h = recent_harness(&paths, egui::vec2(1440.0, 900.0));
let one = h.get_by_label("one.docx").rect();
h.event(egui::Event::PointerMoved(one.center()));
h.run_steps(4);
for (name, path) in ["one.docx", "two.docx"].iter().zip(&paths) {
let described = h.get_by_label(name).accesskit_node().description();
assert_eq!(described.as_deref(), Some(crate::i18n::isolate_path(path).as_str()), "{name} must describe its full path");
}
}
/// A right-to-left language for the Recent tests. `rtl` goes by its code, so it needs no Arabic font.
fn recent_right_to_left() -> crate::i18n::Lang {
crate::i18n::fixture_lang("ar", "\tHome\tHome\n")
}
/// The Recent list alone with one `path`, in `lang`, in a window 1000 wide. `start` points on the
/// side its rows start from and `end` points on the other side are out of view, as on a page
/// scrolled sideways or wider than the window.
fn recent_list_cut(path: &str, lang: crate::i18n::Lang, start: f32, end: f32) -> egui_kittest::Harness<'static, WordApp> {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Services::default());
a.ui.recent = vec![path.to_string()];
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1000.0, 500.0)).build_ui_state(
move |ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
crate::i18n::set_current(lang);
crate::rtl::sync(&ctx);
let mut clip = ui.clip_rect();
let (left, right) = if crate::rtl::on() { (end, start) } else { (start, end) };
clip.min.x += left;
clip.max.x -= right;
ui.set_clip_rect(clip);
super::open_list(app, ui);
},
a,
);
h.run_steps(4);
h
}
/// #5212: text runs from its row's start, so a row whose start is out of view has as much room
/// for its text as before. Only the far end stops at the visible edge.
#[test]
fn recent_text_keeps_its_room_when_its_row_starts_out_of_view() {
let name = format!("{}.docx", "AVeryLongDocumentName".repeat(8));
let path = format!("C:/Users/Someone/{name}");
for lang in [crate::i18n::Lang::EN, recent_right_to_left()] {
let widths = |cut| recent_text_bounds(&recent_list_cut(&path, lang, cut, 0.0)).iter().map(|t| t.1.width().round()).collect::<Vec<_>>();
let whole = widths(0.0);
assert_eq!(whole.len(), 2, "both lines must be painted: {whole:?}");
assert_eq!(widths(500.0), whole, "the cut must not take room from the text");
}
crate::i18n::set_current(crate::i18n::Lang::EN);
}
/// #5212: a row running past the visible area stops its text there, in either direction, with
/// its ellipsis in view.
#[test]
fn recent_text_stops_at_the_visible_edge_in_either_direction() {
let name = format!("{}.docx", "AVeryLongDocumentName".repeat(8));
let path = format!("C:/Users/Someone/{name}");
for lang in [crate::i18n::Lang::EN, recent_right_to_left()] {
let texts = recent_text_bounds(&recent_list_cut(&path, lang, 0.0, 400.0));
assert_eq!(texts.len(), 2, "both lines must be painted");
for (text, bounds, clip, ellipsis) in &texts {
assert!(
bounds.left() >= clip.left() - 0.5 && bounds.right() <= clip.right() + 0.5,
"{text} must end inside the visible area: {bounds:?} in {clip:?}"
);
assert!(ellipsis, "{text} must end in an ellipsis");
}
}
crate::i18n::set_current(crate::i18n::Lang::EN);
}
/// #5212: multibyte text is cut between its characters and stays in its row, starting at the
/// side the row starts from, in either direction.
#[test]
fn recent_shortens_multibyte_text_in_either_direction() {
let name = format!("AVeryLongDocumentName{}.docx", "\u{fc}\u{20ac}".repeat(120));
let path = format!("C:/Users/Someone/{name}");
for lang in [crate::i18n::Lang::EN, recent_right_to_left()] {
let h = recent_list_cut(&path, lang, 0.0, 0.0);
let row = h.get_by_label(&name).rect();
let texts = recent_text_bounds(&h);
assert_eq!(texts.len(), 2, "both lines must be painted");
for (text, bounds, _, ellipsis) in &texts {
let lead = if lang.rtl() { row.right() - bounds.right() } else { bounds.left() - row.left() };
assert!((lead - 40.0).abs() < 1.0, "{text} must start at its row's start: {bounds:?} in {row:?}");
assert!(bounds.left() >= row.left() - 0.5 && bounds.right() <= row.right() + 0.5, "{text} must stay in its row: {bounds:?} in {row:?}");
assert!(ellipsis, "{text} must end in an ellipsis");
}
}
crate::i18n::set_current(crate::i18n::Lang::EN);
}
/// #5212: a right-to-left name runs from the right, so it is cut on its left, and its ellipsis
/// belongs there, not beside the name's first letters.
#[test]
fn recent_puts_the_ellipsis_at_the_end_of_a_right_to_left_name() {
let name = format!("{}.docx", "\u{5d0}\u{5d1}\u{5d2} ".repeat(120));
let h = recent_list_cut(&format!("/docs/{name}"), recent_right_to_left(), 0.0, 0.0);
let output = h.output();
let mut texts = Vec::new();
for clipped in &output.shapes {
collect_text(&clipped.shape, &mut texts);
}
let shown = texts.iter().find(|t| t.galley.text().contains('\u{5d0}')).expect("the name");
let glyphs = &shown.galley.rows[0].glyphs;
let ellipsis = glyphs.iter().find(|g| g.chr == '\u{2026}').expect("an ellipsis");
let left = glyphs.iter().filter(|g| g.size().x > 0.0).map(|g| g.pos.x).fold(f32::MAX, f32::min);
assert!(ellipsis.pos.x <= left + 0.5, "the ellipsis must be the leftmost glyph: {} against {left}", ellipsis.pos.x);
crate::i18n::set_current(crate::i18n::Lang::EN);
}
/// #5212: two files with one name speak their path in the label, so it isn't read twice.
#[test]
fn recent_rows_with_one_name_speak_their_path_once() {
use egui_kittest::kittest::NodeT;
let dir = std::env::temp_dir().join("wordcraft-5212-twins");
let paths = ["one", "two"].map(|d| dir.join(d).join("same.docx").to_string_lossy().to_string());
let h = recent_harness(&paths, egui::vec2(1440.0, 900.0));
for path in &paths {
let label = format!("same.docx, {path}");
assert_eq!(h.get_by_label(&label).accesskit_node().description(), None, "{label} must not repeat its path");
}
}
/// #5212: with the pointer resting on one Recent row, Tab to the next row shows the focused
/// row's path, and moving the pointer again brings back the hovered row's path.
#[test]
fn recent_tab_shows_the_focused_path_while_the_pointer_rests_on_another_row() {
let dir = std::env::temp_dir().join("wordcraft-5212-tab");
let paths = ["one.docx", "two.docx"].map(|n| dir.join(n).to_string_lossy().to_string());
let mut h = recent_harness(&paths, egui::vec2(1440.0, 900.0));
let one = h.get_by_label("one.docx").rect();
h.event(egui::Event::PointerMoved(one.center()));
h.run_steps(4);
h.get_by_label(&paths[0]);
h.get_by_label("one.docx").focus();
h.run_steps(1);
// The first Tab goes to the row's own Remove ×, the second to the next row.
for _ in 0..2 {
h.key_press(egui::Key::Tab);
h.run_steps(4);
}
assert!(h.get_by_label("two.docx").is_focused(), "Tab must move focus to the next Recent row");
assert!(h.query_by_label(&paths[1]).is_some(), "the focused row's path must show while the pointer rests on another row");
h.event(egui::Event::PointerMoved(one.center() + egui::vec2(4.0, 0.0)));
h.run_steps(4);
assert!(h.query_by_label(&paths[0]).is_some(), "moving the pointer must bring back the hovered row's path");
}
/// #1873: the macOS back chevron sits beside the traffic lights windowed, at the plain
/// control inset in full screen.
#[test]
@@ -93,6 +93,45 @@ pub const NUMBER_FORMATS: &[(&str, &str)] = &[
("OrdText", "First, Second, Third, …"),
];
/// Capitalization formats for the `\*` switch of a text field: (switch value, label).
pub const TEXT_FORMATS: &[(&str, &str)] =
&[("", "(none)"), ("Upper", "Uppercase"), ("Lower", "Lowercase"), ("FirstCap", "First capital"), ("Caps", "Title case")];
/// Whether the dialog offers the capitalization Format list for `name` (the fields whose result
/// is text).
pub fn takes_text_format(name: &str) -> bool {
matches!(name, "AUTHOR" | "COMMENTS" | "FILENAME" | "KEYWORDS" | "LASTSAVEDBY" | "SUBJECT" | "TITLE" | "REF" | "STYLEREF" | "MERGEFIELD")
}
/// The capitalization switches in a field code, as their [`TEXT_FORMATS`] values, in the order
/// they appear (layout applies them in that order). Quoted text in the code is not a switch.
pub fn text_formats(code: &str) -> Vec<&'static str> {
let mut chars = code.chars().peekable();
let mut quoted = false;
let mut all = Vec::new();
while let Some(c) = chars.next() {
match c {
'\\' if quoted => {
chars.next();
}
'"' => quoted = !quoted,
'\\' if chars.peek() == Some(&'*') => {
chars.next();
while chars.next_if(|c| c.is_whitespace()).is_some() {}
let mut word = String::new();
while let Some(c) = chars.next_if(|c| !c.is_whitespace() && *c != '\\' && *c != '"') {
word.push(c);
}
if let Some((v, _)) = TEXT_FORMATS.iter().find(|(v, _)| !v.is_empty() && v.eq_ignore_ascii_case(&word)) {
all.push(*v);
}
}
_ => {}
}
}
all
}
pub fn field_kind(name: &str) -> FieldKind {
match name {
"DATE" | "TIME" | "CREATEDATE" | "SAVEDATE" | "PRINTDATE" => FieldKind::Date,
@@ -117,6 +156,12 @@ pub struct FieldForm {
pub date_format: String,
/// `\*` value for number fields (empty = none).
pub number_format: String,
/// `\*` capitalization value for text fields (empty = none).
pub text_format: String,
/// Every capitalization switch of the code typed in Field Codes, in order. The code keeps them
/// all while the Format list shows the last of them.
#[serde(skip)]
typed_text_formats: Vec<&'static str>,
/// Bookmark (REF, PAGEREF), sequence name (SEQ), merge field (MERGEFIELD) or style name
/// (STYLEREF).
pub target: String,
@@ -148,6 +193,8 @@ impl FieldForm {
name: "DATE".into(),
date_format: DATE_FORMATS.first().copied().unwrap_or("M/d/yyyy").to_string(),
number_format: String::new(),
text_format: String::new(),
typed_text_formats: Vec::new(),
target: String::new(),
preserve: true,
codes: false,
@@ -178,6 +225,8 @@ impl FieldForm {
pub fn select(&mut self, name: &str) {
self.name = name.to_string();
self.number_format.clear();
self.text_format.clear();
self.typed_text_formats.clear();
self.target = match field_kind(name) {
FieldKind::Bookmark => self.bookmarks.first().cloned().unwrap_or_default(),
FieldKind::Sequence => "Figure".into(),
@@ -230,6 +279,15 @@ impl FieldForm {
if matches!(field_kind(&self.name), FieldKind::Number | FieldKind::Sequence) && !self.number_format.is_empty() {
s.push_str(&format!(" \\* {}", self.number_format));
}
if takes_text_format(&self.name) && !self.text_format.is_empty() {
if self.typed_text_formats.last().is_some_and(|v| *v == self.text_format) {
for v in &self.typed_text_formats {
s.push_str(&format!(" \\* {v}"));
}
} else {
s.push_str(&format!(" \\* {}", self.text_format));
}
}
if self.preserve && field_kind(&self.name) != FieldKind::Toc {
s.push_str(" \\* MERGEFORMAT");
}
@@ -241,6 +299,27 @@ impl FieldForm {
if self.codes { self.code.trim().to_string() } else { self.instruction() }
}
/// The Format list: a choice replaces the capitalization switches kept from a typed code.
pub fn choose_text_format(&mut self, value: &str) {
self.text_format = value.to_string();
self.typed_text_formats.clear();
}
/// Field Codes / Hide Codes: showing the code starts it from the options; hiding it sets the
/// Format list to the code's last capitalization switch when the code is for the chosen field,
/// and keeps all of the code's capitalization switches until another Format is chosen.
pub fn toggle_codes(&mut self) {
if !self.codes {
self.code = self.instruction();
} else if takes_text_format(&self.name)
&& (wordcraft_layout::fields::field_name(&self.code) == self.name || self.name == "MERGEFIELD" && is_merge_field(&self.code))
{
self.typed_text_formats = text_formats(&self.code);
self.text_format = self.typed_text_formats.last().copied().unwrap_or_default().to_string();
}
self.codes = !self.codes;
}
/// The `insert.field` parameters (a merge field shows «name» until merged).
pub fn params(&self) -> Option<Value> {
let code = self.final_code();
@@ -248,13 +327,29 @@ impl FieldForm {
return None;
}
let name = wordcraft_layout::fields::field_name(&code);
Some(if name == "MERGEFIELD" { json!({"instr": code, "result": format!("«{}»", merge_field_name(&code))}) } else { json!({"instr": code}) })
Some(if name == "MERGEFIELD" || is_merge_field(&code) {
json!({"instr": code, "result": format!("«{}»", merge_field_name(&code))})
} else {
json!({"instr": code})
})
}
}
/// The byte where a field code's type ends: at a space or a quote, as mail merge reads it.
fn field_type_end(code: &str) -> usize {
code.find(|c: char| c.is_whitespace() || c == '"').unwrap_or(code.len())
}
/// Whether a typed code is a `MERGEFIELD`, including one with no space before its quoted name.
fn is_merge_field(code: &str) -> bool {
let code = code.trim_start();
code[..field_type_end(code)].eq_ignore_ascii_case("MERGEFIELD")
}
/// The merge field a `MERGEFIELD` code names (quoted names may hold spaces).
fn merge_field_name(code: &str) -> String {
let rest = code.trim_start().split_once(char::is_whitespace).map(|x| x.1.trim_start()).unwrap_or("");
let code = code.trim_start();
let rest = code[field_type_end(code)..].trim_start();
match rest.strip_prefix('"') {
Some(q) => q.split('"').next().unwrap_or("").to_string(),
None => rest.split_whitespace().next().unwrap_or("").to_string(),
@@ -318,10 +413,7 @@ pub(super) fn field_ui(app: &mut WordApp, ui: &mut Ui, f: &mut FieldForm) -> boo
ui.horizontal(|ui| {
let label = if f.codes { "Hide Codes" } else { "Field Codes" };
if ui.button(tl!(label)).clicked() {
if !f.codes {
f.code = f.instruction();
}
f.codes = !f.codes;
f.toggle_codes();
}
});
let params = f.params();
@@ -409,7 +501,21 @@ fn field_options(ui: &mut Ui, f: &mut FieldForm, t: &Tokens) {
}
}
FieldKind::Toc | FieldKind::Plain => {
ui.label(egui::RichText::new(tl!("This field has no options.")).small().color(t.text_dim));
if !takes_text_format(&f.name) {
ui.label(egui::RichText::new(tl!("This field has no options.")).small().color(t.text_dim));
}
}
}
if takes_text_format(&f.name) {
ui.add_space(4.0);
ui.label(tl!("Format:"));
let shown = TEXT_FORMATS.iter().find(|(v, _)| *v == f.text_format).map(|(_, l)| *l).unwrap_or("(none)");
craft_ui::ComboBox::from_id_salt("field_text").selected_text(tl!(shown)).width(200.0).show_ui(ui, |ui| {
for (v, l) in TEXT_FORMATS {
if ui.selectable_label(f.text_format == *v, tl!(l)).clicked() {
f.choose_text_format(v);
}
}
});
}
}
@@ -149,6 +149,141 @@ fn field_dialog_builds_the_instruction() {
assert!(f.params().is_none());
}
/// Text fields take a capitalization Format: each choice writes its `\*` switch before
/// `\* MERGEFORMAT`, after the field's own arguments and switches, and (none) writes none.
#[test]
fn field_dialog_text_format_writes_its_switch() {
let a = app();
let mut f = FieldForm::new(&a);
f.select("AUTHOR");
assert_eq!(f.text_format, "");
assert_eq!(f.instruction(), r"AUTHOR \* MERGEFORMAT");
for v in ["Upper", "Lower", "FirstCap", "Caps"] {
f.text_format = v.into();
assert_eq!(f.instruction(), format!(r"AUTHOR \* {v} \* MERGEFORMAT"));
}
let labels: Vec<&str> = field::TEXT_FORMATS.iter().map(|(_, l)| *l).collect();
assert_eq!(labels, ["(none)", "Uppercase", "Lowercase", "First capital", "Title case"]);
f.select("REF");
f.target = "intro".into();
f.text_format = "Upper".into();
assert_eq!(f.instruction(), r"REF intro \h \* Upper \* MERGEFORMAT");
f.select("STYLEREF");
f.style_switches = "l".into();
f.text_format = "Caps".into();
f.preserve = false;
assert_eq!(f.instruction(), r#"STYLEREF "Heading 1" \l \* Caps"#);
f.select("MERGEFIELD");
f.target = "City".into();
f.text_format = "Lower".into();
assert_eq!(f.params().unwrap(), json!({"instr": r"MERGEFIELD City \* Lower", "result": "«City»"}));
// Choosing another field starts from (none).
f.select("TITLE");
assert_eq!((f.text_format.as_str(), f.instruction().as_str()), ("", "TITLE"));
}
/// The list is offered for the text fields only; date, number, PAGEREF, SEQ and TOC keep their
/// own options and never take a capitalization switch from it.
#[test]
fn field_dialog_text_format_is_for_text_fields_only() {
for name in ["AUTHOR", "COMMENTS", "FILENAME", "KEYWORDS", "LASTSAVEDBY", "SUBJECT", "TITLE", "REF", "STYLEREF", "MERGEFIELD"] {
assert!(field::takes_text_format(name), "{name}");
}
let a = app();
let mut f = FieldForm::new(&a);
for name in ["DATE", "PAGE", "NUMPAGES", "PAGEREF", "SEQ", "TOC"] {
assert!(!field::takes_text_format(name), "{name}");
f.select(name);
let before = f.instruction();
f.text_format = "Upper".into();
assert_eq!(f.instruction(), before, "{name}");
}
}
/// Hide Codes sets the Format list from the typed code's last capitalization switch outside
/// quotes, and to (none) when the code has none.
#[test]
fn field_dialog_text_format_follows_the_typed_code() {
assert_eq!(field::text_formats(r#"AUTHOR "a \* Lower" \* upper \* Caps \* MERGEFORMAT"#), ["Upper", "Caps"]);
assert!(field::text_formats(r#"MERGEFIELD "x \* FirstCap""#).is_empty());
assert!(field::text_formats(r"PAGE \* roman").is_empty());
let a = app();
let mut f = FieldForm::new(&a);
f.select("SUBJECT");
f.toggle_codes();
assert_eq!(f.code, r"SUBJECT \* MERGEFORMAT");
f.code = r"SUBJECT \* FIRSTCAP \* MERGEFORMAT".into();
f.toggle_codes();
assert!(!f.codes);
assert_eq!(f.instruction(), r"SUBJECT \* FirstCap \* MERGEFORMAT");
f.toggle_codes();
f.code = "SUBJECT".into();
f.toggle_codes();
assert_eq!(f.text_format, "");
// A code for another field leaves the list as it was.
f.text_format = "Lower".into();
f.toggle_codes();
f.code = r"TITLE \* Upper".into();
f.toggle_codes();
assert_eq!(f.text_format, "Lower");
}
/// Hide Codes keeps every capitalization switch of the typed code, in order, so the inserted field
/// shows what the typed code shows; choosing another Format writes that one switch only.
#[test]
fn field_dialog_text_format_keeps_every_typed_case_switch() {
use wordcraft_layout::fields::apply_case_switch;
let a = app();
let mut f = FieldForm::new(&a);
f.select("SUBJECT");
f.toggle_codes();
f.code = r"SUBJECT \* Lower \* Caps".into();
let typed = apply_case_switch(&f.code, "WEEKLY REPORT".into());
assert_eq!(typed, "Weekly Report");
f.toggle_codes();
assert_eq!(f.text_format, "Caps");
assert_eq!(f.final_code(), r"SUBJECT \* Lower \* Caps \* MERGEFORMAT");
assert_eq!(apply_case_switch(&f.final_code(), "WEEKLY REPORT".into()), typed);
// Field Codes shows the same switches again.
f.toggle_codes();
assert_eq!(f.code, r"SUBJECT \* Lower \* Caps \* MERGEFORMAT");
f.toggle_codes();
// A Format the user chooses replaces the typed switches, and choosing Title case again
// does not bring them back.
f.choose_text_format("Upper");
assert_eq!(f.final_code(), r"SUBJECT \* Upper \* MERGEFORMAT");
f.choose_text_format("Caps");
assert_eq!(f.final_code(), r"SUBJECT \* Caps \* MERGEFORMAT");
f.choose_text_format("");
assert_eq!(f.final_code(), r"SUBJECT \* MERGEFORMAT");
// Choosing another field forgets them.
f.toggle_codes();
f.code = r"SUBJECT \* Lower \* Caps".into();
f.toggle_codes();
f.select("SUBJECT");
f.text_format = "Caps".into();
assert_eq!(f.final_code(), r"SUBJECT \* Caps \* MERGEFORMAT");
}
/// A typed `MERGEFIELD` code's type ends at a quote as well as a space, as mail merge reads it.
#[test]
fn field_dialog_reads_a_typed_merge_field_with_no_space_before_its_quote() {
let a = app();
let mut f = FieldForm::new(&a);
f.select("MERGEFIELD");
f.toggle_codes();
f.code = r#"MERGEFIELD"City" \* Lower"#.into();
assert_eq!(f.params().unwrap()["result"], "«City»");
f.toggle_codes();
assert_eq!(f.text_format, "Lower");
// Another field whose name only starts the same way is not this one.
f.choose_text_format("");
f.toggle_codes();
f.code = r"MERGEFIELDX \* Lower".into();
f.toggle_codes();
assert_eq!(f.text_format, "");
}
/// The Field dialog lists Word's document information fields, and the counts take a number
/// format.
#[test]
+42 -18
View File
@@ -154,18 +154,14 @@ pub(super) fn layout(app: &mut WordApp, ui: &mut Ui) {
t.row(|r| {
r.cell(|ui| ui.label(egui::RichText::new(tl!("Left:")).small()));
r.cell(|ui| {
if ui
.add_sized(FIELD, egui::DragValue::new(&mut l).speed(3.6 / k).range(-792.0 / k..=1584.0 / k).measure(u).max_decimals(2))
.changed()
{
let _ = app.run("para.indents", json!({"left": l * k}));
}
let resp =
ui.add_sized(FIELD, egui::DragValue::new(&mut l).speed(3.6 / k).range(-792.0 / k..=1584.0 / k).measure(u).max_decimals(2));
apply_box(app, ui, &resp, "para.indents", json!({"left": l * k}));
});
r.cell(|ui| spaced(ui, egui::RichText::new(tl!("Before:")).small()));
r.cell(|ui| {
if ui.add_sized(FIELD, egui::DragValue::new(&mut b).speed(1.0).range(0.0..=1584.0).suffix(format!(" {}", tl!("pt")))).changed() {
let _ = app.run("para.spacing", json!({"before": b}));
}
let resp = ui.add_sized(FIELD, egui::DragValue::new(&mut b).speed(1.0).range(0.0..=1584.0).suffix(format!(" {}", tl!("pt"))));
apply_box(app, ui, &resp, "para.spacing", json!({"before": b}));
});
});
let mut right = rp.indent_right / k;
@@ -173,18 +169,14 @@ pub(super) fn layout(app: &mut WordApp, ui: &mut Ui) {
t.row(|r| {
r.cell(|ui| ui.label(egui::RichText::new(tl!("Right:")).small()));
r.cell(|ui| {
if ui
.add_sized(FIELD, egui::DragValue::new(&mut right).speed(3.6 / k).range(-792.0 / k..=1584.0 / k).measure(u).max_decimals(2))
.changed()
{
let _ = app.run("para.indents", json!({"right": right * k}));
}
let resp = ui
.add_sized(FIELD, egui::DragValue::new(&mut right).speed(3.6 / k).range(-792.0 / k..=1584.0 / k).measure(u).max_decimals(2));
apply_box(app, ui, &resp, "para.indents", json!({"right": right * k}));
});
r.cell(|ui| spaced(ui, egui::RichText::new(tl!("After:")).small()));
r.cell(|ui| {
if ui.add_sized(FIELD, egui::DragValue::new(&mut a).speed(1.0).range(0.0..=1584.0).suffix(format!(" {}", tl!("pt")))).changed() {
let _ = app.run("para.spacing", json!({"after": a}));
}
let resp = ui.add_sized(FIELD, egui::DragValue::new(&mut a).speed(1.0).range(0.0..=1584.0).suffix(format!(" {}", tl!("pt"))));
apply_box(app, ui, &resp, "para.spacing", json!({"after": a}));
});
});
});
@@ -225,3 +217,35 @@ pub(super) fn layout(app: &mut WordApp, ui: &mut Ui) {
});
});
}
/// Apply the new value of a Layout › Paragraph box (Indent Left/Right, Spacing Before/After)
/// with `cmd` and `params`. A drag changes it frame by frame: every change after the drag's
/// first joins the undo step before it, so one Undo takes the whole drag back (#5171), not 0.1 cm
/// of it. The first change starts its own step, whatever frame it comes on. A change joins only
/// while the document stands where the drag's last change left it: the undo mark and the
/// revision both match. An edit that came in between (a control-channel command, say) keeps its
/// own step, and the drag goes on in a new one. The revision is what catches an Undo followed by
/// an edit: the undo mark comes back to the same number, but each of them bumps the revision.
fn apply_box(app: &mut WordApp, ui: &Ui, r: &egui::Response, cmd: &str, params: serde_json::Value) {
let applied = r.id.with("drag_applied");
if !r.dragged() {
ui.data_mut(|d| d.remove::<(u64, u64)>(applied));
}
if !r.changed() {
return;
}
let drag = r.dragged();
let before = app.session.undo_mark();
let join = drag && ui.data(|d| d.get_temp::<(u64, u64)>(applied)) == Some((before, app.session.rev()));
if join {
app.session.join_next_undo();
}
let _ = app.run(cmd, params);
let after = app.session.undo_mark();
// The newest step is the drag's when this change joined it or made it; a change that made
// none leaves the next one to start the drag's step.
if drag && (join || after != before) {
let rev = app.session.rev();
ui.data_mut(|d| d.insert_temp(applied, (after, rev)));
}
}
+96
View File
@@ -1092,3 +1092,99 @@ fn shape_and_chart_formats_leave_out_of_range_sizes_alone() {
assert_eq!(before.0, Some((20.0, 2500.0)));
assert_eq!(shown(a), before, "Chart Design shown, the chart untouched");
}
type LayoutH = egui_kittest::Harness<'static, WordApp>;
/// A window on the Layout tab with "Indented" typed, and the Left indent box drag, 60 points
/// right in ten moves: `between(k)` runs before the k-th move (an edit coming in mid-drag).
fn drag_left_indent(between: impl Fn(&mut LayoutH, usize)) -> (LayoutH, usize) {
use crate::table_resize::tests::{button, steps};
use egui_kittest::kittest::Queryable;
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), Default::default());
a.run("text.insert", json!({"text": "Indented"})).unwrap();
a.ui.tab = "Layout".into();
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
a,
);
steps(&mut h, 4);
let depth = h.state().session.undo_depth();
let label = h.get_by_label("Left:").rect();
// The box is the cell right of the label.
let from = egui::pos2(label.right() + 30.0, label.center().y);
h.event(egui::Event::PointerMoved(from));
h.step();
button(&h, from, true);
h.step();
for k in 1..=10 {
between(&mut h, k);
h.event(egui::Event::PointerMoved(from + egui::vec2(6.0 * k as f32, 0.0)));
h.step();
}
button(&h, from + egui::vec2(60.0, 0.0), false);
steps(&mut h, 3);
(h, depth)
}
fn left_indent(h: &LayoutH) -> f32 {
let s = &h.state().session;
s.doc.para_at(&s.sel.focus).map(|p| s.doc.styles.resolve_para(&p.props).indent_left).unwrap()
}
/// #5171: dragging Layout › Paragraph › Indent Left changes the indent as it goes, in one undo
/// step: one Undo takes the whole drag back, not 0.1 cm of it. The text typed before it keeps
/// its own step.
#[test]
fn dragging_a_layout_indent_box_is_one_undo_step() {
let (mut h, depth) = drag_left_indent(|_, _| {});
let dragged = left_indent(&h);
assert!(dragged > 20.0, "the drag indents the paragraph: {dragged}");
assert_eq!(h.state().session.undo_depth(), depth + 1, "one undo step for the drag");
h.state_mut().run("edit.undo", json!({})).unwrap();
assert_eq!(left_indent(&h), 0.0, "one Undo takes the whole drag back");
assert!(h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body).starts_with("Indented"), "the typing keeps its own step");
}
/// #5171 review: an edit that comes in during the drag (a control-channel command) keeps its own
/// undo step: the drag's changes after it make a step of their own instead of joining it.
#[test]
fn an_edit_in_the_middle_of_a_box_drag_keeps_its_own_undo_step() {
let (mut h, depth) = drag_left_indent(|h, k| {
if k == 5 {
h.state_mut().run("text.insert", json!({"text": " now"})).unwrap();
}
});
let text = |h: &LayoutH| h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body);
assert!(text(&h).contains(" now"), "{}", text(&h));
assert_eq!(h.state().session.undo_depth(), depth + 3, "the drag before, the edit, the drag after");
let full = left_indent(&h);
h.state_mut().run("edit.undo", json!({})).unwrap();
let mid = left_indent(&h);
assert!(mid > 0.0 && mid < full, "one Undo takes back the drag after the edit: {mid} of {full}");
assert!(text(&h).contains(" now"), "and leaves the edit");
h.state_mut().run("edit.undo", json!({})).unwrap();
assert!(!text(&h).contains(" now") && left_indent(&h) == mid, "the edit is its own step");
}
/// #5171 review: an Undo and then an edit in the middle of a drag bring the undo mark back to
/// where the drag left it. The drag's next change still doesn't join that edit: one Undo takes
/// back the rest of the drag and leaves the edit.
#[test]
fn an_undo_then_an_edit_in_the_middle_of_a_box_drag_keeps_the_edit_apart() {
let (mut h, _) = drag_left_indent(|h, k| {
if k == 5 {
h.state_mut().run("edit.undo", json!({})).unwrap();
h.state_mut().run("text.insert", json!({"text": " now"})).unwrap();
}
});
let text = |h: &LayoutH| h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body);
assert!(text(&h).contains(" now"), "{}", text(&h));
assert!(left_indent(&h) > 0.0, "the drag goes on after the edit");
h.state_mut().run("edit.undo", json!({})).unwrap();
assert_eq!(left_indent(&h), 0.0, "one Undo takes back the drag after the edit");
assert!(text(&h).contains(" now"), "and leaves the edit: {}", text(&h));
}
+3 -1
View File
File diff suppressed because one or more lines are too long