Compare commits

..
1 Commits
Author SHA1 Message Date
e2df2d64cd Tables in a header or footer: borders, handles, selection arrows, pen and eraser work while it is edited (#5558) (#5576)
Lands #5576 rebased onto main; only docs conflicts were resolved (both sides kept).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: D13GOOOO <106814760+D13GOOOO@users.noreply.github.com>
2026-11-17 04:04:48 +00:00
27 changed files with 649 additions and 1886 deletions
+2 -4
View File
@@ -451,10 +451,8 @@ 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).
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
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
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
+3 -5
View File
File diff suppressed because one or more lines are too long
+96 -3
View File
@@ -151,7 +151,7 @@ impl Launcher {
name: Some(name.clone()),
suggested: Some(name.clone()),
folder: dir.clone().map(std::path::PathBuf::from),
filters: wordcraft_ui_egui::save_filters(name),
filters: save_filters(name),
current: Some(0),
cancel,
timeout: None,
@@ -224,7 +224,7 @@ fn picker(dialog: rfd::AsyncFileDialog, req: &FileDialogRequest) -> Picking {
if let Some(dir) = dir.filter(|d| std::path::Path::new(d).is_dir()) {
dialog = dialog.set_directory(dir);
}
for (label, exts) in wordcraft_ui_egui::save_filters(&name) {
for (label, exts) in save_filters(&name) {
dialog = dialog.add_filter(label, &exts);
}
Box::pin(async move { dialog.save_file().await.into_iter().collect() })
@@ -324,9 +324,62 @@ fn on_path(program: &str) -> bool {
std::env::var_os("PATH").is_some_and(|paths| std::env::split_paths(&paths).any(|dir| dir.join(program).is_file()))
}
/// The file types Save As offers: every format the engine saves, with the suggested name's own
/// format first. rfd makes a filter's first extension the dialog's default, which the Windows,
/// macOS and Linux panels append to a file name the user typed without one; with no filter at
/// all the name came back bare and the save failed, since the format is chosen by extension
/// (#689).
fn save_exts(name: &str) -> Vec<String> {
let suggested = std::path::Path::new(name)
.extension()
.and_then(std::ffi::OsStr::to_str)
.map(str::to_ascii_lowercase)
// A .markdown file is under Markdown's one entry in the list.
.map(|e| if e == "markdown" { "md".to_string() } else { e })
.filter(|e| wordcraft_engine::io::SAVE_EXTS.contains(&e.as_str()))
.unwrap_or_else(|| "docx".to_string());
let mut exts: Vec<String> = Vec::with_capacity(wordcraft_engine::io::SAVE_EXTS.len());
exts.push(suggested.clone());
exts.extend(wordcraft_engine::io::SAVE_EXTS.iter().filter(|e| **e != suggested).map(|e| (*e).to_string()));
exts
}
/// The "Save as type" list (#1399): one named entry per format, the suggested one first (see
/// [`save_exts`] for why the order matters).
///
/// On Linux and the BSDs, [`crate::portal_save`] asks the portal directly over D-Bus and gives a
/// name the dialog left alone the chosen type's extension (#6180). When falling back to `rfd`, the
/// extension in the name wins, as `rfd` doesn't report which entry the user picked.
fn save_filters(name: &str) -> Vec<(String, Vec<String>)> {
save_exts(name).into_iter().map(|e| (format!("{} (*.{e})", format_name(&e)), vec![e])).collect()
}
/// A readable name for a save format's extension.
fn format_name(ext: &str) -> String {
match ext {
"docx" => "Word Document".into(),
"docm" => "Word Macro-Enabled Document".into(),
"dotx" => "Word Template".into(),
"dotm" => "Word Macro-Enabled Template".into(),
"pdf" => "PDF".into(),
"txt" => "Plain Text".into(),
"md" => "Markdown".into(),
"html" => "Web Page".into(),
"rtf" => "Rich Text Format".into(),
"odt" => "OpenDocument Text".into(),
"ott" => "OpenDocument Text Template".into(),
"fodt" => "Flat OpenDocument Text".into(),
"tex" => "LaTeX".into(),
"png" => "PNG Image".into(),
"json" => "JSON".into(),
"xml" => "XML".into(),
other => other.to_ascii_uppercase(),
}
}
#[cfg(test)]
mod tests {
use super::pick;
use super::{pick, save_exts, save_filters};
use std::time::Duration;
/// #2999: a dialog that "cancels" at once is a portal that failed: asked again without a
@@ -377,4 +430,44 @@ mod tests {
assert!(newer.token.is_cancelled(), "the newer request is still armed");
assert!(!abandoned.token.is_cancelled(), "only the armed request is cancelled");
}
/// #1399: the Save dialog's type list has one named entry per format, the suggested one first,
/// every savable extension exactly once.
#[test]
fn save_dialog_lists_one_named_type_per_format() {
let filters = save_filters("report.odt");
assert_eq!(filters.len(), wordcraft_engine::io::SAVE_EXTS.len());
assert_eq!(filters[0].1, vec!["odt".to_string()]);
assert!(filters[0].0.contains("OpenDocument"), "{}", filters[0].0);
let all: Vec<&String> = filters.iter().flat_map(|(_, e)| e).collect();
for e in wordcraft_engine::io::SAVE_EXTS {
assert_eq!(all.iter().filter(|x| x.as_str() == *e).count(), 1, "{e}");
}
assert!(filters.iter().all(|(l, e)| !l.trim().is_empty() && e.len() == 1));
let mut labels: Vec<&String> = filters.iter().map(|(l, _)| l).collect();
labels.sort();
labels.dedup();
assert_eq!(labels.len(), filters.len(), "labels are distinct");
// Unknown names fall back to Word's format first.
assert_eq!(save_filters("no extension")[0].1, vec!["docx".to_string()]);
}
/// #689: the Save dialog's default extension is the suggested name's own format, so a file
/// name the user types without one is saved in the document's format instead of coming back
/// bare and failing.
#[test]
fn save_dialog_defaults_to_the_suggested_format() {
assert_eq!(save_exts("novel.docx")[0], "docx");
assert_eq!(save_exts("report.odt")[0], "odt");
assert_eq!(save_exts("annual report.pdf")[0], "pdf");
assert_eq!(save_exts("notes.md")[0], "md");
assert_eq!(save_exts("notes.markdown")[0], "md");
// A suggested name always has an extension; anything unreadable falls back to Word's.
assert_eq!(save_exts("no extension")[0], "docx");
assert_eq!(save_exts("mystery.rtf2")[0], "docx");
// Every savable format is still offered, once.
let exts = save_exts("novel.docx");
assert!(wordcraft_engine::io::SAVE_EXTS.iter().all(|e| exts.iter().any(|x| x == e)));
assert_eq!(exts.len(), wordcraft_engine::io::SAVE_EXTS.len());
}
}
+16 -164
View File
@@ -23,7 +23,6 @@ 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")]
@@ -223,44 +222,31 @@ 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;
}
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)
if let Some(p) = prefs_path()
&& 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
@@ -346,8 +332,6 @@ 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}");
@@ -364,79 +348,11 @@ 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 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)?;
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()))?;
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<()> {
@@ -710,6 +626,7 @@ 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
@@ -922,72 +839,7 @@ mod launch_arg_tests {
#[cfg(test)]
mod prefs_tests {
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);
}
use super::write_prefs;
#[test]
fn failed_preferences_write_keeps_the_old_file_and_reports_the_error() {
-550
View File
@@ -1,550 +0,0 @@
//! 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"]));
}
}
+2 -3
View File
@@ -107,8 +107,7 @@ 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 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));
let v = 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),
@@ -135,7 +134,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(wordcraft_layout::fields::apply_case_switch(t, value(s, row, &n))));
return Some(Act::Text(value(s, row, &n)));
}
Some(match keyword(t).as_str() {
"ADDRESSBLOCK" => Act::Text(address_block(s, row)),
-27
View File
@@ -147,33 +147,6 @@ 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]
+54 -26
View File
@@ -9,9 +9,10 @@ use wordcraft_doc::props::{HeightRule, VMerge};
use wordcraft_doc::table::{MAX_COLS, MAX_ROWS};
use wordcraft_doc::{Block, Cell, Path, Pos, StoryRef, Table, para_block};
use wordcraft_geom::Rect;
use wordcraft_layout::{DocLayout, Placed};
use wordcraft_layout::DocLayout;
use super::sel_result;
use super::table_resize::Reach;
use crate::{CmdError, CmdResult, CommandSpec, Selection, Session, p};
/// A drag shorter than this (points) both ways isn't a rectangle.
@@ -29,7 +30,7 @@ pub fn specs() -> Vec<CommandSpec> {
r#"{"page": n, "x0": pt, "y0": pt, "x1": pt, "y1": pt, "story"?: StoryRef} (a pen stroke in page points, 0-based page: a rectangle at least 12 pt each way outside any table inserts a one-cell table of that size at the paragraph under its start; a straight vertical or horizontal line inside a table splits the cells it crosses there. In the app the button turns the pen on.)"#,
),
CommandSpec::new("table.eraser", "Eraser", "Table Layout › Draw", eraser).params(
r#"{"page": n, "x": pt, "y": pt} (removes the border between two cells within 4 pt of the point: cells that make one rectangle merge, including cells merged down the same rows; otherwise the border is hidden along the whole edge. In the app the button turns the eraser on.)"#,
r#"{"page": n, "x": pt, "y": pt, "story"?: StoryRef} (removes the border between two cells within 4 pt of the point, of a table in `story` (default: the caret's; a header's or footer's while one is edited): cells that make one rectangle merge, including cells merged down the same rows; otherwise the border is hidden along the whole edge. In the app the button turns the eraser on.)"#,
),
]
}
@@ -55,16 +56,12 @@ struct CellBox {
cell: usize,
}
fn cell_boxes(l: &DocLayout, page: usize) -> Vec<CellBox> {
let Some(pg) = l.pages.get(page) else { return Vec::new() };
pg.items
.iter()
.filter_map(|it| match it {
Placed::Cell { rect, table, row, cell, story, .. } => {
Some(CellBox { rect: *rect, table: table.clone(), story: *story, row: *row, cell: *cell })
}
_ => None,
})
/// The table cells on a page the pen and eraser reach ([`Reach`]: a header's and footer's while
/// one of them is edited, #5558).
fn cell_boxes(l: &DocLayout, page: usize, reach: Reach) -> Vec<CellBox> {
super::table_resize::cell_boxes_in(l, page, reach)
.into_iter()
.map(|b| CellBox { rect: b.rect, table: b.table, story: b.story, row: b.row, cell: b.cell })
.collect()
}
@@ -79,13 +76,22 @@ fn table_at(boxes: &[CellBox], x: f32, y: f32) -> Option<(StoryRef, Path)> {
/// Classify a pen stroke: a straight line inside a table, a rectangle outside one, else `None`.
pub fn stroke(l: &DocLayout, page: usize, x0: f32, y0: f32, x1: f32, y1: f32) -> Option<Stroke> {
stroke_in(l, page, Reach::Body, x0, y0, x1, y1)
}
/// [`stroke`] while `editing` is edited: across a header's or footer's tables then (#5558).
pub fn stroke_in(l: &DocLayout, page: usize, tables: Reach, x0: f32, y0: f32, x1: f32, y1: f32) -> Option<Stroke> {
stroke_among(&cell_boxes(l, page, tables), x0, y0, x1, y1)
}
/// [`stroke`] across the tables of `boxes`.
fn stroke_among(boxes: &[CellBox], x0: f32, y0: f32, x1: f32, y1: f32) -> Option<Stroke> {
if ![x0, y0, x1, y1].iter().all(|v| v.is_finite()) {
return None;
}
let (dx, dy) = ((x1 - x0).abs(), (y1 - y0).abs());
let boxes = cell_boxes(l, page);
let (mx, my) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0);
if table_at(&boxes, x0, y0).is_some() || table_at(&boxes, mx, my).is_some() {
if table_at(boxes, x0, y0).is_some() || table_at(boxes, mx, my).is_some() {
if dy >= dx && dy >= MIN_LINE && dx <= MIN_RECT.max(dy * 0.2) {
return Some(Stroke::Vertical { x: mx, y0: y0.min(y1), y1: y0.max(y1) });
}
@@ -97,6 +103,19 @@ pub fn stroke(l: &DocLayout, page: usize, x0: f32, y0: f32, x1: f32, y1: f32) ->
(dx >= MIN_RECT && dy >= MIN_RECT).then(|| Stroke::Rect(Rect::new(x0.min(x1), y0.min(y1), dx, dy)))
}
/// The cells a pen or eraser command reaches: those of the tables its `story` (default: the
/// caret's) reaches ([`Reach`]), and of those only `story`'s own when the command names one: a
/// caller that names a story means its tables, not a table of another drawn there.
fn command_boxes(s: &Session, l: &DocLayout, v: &Value, page: usize) -> Vec<CellBox> {
let story = super::story_param(s, v);
let boxes = cell_boxes(l, page, Reach::of(l, &s.doc, story, page));
let named = v.get("story").and_then(|x| serde_json::from_value::<StoryRef>(x.clone()).ok());
match named {
Some(named) => boxes.into_iter().filter(|b| b.story == named).collect(),
None => boxes,
}
}
fn page_param(v: &Value) -> Result<usize, CmdError> {
p::u64(v, "page").map(|n| usize::try_from(n).unwrap_or(usize::MAX)).ok_or_else(|| CmdError::Params("`page` (number) is required".into()))
}
@@ -108,10 +127,11 @@ fn draw(s: &mut Session, v: &Value) -> CmdResult {
if l.pages.get(page).is_none() {
return Err(CmdError::Params(format!("no page {page}")));
}
match stroke(&l, page, x0, y0, x1, y1) {
let boxes = command_boxes(s, &l, v, page);
match stroke_among(&boxes, x0, y0, x1, y1) {
Some(Stroke::Rect(r)) => draw_table(s, v, &l, page, (x0, y0), r),
Some(Stroke::Vertical { x, y0, y1 }) => split_columns(s, &l, page, x, (y0, y1)),
Some(Stroke::Horizontal { y, x0, x1 }) => split_rows(s, &l, page, y, (x0, x1)),
Some(Stroke::Vertical { x, y0, y1 }) => split_columns(s, &boxes, x, (y0, y1)),
Some(Stroke::Horizontal { y, x0, x1 }) => split_rows(s, &boxes, y, (x0, x1)),
None => Err(CmdError::Failed(
"draw a rectangle (at least 12 pt each way) outside a table, or a straight horizontal or vertical line across table cells".into(),
)),
@@ -276,13 +296,12 @@ fn hide_edge(t: &mut Table, vertical: bool, line: usize, (lo, hi): (usize, usize
}
/// A vertical line at page `x`: split each crossed cell into two columns there.
fn split_columns(s: &mut Session, l: &DocLayout, page: usize, x: f32, (ya, yb): (f32, f32)) -> CmdResult {
let boxes = cell_boxes(l, page);
fn split_columns(s: &mut Session, boxes: &[CellBox], x: f32, (ya, yb): (f32, f32)) -> CmdResult {
let hit = |r: &Rect| {
let overlap = yb.min(r.bottom()) - ya.max(r.y);
x > r.x + SNAP && x < r.right() - SNAP && overlap >= r.h * 0.5
};
let Some((story, tp, cells)) = crossed(&boxes, (x, (ya + yb) / 2.0), hit) else {
let Some((story, tp, cells)) = crossed(boxes, (x, (ya + yb) / 2.0), hit) else {
return Err(CmdError::Failed("the line doesn't cross a table cell".into()));
};
let Some(&(r0, c0, rect0)) = cells.first() else { return Err(CmdError::Failed("the line doesn't cross a table cell".into())) };
@@ -372,13 +391,12 @@ fn split_columns(s: &mut Session, l: &DocLayout, page: usize, x: f32, (ya, yb):
/// A horizontal line at page `y`: split the row it crosses there. Crossed cells become two;
/// the row's other cells span both rows (a vertical merge).
fn split_rows(s: &mut Session, l: &DocLayout, page: usize, y: f32, (xa, xb): (f32, f32)) -> CmdResult {
let boxes = cell_boxes(l, page);
fn split_rows(s: &mut Session, boxes: &[CellBox], y: f32, (xa, xb): (f32, f32)) -> CmdResult {
let hit = |r: &Rect| {
let overlap = xb.min(r.right()) - xa.max(r.x);
y > r.y + SNAP && y < r.bottom() - SNAP && overlap >= r.w * 0.5
};
let Some((story, tp, cells)) = crossed(&boxes, ((xa + xb) / 2.0, y), hit) else {
let Some((story, tp, cells)) = crossed(boxes, ((xa + xb) / 2.0, y), hit) else {
return Err(CmdError::Failed("the line doesn't cross a table cell".into()));
};
let Some(&(r, c0, _)) = cells.first() else { return Err(CmdError::Failed("the line doesn't cross a table cell".into())) };
@@ -459,17 +477,26 @@ pub struct EraseTarget {
/// The border between two cells nearest page point (`x`, `y`), within [`ERASER_REACH`].
pub fn erase_target(l: &DocLayout, page: usize, x: f32, y: f32) -> Option<EraseTarget> {
erase_target_in(l, page, Reach::Body, x, y)
}
/// [`erase_target`] while `editing` is edited: a header's or footer's tables then (#5558).
pub fn erase_target_in(l: &DocLayout, page: usize, tables: Reach, x: f32, y: f32) -> Option<EraseTarget> {
erase_among(&cell_boxes(l, page, tables), x, y)
}
/// [`erase_target`] among the tables of `boxes`.
fn erase_among(boxes: &[CellBox], x: f32, y: f32) -> Option<EraseTarget> {
if !x.is_finite() || !y.is_finite() {
return None;
}
let boxes = cell_boxes(l, page);
let mut best: Option<(f32, usize, EraseTarget)> = None;
let mut offer = |d: f32, depth: usize, e: EraseTarget| {
if d <= ERASER_REACH && best.as_ref().is_none_or(|(bd, bdepth, _)| d < *bd - 0.01 || (d <= *bd + 0.01 && depth > *bdepth)) {
best = Some((d, depth, e));
}
};
for a in &boxes {
for a in boxes {
let (ar, ab) = (a.rect.right(), a.rect.bottom());
let same = |b: &&CellBox| b.story == a.story && b.table == a.table;
// The border on a's right, shared with the next cell of its row.
@@ -518,7 +545,7 @@ fn eraser(s: &mut Session, v: &Value) -> CmdResult {
if l.pages.get(page).is_none() {
return Err(CmdError::Params(format!("no page {page}")));
}
let e = erase_target(&l, page, x, y).ok_or_else(|| CmdError::Failed("there's no border between two cells there".into()))?;
let e = erase_among(&command_boxes(s, &l, v, page), x, y).ok_or_else(|| CmdError::Failed("there's no border between two cells there".into()))?;
let (story, tp) = (e.story, e.table.clone());
let t = s.doc.table_mut(story, &tp)?;
let ((r, c), (r2, c2)) = (e.first, e.second);
@@ -581,6 +608,7 @@ fn eraser(s: &mut Session, v: &Value) -> CmdResult {
mod tests {
use super::*;
use serde_json::json;
use wordcraft_layout::Placed;
/// Each row's cell spans.
fn shape(t: &Table) -> Value {
+21 -16
View File
@@ -16,7 +16,7 @@ use wordcraft_doc::{Document, Path, Pos, StoryRef, Table};
use wordcraft_geom::{Point, Rect};
use wordcraft_layout::{DocLayout, Placed};
use super::table_resize::{self, CellBox, Edge, REACH, ResizeTarget};
use super::table_resize::{self, CellBox, Edge, REACH, Reach, ResizeTarget};
use super::{sel_result, table};
use crate::{CellRange, CmdError, CmdResult, CommandSpec, Selection, Session, p};
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
r#"{"page": n, "x": pt, "y": pt, "toX": pt, "toY": pt, "reach"?: pt} (a drag from the move handle past a table's top-left corner: the table floats where it's dropped, the text wrapping around it; tables in the main text only)"#,
),
CommandSpec::new("table.fitColumn", "AutoFit Column by Double-Clicking", "Table Layout › Cell Size", fit_column).params(
r#"{"page": n, "x": pt, "y": pt, "reach"?: pt} (a double-click on a column border: the column left of it fits its contents and the columns right of it keep their widths, moving with the border, so the table narrows or widens (up to the right margin), as in Word)"#,
r#"{"page": n, "x": pt, "y": pt, "reach"?: pt} (a double-click on a column border of a table in the caret's story: the column left of it fits its contents and the columns right of it keep their widths, moving with the border, so the table narrows or widens (up to the right margin), as in Word)"#,
),
]
}
@@ -205,11 +205,12 @@ pub fn target_at(l: &DocLayout, doc: &Document, story: StoryRef, page: usize, x:
return None;
}
let reach = clean_reach(reach);
if table_resize::resize_target(l, doc, page, x, y, reach).is_some() {
let tables = Reach::of(l, doc, story, page);
if table_resize::resize_target_in(l, doc, page, x, y, reach, tables).is_some() {
return None;
}
let boxes = table_resize::cell_boxes(l, page);
table_resize::tables_on(l, doc, page)
let boxes = table_resize::cell_boxes_in(l, page, tables);
table_resize::tables_on_in(l, doc, page, tables)
.into_iter()
.filter(|g| g.story == story)
.filter_map(|geom| {
@@ -226,7 +227,7 @@ pub fn handle_table(l: &DocLayout, doc: &Document, story: StoryRef, page: usize,
return None;
}
let pad = clean_reach(reach) / 2.0;
table_resize::tables_on(l, doc, page)
table_resize::tables_on_in(l, doc, page, Reach::of(l, doc, story, page))
.into_iter()
.filter(|g| {
let h = handle(g);
@@ -242,7 +243,7 @@ pub fn caret_handles(l: &DocLayout, doc: &Document, story: StoryRef, table: &Pat
let rows = doc.table(story, table).map_or(0, |t| t.rows.len());
let has_row = |p: usize, r: usize| {
l.pages.get(p).is_some_and(|pg| {
pg.items.iter().any(|it| matches!(it, Placed::Cell { table: t, story: st, row, .. } if *st == story && t == table && *row == r))
pg.story_items(story).any(|it| matches!(it, Placed::Cell { table: t, story: st, row, .. } if *st == story && t == table && *row == r))
})
};
// A repeated header row, or a row running on to the next page, is drawn on more than one
@@ -253,7 +254,9 @@ pub fn caret_handles(l: &DocLayout, doc: &Document, story: StoryRef, table: &Pat
return (None, None);
}
// The table's geometry on this page that the pointer handles are drawn and grabbed from.
let Some(g) = table_resize::tables_on(l, doc, page).into_iter().find(|g| g.story == story && g.table == *table) else {
let Some(g) =
table_resize::tables_on_in(l, doc, page, Reach::of(l, doc, story, page)).into_iter().find(|g| g.story == story && g.table == *table)
else {
return (None, None);
};
(first.then(|| handle(&g)), last.then(|| g.handle()))
@@ -298,7 +301,7 @@ pub fn cell_rects(l: &DocLayout, doc: &Document, range: &CellRange) -> Vec<(usiz
let picked: std::collections::BTreeSet<(usize, usize)> = range.cells(t).into_iter().collect();
let mut out = Vec::new();
for (pi, pg) in l.pages.iter().enumerate() {
for it in &pg.items {
for it in pg.story_items(range.story) {
// A vertically merged cell's box spans its rows (#640); its continuation rows'
// `covered` boxes would shade it twice.
if let Placed::Cell { rect, table, row, cell, story, covered: false, .. } = it
@@ -326,7 +329,7 @@ pub fn selection_rects(l: &DocLayout, doc: &Document, a: &Pos, b: &Pos, page_hin
let mut seen = BTreeMap::new();
let mut cells = Vec::new();
for (pi, pg) in l.pages.iter().enumerate() {
for it in &pg.items {
for it in pg.story_items(a.story) {
// A vertically merged cell's box spans its rows (#640), as in `cell_rects`.
if let Placed::Cell { rect, table, row, story, covered: false, .. } = it
&& *story == a.story
@@ -510,7 +513,7 @@ fn insert_at(s: &mut Session, v: &Value) -> CmdResult {
/// Where table `table` of `story` is first drawn: its page and top-left corner.
pub fn corner(l: &DocLayout, story: StoryRef, table: &Path) -> Option<(usize, f32, f32)> {
l.pages.iter().enumerate().find_map(|(pi, pg)| {
let cells = pg.items.iter().filter_map(|it| match it {
let cells = pg.story_items(story).filter_map(|it| match it {
Placed::Cell { rect, table: t, story: st, .. } if *st == story && t == table => Some(*rect),
_ => None,
});
@@ -565,10 +568,12 @@ fn move_drag(s: &mut Session, v: &Value) -> CmdResult {
fn fit_column(s: &mut Session, v: &Value) -> CmdResult {
let (page, x, y, reach) = point(v)?;
let l = s.layout();
let Some((target, line)) = table_resize::resize_target(&l, &s.doc, page, x, y, reach).and_then(|t| match t.edge {
Edge::Column(line) => Some((t, line)),
_ => None,
}) else {
let Some((target, line)) = table_resize::resize_target_in(&l, &s.doc, page, x, y, reach, Reach::of(&l, &s.doc, s.sel.focus.story, page))
.and_then(|t| match t.edge {
Edge::Column(line) => Some((t, line)),
_ => None,
})
else {
return Err(CmdError::Failed("there's no column border there".into()));
};
let t = s.doc.table(target.story, &target.table).ok_or_else(|| CmdError::Failed("there's no table there".into()))?;
@@ -595,7 +600,7 @@ fn room_right(l: &DocLayout, doc: &Document, page: usize, target: &ResizeTarget)
let margin = l.pages.get(page).map_or(target.right(), |pg| pg.body.right());
let Some((outer, row, cell)) = target.table.cell() else { return margin };
let Some(t) = doc.table(target.story, &outer) else { return margin };
let boxes = table_resize::cell_boxes(l, page);
let boxes = table_resize::story_cell_boxes(l, page, target.story);
let Some(b) = boxes.iter().find(|b| b.story == target.story && b.table == outer && b.row == row && b.cell == cell) else {
return margin;
};
+77 -19
View File
@@ -9,7 +9,7 @@
use serde_json::Value;
use wordcraft_doc::props::{Align, HeightRule, VMerge};
use wordcraft_doc::table::MAX_COLS;
use wordcraft_doc::{Cell, Document, Path, StoryRef, Table};
use wordcraft_doc::{Cell, Document, PartKind, Path, StoryRef, Table};
use wordcraft_geom::Rect;
use wordcraft_layout::{DocLayout, Placed};
@@ -29,7 +29,7 @@ const MAX_LEN: f32 = 1584.0;
pub fn specs() -> Vec<CommandSpec> {
vec![CommandSpec::new("table.resizeDrag", "Resize Table by Dragging", "Table Layout › Cell Size", resize_drag).params(
r#"{"page": n, "x": pt, "y": pt, "toX": pt, "toY": pt, "shift"?: bool, "ctrl"?: bool, "reach"?: pt} (a mouse drag in page points, 0-based page, starting on a table border or the resize handle: a column border moves (the column to its right gives or takes the difference, so the table keeps its width; with ctrl the columns right of it share it in proportion; with shift, or on the table's right edge, only the column left of it changes); the table's left edge moves a left-aligned table's indent, the first column making up the difference (a centred or right-aligned table keeps its alignment: only the first column changes); with cells of the table selected, a border of theirs moves only in their rows; a row's bottom border sets that row's height; the handle just outside the bottom-right corner scales every column and the rows on that page. `reach` (default 3) is how near the start has to be.)"#,
r#"{"page": n, "x": pt, "y": pt, "toX": pt, "toY": pt, "shift"?: bool, "ctrl"?: bool, "reach"?: pt} (a mouse drag in page points, 0-based page, starting on a border or the resize handle of a table in the caret's story (a header's or footer's tables while one is edited): a column border moves (the column to its right gives or takes the difference, so the table keeps its width; with ctrl the columns right of it share it in proportion; with shift, or on the table's right edge, only the column left of it changes); the table's left edge moves a left-aligned table's indent, the first column making up the difference (a centred or right-aligned table keeps its alignment: only the first column changes); with cells of the table selected, a border of theirs moves only in their rows; a row's bottom border sets that row's height; the handle just outside the bottom-right corner scales every column and the rows on that page. `reach` (default 3) is how near the start has to be.)"#,
)]
}
@@ -327,17 +327,53 @@ pub(crate) struct CellBox {
pub(crate) cell: usize,
}
pub(crate) fn cell_boxes(l: &DocLayout, page: usize) -> Vec<CellBox> {
/// Which of a page's tables the pointer reaches (#5558): the body's, with its text boxes' and
/// notes', while those are edited; a header's and footer's, with the text boxes in them, while
/// a header or footer (or a text box in one) is, and then not the dimmed body's.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Reach {
Body,
HeaderFooter,
}
impl Reach {
/// The reach while `editing` is edited, around `page` (where a text box's host is looked for).
pub fn of(l: &DocLayout, doc: &Document, editing: StoryRef, page: usize) -> Reach {
let kind = |s: StoryRef| match s {
StoryRef::Part(id) => doc.parts.get(&id).map(|p| p.kind),
StoryRef::Body => None,
};
let host = match editing {
StoryRef::Part(id) if kind(editing) == Some(PartKind::TextBox) => l.text_box(id, page).map_or(editing, |o| o.story),
_ => editing,
};
if matches!(kind(host), Some(PartKind::Header | PartKind::Footer)) { Reach::HeaderFooter } else { Reach::Body }
}
}
/// The table cells on a page that the pointer reaches ([`Reach`]).
pub(crate) fn cell_boxes_in(l: &DocLayout, page: usize, reach: Reach) -> Vec<CellBox> {
let Some(pg) = l.pages.get(page) else { return Vec::new() };
pg.items
.iter()
.filter_map(|it| match it {
Placed::Cell { rect, table, row, cell, story, .. } => {
Some(CellBox { rect: *rect, table: table.clone(), story: *story, row: *row, cell: *cell })
}
_ => None,
})
.collect()
let items: Box<dyn Iterator<Item = &Placed>> = match reach {
Reach::Body => Box::new(pg.items.iter()),
Reach::HeaderFooter => Box::new(pg.header.iter().chain(pg.footer.iter())),
};
items.filter_map(cell_box).collect()
}
/// The cells of `story`'s tables on a page, wherever that story is drawn.
pub(crate) fn story_cell_boxes(l: &DocLayout, page: usize, story: StoryRef) -> Vec<CellBox> {
let Some(pg) = l.pages.get(page) else { return Vec::new() };
pg.story_items(story).filter_map(cell_box).filter(|b| b.story == story).collect()
}
fn cell_box(it: &Placed) -> Option<CellBox> {
match it {
Placed::Cell { rect, table, row, cell, story, .. } => {
Some(CellBox { rect: *rect, table: table.clone(), story: *story, row: *row, cell: *cell })
}
_ => None,
}
}
/// The drawn geometry of one table on a page, from its cells' boxes.
@@ -403,8 +439,14 @@ fn geometry(t: &Table, boxes: &[&CellBox]) -> Option<(Vec<f32>, Vec<DrawnRow>)>
}
/// Every table drawn on a page, with its geometry there (`edge` is a placeholder).
#[cfg(test)]
pub(crate) fn tables_on(l: &DocLayout, doc: &Document, page: usize) -> Vec<ResizeTarget> {
let boxes = cell_boxes(l, page);
tables_on_in(l, doc, page, Reach::Body)
}
/// Every table drawn on a page that the pointer reaches ([`Reach`]).
pub(crate) fn tables_on_in(l: &DocLayout, doc: &Document, page: usize, reach: Reach) -> Vec<ResizeTarget> {
let boxes = cell_boxes_in(l, page, reach);
let mut tables: Vec<(StoryRef, &Path)> = Vec::new();
for b in &boxes {
if !tables.iter().any(|(s, p)| *s == b.story && **p == b.table) {
@@ -431,11 +473,17 @@ fn on_handle(t: &ResizeTarget, x: f32, y: f32, reach: f32) -> bool {
/// The innermost table under page point (`x`, `y`) whose resize handle is on this page, or whose
/// handle is under the point: the one whose handle the app shows.
pub fn table_under(l: &DocLayout, doc: &Document, page: usize, x: f32, y: f32, reach: f32) -> Option<ResizeTarget> {
table_under_in(l, doc, page, x, y, reach, Reach::Body)
}
/// [`table_under`] among the tables `tables` reaches: a header's or footer's while one is edited
/// (#5558).
pub fn table_under_in(l: &DocLayout, doc: &Document, page: usize, x: f32, y: f32, reach: f32, tables: Reach) -> Option<ResizeTarget> {
if !x.is_finite() || !y.is_finite() {
return None;
}
let reach = if reach.is_finite() { reach.clamp(0.5, 24.0) } else { REACH };
tables_on(l, doc, page)
tables_on_in(l, doc, page, tables)
.into_iter()
.filter(|t| t.ends_here && ((x >= t.left() && x <= t.right() && y >= t.top() && y <= t.bottom()) || on_handle(t, x, y, reach)))
.max_by_key(|t| t.table.0.len())
@@ -444,12 +492,18 @@ pub fn table_under(l: &DocLayout, doc: &Document, page: usize, x: f32, y: f32, r
/// The table border or resize handle within `reach` points of page point (`x`, `y`): the
/// nearest, and of nested tables the innermost.
pub fn resize_target(l: &DocLayout, doc: &Document, page: usize, x: f32, y: f32, reach: f32) -> Option<ResizeTarget> {
resize_target_in(l, doc, page, x, y, reach, Reach::Body)
}
/// [`resize_target`] among the tables `tables` reaches: a header's or footer's while one is
/// edited (#5558).
pub fn resize_target_in(l: &DocLayout, doc: &Document, page: usize, x: f32, y: f32, reach: f32, tables: Reach) -> Option<ResizeTarget> {
if !x.is_finite() || !y.is_finite() {
return None;
}
let reach = if reach.is_finite() { reach.clamp(0.5, 24.0) } else { REACH };
let mut best: Option<(f32, usize, ResizeTarget)> = None;
for mut target in tables_on(l, doc, page) {
for mut target in tables_on_in(l, doc, page, tables) {
let depth = target.table.0.len();
let mut offer = |d: f32, edge: Edge, target: &mut ResizeTarget| {
if d <= reach && best.as_ref().is_none_or(|(bd, bdepth, _)| d < *bd - 0.01 || (d <= *bd + 0.01 && depth > *bdepth)) {
@@ -500,8 +554,8 @@ fn resize_drag(s: &mut Session, v: &Value) -> CmdResult {
if l.pages.get(page).is_none() {
return Err(CmdError::Params(format!("no page {page}")));
}
let mut target =
resize_target(&l, &s.doc, page, x, y, reach).ok_or_else(|| CmdError::Failed("there's no table border or resize handle there".into()))?;
let mut target = resize_target_in(&l, &s.doc, page, x, y, reach, Reach::of(&l, &s.doc, s.sel.focus.story, page))
.ok_or_else(|| CmdError::Failed("there's no table border or resize handle there".into()))?;
target.limit_to_selection(s, y);
let plan = target.plan(to_x - x, to_y - y, share);
if plan.widths.is_none() && plan.heights.is_empty() && plan.cells.is_empty() {
@@ -647,7 +701,11 @@ fn regrid(t: &mut Table, cols: &[f32], rows: &[(usize, Vec<f32>)]) -> Result<(),
/// The page x of the target table's left edge on `page`, as drawn.
fn drawn_left(l: &DocLayout, page: usize, target: &ResizeTarget) -> Option<f32> {
cell_boxes(l, page).iter().filter(|b| b.story == target.story && b.table == target.table).map(|b| b.rect.x).min_by(f32::total_cmp)
story_cell_boxes(l, page, target.story)
.iter()
.filter(|b| b.story == target.story && b.table == target.table)
.map(|b| b.rect.x)
.min_by(f32::total_cmp)
}
/// Make `widths` (one per grid column) the table's column widths, as drawn: no preferred table
@@ -663,7 +721,7 @@ pub(crate) fn set_widths(t: &mut Table, widths: Vec<f32>) {
/// The drawn height of each of the target table's rows on `page`.
fn drawn_heights(l: &DocLayout, doc: &Document, page: usize, target: &ResizeTarget) -> Vec<(usize, f32)> {
tables_on(l, doc, page)
tables_on_in(l, doc, page, Reach::of(l, doc, target.story, page))
.into_iter()
.find(|t| t.story == target.story && t.table == target.table)
.map(|t| t.rows.iter().map(|r| (r.row, r.bottom - r.top)).collect())
-42
View File
@@ -47,48 +47,6 @@ fn ext_of(name: &str) -> String {
file.rsplit_once('.').map(|(_, ext)| ext.to_ascii_lowercase()).unwrap_or_default()
}
/// The format a file extension (any case) saves as, named by its [`SAVE_EXTS`] entry, other
/// spellings included (`htm` is `html`, `text` is `txt`); `None` for one WordCraft doesn't save.
pub fn save_format(ext: &str) -> Option<&'static str> {
let ext = ext.to_ascii_lowercase();
let ext = match ext.as_str() {
"text" => "txt",
"markdown" => "md",
"htm" | "xhtml" => "html",
"latex" | "ltx" => "tex",
other => other,
};
SAVE_EXTS.iter().copied().find(|e| *e == ext)
}
/// The path Save As writes for a `path` the user named, in format `ext` (`docx`, `pdf`…): a file
/// name with no extension, or with one WordCraft doesn't save (`Report v1.2`, `notes.final`),
/// gets `.ext` added, as Word adds `.docx` (#5368). The format is chosen by the extension, so
/// such a name used to fail to save at all.
pub fn with_save_ext(path: &str, ext: &str) -> String {
if save_format(&ext_of(path)).is_some() {
return path.to_string();
}
add_ext(path, ext)
}
/// The path an export in format `ext` writes for a `path` the user named: one whose extension
/// isn't that format's (`Report`, `Report.docx` for a PDF) gets `.ext` added, so an export
/// writes the format it was asked for (#5368).
pub fn with_export_ext(path: &str, ext: &str) -> String {
let current = ext_of(path);
if current == ext.to_ascii_lowercase() || save_format(&current).is_some_and(|f| save_format(ext) == Some(f)) {
return path.to_string();
}
add_ext(path, ext)
}
/// `path` with `.ext` after it. Windows drops a file name's trailing dots, so `Report.` is
/// `Report.docx`, not `Report..docx`.
fn add_ext(path: &str, ext: &str) -> String {
format!("{}.{ext}", path.trim_end_matches('.'))
}
/// Is `ext` one of Word's package formats (.docx/.docm/.dotx/.dotm), which save without loss?
pub fn is_word_package(ext: &str) -> bool {
wordcraft_docx::Flavor::from_ext(ext).is_some()
+1 -3
View File
@@ -248,9 +248,7 @@ impl Session {
/// `file.printPdf`: write the print job's PDF to `path` (no dialogs).
pub(crate) fn print_pdf_to_file(s: &mut Session, v: &Value) -> Result<Value, CmdError> {
let path = p::req_str(v, "path")?;
// `.pdf` after a name without it, by the rule exports follow (the built-in browser asks
// about replacing this same name).
let path = crate::io::with_export_ext(path, "pdf");
let path = if path.to_ascii_lowercase().ends_with(".pdf") { path.to_string() } else { format!("{path}.pdf") };
let (bytes, plan) = s.print_pdf(v)?;
// Through `io`, so an agent confined to an automation write root (#769) can't print elsewhere.
#[cfg(not(target_arch = "wasm32"))]
+174 -31
View File
@@ -13404,38 +13404,181 @@ fn page_down_extends_a_selection_that_ends_in_collapsed_outline_text() {
assert!(s.layout().caret(&s.sel.focus).is_some(), "to a place the outline shows");
}
/// #5368: Save As adds the format's extension to a name with none, or with one WordCraft
/// doesn't save, as Word adds .docx; a name with a format's extension (any case) is kept.
/// #5558: a table in the header is edited like one in the body (typing in its cells, Table
/// Layout's rows and columns), and a table copied from the body is pasted into the header as a
/// table, not as its text.
#[test]
fn save_as_adds_the_extension_to_a_name_without_a_format() {
use crate::io::with_save_ext;
assert_eq!(with_save_ext(r"C:\Docs\Report", "docx"), r"C:\Docs\Report.docx");
assert_eq!(with_save_ext(r"C:\My.Docs\Report", "docx"), r"C:\My.Docs\Report.docx", "a Windows folder's dot doesn't count either");
assert_eq!(with_save_ext("/home/me/Report v1.2", "docx"), "/home/me/Report v1.2.docx");
assert_eq!(with_save_ext("/home/me/notes.final", "dotx"), "/home/me/notes.final.dotx");
assert_eq!(with_save_ext("/home/me/Report.", "docx"), "/home/me/Report.docx");
assert_eq!(with_save_ext("/home/my.docs/Report", "pdf"), "/home/my.docs/Report.pdf", "a dot in a folder name doesn't count");
for kept in ["/a/Report.docx", "/a/Report.PDF", "/a/page.htm", "/a/notes.text", "/a/Report.odt"] {
assert_eq!(with_save_ext(kept, "docx"), kept);
}
// Every name it gives saves.
let doc = wordcraft_doc::Document::from_text("x");
for name in ["Report", "Report v1.2", "Report."] {
let path = with_save_ext(name, "docx");
assert!(crate::io::save_bytes(&path, &doc).is_ok(), "{path}");
}
assert!(crate::io::save_bytes("Report v1.2", &doc).is_err(), "it used to fail");
// Other spellings name the same format.
assert_eq!(crate::io::save_format("HTM"), Some("html"));
assert_eq!(crate::io::save_format("text"), Some("txt"));
assert_eq!(crate::io::save_format("2"), None);
// An export writes its own format, whatever format's extension the name has.
use crate::io::with_export_ext;
assert_eq!(with_export_ext("/a/Handout", "pdf"), "/a/Handout.pdf");
assert_eq!(with_export_ext("/a/Handout.docx", "pdf"), "/a/Handout.docx.pdf");
assert_eq!(with_export_ext("/a/Handout.PDF", "pdf"), "/a/Handout.PDF");
assert_eq!(with_export_ext("/a/page.htm", "html"), "/a/page.htm");
assert_eq!(with_export_ext("/a/shot.pdf", "png"), "/a/shot.pdf.png");
fn a_header_table_is_edited_and_a_copied_table_pastes_into_the_header() {
let mut s = s();
run(&mut s, "text.insert", json!({"text": "Body"}));
let id = run(&mut s, "insert.header", json!({"text": "Head"}))["story"].as_u64().unwrap() as u32;
let hf = StoryRef::Part(id);
run(&mut s, "insert.table", json!({"rows": 2, "cols": 2}));
assert_eq!(s.sel.focus.story, hf, "the caret stays in the header");
assert!(s.sel.focus.path.cell().is_some(), "the caret is in the new table: {:?}", s.sel.focus);
run(&mut s, "text.insert", json!({"text": "Cell"}));
run(&mut s, "table.insertRowBelow", json!({}));
run(&mut s, "table.insertColumnRight", json!({}));
let tables = |s: &Session| {
s.doc
.story(hf)
.map(|b| b.iter().filter_map(|b| b.as_table().map(|t| (t.rows.len(), t.rows[0].cells.len()))).collect::<Vec<_>>())
.unwrap_or_default()
};
assert_eq!(tables(&s), vec![(3, 3)]);
assert!(s.doc.plain_text(hf).contains("Cell"));
// Its column border drags, as a body table's does: the border is in the page's header.
let first = s.layout().pages[0].header.iter().find_map(|it| match it {
wordcraft_layout::Placed::Cell { rect, row: 0, cell: 0, story, .. } if *story == hf => Some(*rect),
_ => None,
});
let first = first.expect("the header's table is laid out");
let grid = |s: &Session| s.doc.story(hf).and_then(|b| b.iter().find_map(|b| b.as_table().map(|t| t.grid.clone()))).unwrap_or_default();
let before = grid(&s);
let (x, y) = (first.right(), first.y + first.h / 2.0);
run(&mut s, "table.resizeDrag", json!({"page": 0, "x": x, "y": y, "toX": x + 30.0, "toY": y}));
let after = grid(&s);
assert!(after[0] > before[0] + 20.0, "the header table's first column widened: {before:?} → {after:?}");
// While the body is edited, the dimmed header's table doesn't take the pointer.
assert!(crate::cmd::table_resize::resize_target_in(&s.layout(), &s.doc, 0, x, y, 4.0, crate::cmd::table_resize::Reach::Body).is_none());
// The Draw Table pen splits the header table's cell it crosses, as in the body.
let first = s.layout().pages[0].header.iter().find_map(|it| match it {
wordcraft_layout::Placed::Cell { rect, row: 0, cell: 0, story, .. } if *story == hf => Some(*rect),
_ => None,
});
let first = first.expect("the header's table is still laid out");
let mid = first.x + first.w / 2.0;
run(&mut s, "table.draw", json!({"page": 0, "x0": mid, "y0": first.y + 1.0, "x1": mid, "y1": first.bottom() - 1.0}));
assert_eq!(grid(&s).len(), 4, "the pen split a column of the header's table");
// A table copied from the body pastes into the header as a table.
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 4)}));
run(&mut s, "insert.table", json!({"rows": 1, "cols": 2}));
run(&mut s, "text.insert", json!({"text": "Copied"}));
run(&mut s, "table.selectTable", json!({}));
run(&mut s, "edit.copy", json!({}));
// The end of the header's "Head" paragraph, after its table.
let head = s.doc.story(hf).map_or(0, |b| b.len().saturating_sub(1));
let at = Pos { story: hf, path: wordcraft_doc::Path::top(head), off: 4 };
assert_eq!(s.doc.para_at(&at).map(|p| p.text.as_str()), Some("Head"));
run(&mut s, "caret.set", json!({"pos": at}));
run(&mut s, "edit.paste", json!({}));
let mut found = tables(&s);
found.sort();
assert_eq!(found, vec![(1, 2), (3, 4)], "{:?}", s.doc.story(hf));
assert!(s.doc.plain_text(hf).contains("Copied"));
}
/// #5558 review: a body text box and a footnote share the body's editing. With the caret in
/// one, the body's table still takes the pointer (border drags, the pen) and the dimmed header's
/// doesn't; with the caret in the footer, the footer's table takes it and the body's doesn't.
#[test]
fn body_tables_keep_the_pointer_from_a_text_box_or_a_note_and_a_footer_table_takes_it() {
use crate::cmd::table_resize::{Reach, resize_target_in};
use wordcraft_layout::Placed;
let mut s = s();
run(&mut s, "text.insert", json!({"text": "Body"}));
run(&mut s, "insert.table", json!({"rows": 2, "cols": 2}));
let head = run(&mut s, "insert.header", json!({"text": "Head"}))["story"].as_u64().unwrap() as u32;
run(&mut s, "insert.table", json!({"rows": 1, "cols": 2}));
let foot = run(&mut s, "insert.footer", json!({"text": "Foot"}))["story"].as_u64().unwrap() as u32;
run(&mut s, "insert.table", json!({"rows": 1, "cols": 2}));
run(&mut s, "insert.closeHeader", json!({}));
// The middle of the right border of `story`'s first cell on page 1.
let border = |s: &mut Session, story: StoryRef| {
let l = s.layout();
let pg = &l.pages[0];
let r = pg.items.iter().chain(&pg.header).chain(&pg.footer).find_map(|it| match it {
Placed::Cell { rect, row: 0, cell: 0, story: st, .. } if *st == story => Some(*rect),
_ => None,
});
let r = r.unwrap_or_else(|| panic!("{story:?}'s table is laid out"));
(r.right(), r.y + r.h / 2.0, r)
};
let grabbed = |s: &mut Session, (x, y): (f32, f32)| {
let l = s.layout();
let reach = Reach::of(&l, &s.doc, s.sel.focus.story, 0);
resize_target_in(&l, &s.doc, 0, x, y, 4.0, reach).map(|t| t.story)
};
let grid = |s: &Session, story: StoryRef| {
s.doc.story(story).and_then(|b| b.iter().find_map(|b| b.as_table().map(|t| t.grid.clone()))).unwrap_or_default()
};
// A text box in the body (the borders are measured once it is in).
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 0)}));
let boxed = run(&mut s, "insert.textBox", json!({"text": "in box"}))["story"].as_u64().unwrap() as u32;
assert_eq!(s.sel.focus.story, StoryRef::Part(boxed));
let (bx, by, _) = border(&mut s, StoryRef::Body);
let (hx, hy, _) = border(&mut s, StoryRef::Part(head));
assert_eq!(grabbed(&mut s, (bx, by)), Some(StoryRef::Body), "the body's table, from a body text box");
assert_eq!(grabbed(&mut s, (hx, hy)), None, "not the dimmed header's");
let before = grid(&s, StoryRef::Body);
run(&mut s, "table.resizeDrag", json!({"page": 0, "x": bx, "y": by, "toX": bx + 20.0, "toY": by}));
assert!(grid(&s, StoryRef::Body)[0] > before[0] + 10.0, "the drag widened the body's column");
// A footnote.
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 4)}));
run(&mut s, "references.footnote", json!({"text": "note"}));
let note = s.doc.parts.iter().find(|(_, p)| p.kind == wordcraft_doc::PartKind::Footnote).map(|(id, _)| *id).expect("the footnote's story");
run(&mut s, "caret.set", json!({"pos": Pos { story: StoryRef::Part(note), path: wordcraft_doc::Path::top(0), off: 0 }}));
let (bx, by, _) = border(&mut s, StoryRef::Body);
assert_eq!(grabbed(&mut s, (bx, by)), Some(StoryRef::Body), "the body's table, from a footnote");
assert_eq!(grabbed(&mut s, (hx, hy)), None);
// The pen still splits the body's cell it crosses instead of drawing a new table.
let (_, _, cell) = border(&mut s, StoryRef::Body);
let mid = cell.x + cell.w / 2.0;
let cols = grid(&s, StoryRef::Body).len();
run(&mut s, "table.draw", json!({"page": 0, "x0": mid, "y0": cell.y + 1.0, "x1": mid, "y1": cell.bottom() - 1.0}));
assert_eq!(grid(&s, StoryRef::Body).len(), cols + 1, "the pen split a body column");
// The footer, while it is edited: its table, not the body's.
run(&mut s, "caret.set", json!({"pos": Pos { story: StoryRef::Part(foot), path: wordcraft_doc::Path::top(0), off: 0 }}));
let (bx, by, _) = border(&mut s, StoryRef::Body);
let (fx, fy, _) = border(&mut s, StoryRef::Part(foot));
assert_eq!(grabbed(&mut s, (fx, fy)), Some(StoryRef::Part(foot)), "the footer's table, while the footer is edited");
assert_eq!(grabbed(&mut s, (bx, by)), None, "not the dimmed body's");
let before = grid(&s, StoryRef::Part(foot));
run(&mut s, "table.resizeDrag", json!({"page": 0, "x": fx, "y": fy, "toX": fx + 20.0, "toY": fy}));
assert!(grid(&s, StoryRef::Part(foot))[0] > before[0] + 10.0, "the drag widened the footer's column");
}
/// #5558 review: `table.eraser` and `table.draw` with a `story` work on that story's tables only:
/// a border of another story's table drawn there (a table in a body text box, among the body's
/// items) is left alone; the named story's own is erased.
#[test]
fn the_eraser_and_the_pen_keep_to_the_story_they_are_given() {
use wordcraft_layout::Placed;
let mut s = s();
run(&mut s, "text.insert", json!({"text": "Body"}));
run(&mut s, "insert.table", json!({"rows": 1, "cols": 2}));
// A text box in the body with a table of its own.
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 0)}));
let boxed = StoryRef::Part(run(&mut s, "insert.textBox", json!({"text": "Box"}))["story"].as_u64().unwrap() as u32);
run(&mut s, "insert.table", json!({"rows": 1, "cols": 2}));
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 0)}));
let first = |s: &mut Session, story: StoryRef| {
let l = s.layout();
let r = l.pages[0].items.iter().find_map(|it| match it {
Placed::Cell { rect, row: 0, cell: 0, story: st, .. } if *st == story => Some(*rect),
_ => None,
});
r.unwrap_or_else(|| panic!("{story:?}'s table is laid out"))
};
let cols = |s: &Session, story: StoryRef| {
s.doc.story(story).and_then(|b| b.iter().find_map(|b| b.as_table().map(|t| t.rows[0].cells.len()))).unwrap_or(0)
};
let body = serde_json::to_value(StoryRef::Body).unwrap();
// Named the body: the text box's table, though drawn among the body's items, is left alone.
let b = first(&mut s, boxed);
let erase = json!({"page": 0, "x": b.right(), "y": b.y + b.h / 2.0, "story": body.clone()});
assert!(s.run("table.eraser", &erase).is_err(), "no body border there");
let mid = b.x + b.w / 2.0;
let line = json!({"page": 0, "x0": mid, "y0": b.y + 1.0, "x1": mid, "y1": b.bottom() - 1.0, "story": body.clone()});
assert!(s.run("table.draw", &line).is_err(), "no body table to split there");
assert_eq!(cols(&s, boxed), 2, "the text box's table is as it was");
// The body's own border is erased.
let t = first(&mut s, StoryRef::Body);
run(&mut s, "table.eraser", json!({"page": 0, "x": t.right(), "y": t.y + t.h / 2.0, "story": body}));
assert_eq!(cols(&s, StoryRef::Body), 1, "the body table's two cells merged");
}
/// A picture an OpenDocument file gives no size is shown at its own, fitted to the text as other
+10 -7
View File
@@ -264,18 +264,21 @@ impl<'a> PartPages<'a> {
/// The items of `page` that `story`'s pieces are among (each one looked at counted as a step of
/// [`crate::work`]).
fn items_of(page: &Page, story: StoryRef) -> Box<dyn Iterator<Item = &Placed> + '_> {
let items = story_items(page, story);
let items = page.story_items(story);
#[cfg(test)]
let items: Box<dyn Iterator<Item = &Placed> + '_> = Box::new(items.inspect(|_| crate::work::steps(1)));
items
}
fn story_items(page: &Page, story: StoryRef) -> Box<dyn Iterator<Item = &Placed> + '_> {
match story {
StoryRef::Body => Box::new(page.items.iter()),
// Headers and footers, and the text boxes in them, are drawn with the page's header and
// footer; everything else is in its items.
StoryRef::Part(_) => Box::new(page.header.iter().chain(page.footer.iter()).chain(page.items.iter())),
impl Page {
/// The items `story`'s pieces are among: the page's items for the body; for a header,
/// footer or text box, its header and footer too (they hold the header's and footer's
/// pieces, and the text boxes in them).
pub fn story_items(&self, story: StoryRef) -> Box<dyn Iterator<Item = &Placed> + '_> {
match story {
StoryRef::Body => Box::new(self.items.iter()),
StoryRef::Part(_) => Box::new(self.header.iter().chain(self.footer.iter()).chain(self.items.iter())),
}
}
}
+5 -67
View File
@@ -635,27 +635,17 @@ 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 twin = names.iter().filter(|n| *n == name).count() > 1;
let spoken = if twin { format!("{name}, {p}") } else { name.clone() };
let spoken = if names.iter().filter(|n| *n == name).count() > 1 { 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
@@ -669,25 +659,8 @@ fn open_list(app: &mut WordApp, ui: &mut Ui) {
t.accent,
);
let side = crate::rtl::lead_center(rtl);
// 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);
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);
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 };
@@ -718,41 +691,6 @@ 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,289 +75,6 @@ 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,45 +93,6 @@ 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,
@@ -156,12 +117,6 @@ 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,
@@ -193,8 +148,6 @@ 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,
@@ -225,8 +178,6 @@ 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(),
@@ -279,15 +230,6 @@ 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");
}
@@ -299,27 +241,6 @@ 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();
@@ -327,29 +248,13 @@ impl FieldForm {
return None;
}
let name = wordcraft_layout::fields::field_name(&code);
Some(if name == "MERGEFIELD" || is_merge_field(&code) {
json!({"instr": code, "result": format!("«{}»", merge_field_name(&code))})
} else {
json!({"instr": code})
})
Some(if name == "MERGEFIELD" { 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 code = code.trim_start();
let rest = code[field_type_end(code)..].trim_start();
let rest = code.trim_start().split_once(char::is_whitespace).map(|x| x.1.trim_start()).unwrap_or("");
match rest.strip_prefix('"') {
Some(q) => q.split('"').next().unwrap_or("").to_string(),
None => rest.split_whitespace().next().unwrap_or("").to_string(),
@@ -413,7 +318,10 @@ 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() {
f.toggle_codes();
if !f.codes {
f.code = f.instruction();
}
f.codes = !f.codes;
}
});
let params = f.params();
@@ -501,21 +409,7 @@ fn field_options(ui: &mut Ui, f: &mut FieldForm, t: &Tokens) {
}
}
FieldKind::Toc | FieldKind::Plain => {
if !takes_text_format(&f.name) {
ui.label(egui::RichText::new(tl!("This field has no options.")).small().color(t.text_dim));
}
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,141 +149,6 @@ 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]
+17 -120
View File
@@ -11,7 +11,7 @@ use std::path::{Path, PathBuf};
use egui::{Align2, Rect, Sense, Ui, pos2, vec2};
use crate::file_dialogs::{AfterPick, FileDialogRequest, format_name, open_filters, save_filters};
use crate::file_dialogs::{AfterPick, FileDialogRequest, open_filters};
use crate::print_page::{EXPORT_FORMATS, export_file_ext, export_name, is_document_ext};
use crate::theme::{Tokens, regular};
use crate::{WordApp, icons};
@@ -154,18 +154,9 @@ impl FileBrowser {
FileDialogRequest::Open { purpose } | FileDialogRequest::OpenMany { purpose } => {
(String::new(), open_filters(purpose).iter().map(|(l, e)| ((*l).to_string(), e.iter().map(|x| (*x).to_string()).collect())).collect())
}
// Print's Save as PDF writes a PDF whatever type is picked: only that one, then All
// files. (An export's types are File › Export's formats, below.)
FileDialogRequest::Save { name, .. } if matches!(after, AfterPick::PrintPdf { .. }) => {
let ext = Path::new(name).extension().and_then(std::ffi::OsStr::to_str).filter(|e| !e.is_empty());
let mut f: Vec<(String, Vec<String>)> =
ext.map(|e| (format!("{} (*.{e})", format_name(&e.to_ascii_lowercase())), vec![e.to_string()])).into_iter().collect();
f.push(("All files".into(), vec!["*".into()]));
(name.clone(), f)
}
// Every format WordCraft saves, the suggested one first, as the system dialog lists them (#5368).
FileDialogRequest::Save { name, .. } => {
let mut f = save_filters(name);
let ext = Path::new(name).extension().and_then(std::ffi::OsStr::to_str).filter(|e| !e.is_empty());
let mut f: Vec<(String, Vec<String>)> = ext.map(|e| (format!("*.{e}"), vec![e.to_string()])).into_iter().collect();
f.push(("All files".into(), vec!["*".into()]));
(name.clone(), f)
}
@@ -211,27 +202,14 @@ impl FileBrowser {
self.note = Note::None;
}
/// A type was chosen: when exporting it is the format, and the name's export extension follows
/// it. Saving, the name's extension changes to the type's when it is a format's
/// (`Report.docx` → `Report.pdf`), so the type picked is the type saved (#5368).
/// A type was chosen: when exporting it is the format, and the name's export extension follows it.
fn type_changed(&mut self) {
if let Some(format) = self.exports.get(self.filter).cloned() {
// Only a known document extension is replaced; `notes.v2` keeps its `.v2`.
if Path::new(&self.name).extension().and_then(|e| e.to_str()).is_some_and(is_document_ext) {
self.name = export_name(&self.name, &format);
}
self.after = AfterPick::Export { ext: format };
return;
}
if !matches!(self.req, FileDialogRequest::Save { .. }) {
return;
}
let Some(ext) = self.exts().first().filter(|e| e.as_str() != "*").cloned() else { return };
let path = Path::new(&self.name);
let typed = path.extension().and_then(std::ffi::OsStr::to_str);
if typed.and_then(wordcraft_engine::io::save_format).is_some() {
self.name = path.with_extension(ext).to_string_lossy().into_owned();
let Some(format) = self.exports.get(self.filter).cloned() else { return };
// Only a known document extension is replaced; `notes.v2` keeps its `.v2`.
if Path::new(&self.name).extension().and_then(|e| e.to_str()).is_some_and(is_document_ext) {
self.name = export_name(&self.name, &format);
}
self.after = AfterPick::Export { ext: format };
}
fn up(&mut self) {
@@ -267,13 +245,11 @@ impl FileBrowser {
// The chosen type is the format: its extension replaces a known document
// extension on the name, and is added to any other.
path = PathBuf::from(export_name(&path.to_string_lossy(), ext));
} else if let Some(ext) = self.exts().first().filter(|e| e.as_str() != "*") {
// A name with no extension WordCraft saves (`Report v1.2`) gets the type's (#5368).
path = PathBuf::from(wordcraft_engine::io::with_save_ext(&path.to_string_lossy(), ext));
} else if path.extension().is_none()
&& let Some(ext) = self.exts().first().filter(|e| e.as_str() != "*")
{
path.set_extension(ext);
}
// Then the save's own rule (All files: the suggested format; Print's Save as PDF:
// `.pdf`), so a file about to be replaced is asked about under its written name.
path = PathBuf::from(self.after.written_path(&path.to_string_lossy()));
if path.exists() && self.note != Note::Replace(path.clone()) {
self.note = Note::Replace(path);
return Step::Stay;
@@ -324,24 +300,6 @@ impl WordApp {
self.file_browser.open = Some(Box::new(FileBrowser::new(req, after, start, unavailable)));
}
/// Ask whether to replace `path` before a save or export writes it: the built-in browser on
/// its folder and name, saying it exists (#5368 review). The system dialog only asked about
/// the name it returned, and the save added an extension to that. OK replaces the file,
/// another name saves there, Cancel cancels the save.
pub(crate) fn confirm_replace(&mut self, req: FileDialogRequest, after: AfterPick, path: PathBuf) {
let req = match req {
FileDialogRequest::Save { .. } => FileDialogRequest::Save {
name: path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(),
dir: path.parent().filter(|d| d.is_dir()).map(|d| d.to_string_lossy().into_owned()),
},
other => other,
};
self.show_file_browser(req, after, false);
if let Some(b) = self.file_browser.open.as_mut() {
b.note = Note::Replace(path);
}
}
/// `ui.fileBrowser`: the built-in browser for `purpose` (document, picture, recipients, save,
/// export), even when a system dialog was asked for and never showed up (it is given up as cancelled).
pub(crate) fn browse_builtin(&mut self, purpose: &str) {
@@ -353,11 +311,10 @@ impl WordApp {
let (req, after) = match purpose {
"picture" => (FileDialogRequest::Open { purpose: "picture".into() }, AfterPick::Picture),
"recipients" => (FileDialogRequest::Open { purpose: "recipients".into() }, AfterPick::Recipients),
"save" => {
let name = self.default_save_name();
let after = AfterPick::save_as(crate::file_dialogs::AfterSave::Nothing, self.session.document_id(), &name);
(FileDialogRequest::Save { name, dir: None }, after)
}
"save" => (
FileDialogRequest::Save { name: self.default_save_name(), dir: None },
AfterPick::SaveAs { after: crate::file_dialogs::AfterSave::Nothing, document: self.session.document_id() },
),
"export" => {
let ext = pending.unwrap_or_else(|| "pdf".into());
let name = format!("{}.{}", self.title_stem(), export_file_ext(&ext));
@@ -645,66 +602,6 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
/// #5368: the built-in Save As lists every format WordCraft saves, the suggested one first;
/// picking a type changes the name's extension to it, a name with no format's extension gets
/// the type's, and the replace prompt is about the file that will be written.
#[test]
fn save_lists_every_format_and_the_type_picked_is_saved() {
let dir = scratch("save-types");
let req = FileDialogRequest::Save { name: "Document1.docx".into(), dir: None };
let after = AfterPick::save_as(crate::file_dialogs::AfterSave::Nothing, 0, "Document1.docx");
let mut b = FileBrowser::new(req, after, dir.clone(), false);
assert_eq!(b.filters.len(), wordcraft_engine::io::SAVE_EXTS.len() + 1, "every format, then All files");
assert_eq!(b.filters[0].1, ["docx"]);
assert_eq!(b.filters.last().map(|f| f.1.clone()), Some(vec!["*".to_string()]));
let pdf = b.filters.iter().position(|(_, e)| e[0] == "pdf").unwrap();
b.filter = pdf;
b.type_changed();
assert_eq!(b.name, "Document1.pdf");
assert_eq!(b.accept(), Step::Pick(dir.join("Document1.pdf")));
b.name = "Report v1.2".into();
b.type_changed();
assert_eq!(b.name, "Report v1.2", "a name with no format's extension isn't changed");
assert_eq!(b.accept(), Step::Pick(dir.join("Report v1.2.pdf")));
// Another spelling of a format is a format's extension too.
b.name = "Page.htm".into();
b.type_changed();
assert_eq!(b.name, "Page.pdf");
// All files: the suggested format, and a file of that name is asked about before it's replaced.
b.filter = b.filters.len() - 1;
b.type_changed();
b.name = "Bare".into();
assert_eq!(b.accept(), Step::Pick(dir.join("Bare.docx")));
std::fs::write(dir.join("Bare.docx"), b"x").unwrap();
assert_eq!(b.accept(), Step::Stay, "asks before replacing Bare.docx");
assert_eq!(b.accept(), Step::Pick(dir.join("Bare.docx")));
let _ = std::fs::remove_dir_all(&dir);
}
/// #5368 review: Print's Save as PDF writes a PDF whatever type is picked, so the built-in
/// browser offers only that one and All files; the file asked about before it's replaced is
/// the one written, `.pdf` added as `file.printPdf` adds it. (An export's types are File ›
/// Export's formats, and the one picked is written: `export_types_choose_the_format_and_the_extension`.)
#[test]
fn print_to_pdf_lists_only_pdf() {
let dir = scratch("export-types");
let req = FileDialogRequest::Save { name: "Handout.pdf".into(), dir: None };
let mut b = FileBrowser::new(req, AfterPick::PrintPdf { settings: serde_json::json!({}) }, dir.clone(), false);
assert_eq!(b.filters.len(), 2, "{:?}", b.filters);
assert_eq!(b.filters[0].1, ["pdf"]);
assert!(b.filters[0].0.starts_with("PDF"), "{}", b.filters[0].0);
assert_eq!(b.filters[1].1, ["*"]);
b.filter = 1;
b.type_changed();
b.name = "Handout.docx".into();
assert_eq!(b.accept(), Step::Pick(dir.join("Handout.docx.pdf")), "a PDF is written, named so");
std::fs::write(dir.join("Notes.pdf"), b"x").unwrap();
b.name = "Notes".into();
assert_eq!(b.accept(), Step::Stay, "asks before replacing Notes.pdf");
assert_eq!(b.accept(), Step::Pick(dir.join("Notes.pdf")));
let _ = std::fs::remove_dir_all(&dir);
}
/// The host can't show a system dialog (#576): Save As carries on in the built-in browser,
/// and its answer saves the document.
#[test]
+19 -120
View File
@@ -55,69 +55,14 @@ pub fn open_filters(purpose: &str) -> &'static [(&'static str, &'static [&'stati
}
}
/// The file types Save As offers: every format the engine saves, with the suggested name's own
/// format first. rfd makes a filter's first extension the dialog's default, which the Windows,
/// macOS and Linux panels append to a file name the user typed without one; with no filter at
/// all the name came back bare and the save failed, since the format is chosen by extension
/// (#689). The built-in browser lists them too (#5368).
pub fn save_exts(name: &str) -> Vec<String> {
let saves = wordcraft_engine::io::SAVE_EXTS;
let suggested = std::path::Path::new(name)
.extension()
.and_then(std::ffi::OsStr::to_str)
.map(str::to_ascii_lowercase)
// A .markdown file is under Markdown's one entry in the list.
.map(|e| if e == "markdown" { "md".to_string() } else { e })
.filter(|e| saves.contains(&e.as_str()))
.unwrap_or_else(|| "docx".to_string());
let mut exts: Vec<String> = Vec::with_capacity(saves.len());
exts.push(suggested.clone());
exts.extend(saves.iter().filter(|e| **e != suggested).map(|e| (*e).to_string()));
exts
}
/// The "Save as type" list (#1399): one named entry per format, the suggested one first (see
/// [`save_exts`] for why the order matters).
///
/// On Linux and the BSDs, the app asks the desktop portal directly over D-Bus and gives a name
/// the dialog left alone the chosen type's extension (#6180). When falling back to `rfd`, the
/// extension in the name wins, as `rfd` doesn't report which entry the user picked.
pub fn save_filters(name: &str) -> Vec<(String, Vec<String>)> {
save_exts(name).into_iter().map(|e| (format!("{} (*.{e})", format_name(&e)), vec![e])).collect()
}
/// A readable name for a save format's extension.
pub(crate) fn format_name(ext: &str) -> String {
match ext {
"docx" => "Word Document".into(),
"docm" => "Word Macro-Enabled Document".into(),
"dotx" => "Word Template".into(),
"dotm" => "Word Macro-Enabled Template".into(),
"pdf" => "PDF".into(),
"txt" => "Plain Text".into(),
"md" => "Markdown".into(),
"html" => "Web Page".into(),
"rtf" => "Rich Text Format".into(),
"odt" => "OpenDocument Text".into(),
"ott" => "OpenDocument Text Template".into(),
"fodt" => "Flat OpenDocument Text".into(),
"tex" => "LaTeX".into(),
"png" => "PNG Image".into(),
"json" => "JSON".into(),
"xml" => "XML".into(),
other => other.to_ascii_uppercase(),
}
}
/// What to do with the path picked in a dialog.
pub(crate) enum AfterPick {
/// Open the picked document from the window showing `document` ([`WordApp::open_file`]).
OpenDocument { document: u64 },
/// Insert the picked picture, or replace the pending Change Picture target.
Picture,
/// Save the document there, then carry on. A name with no extension WordCraft saves gets
/// `ext`, the suggested name's (#5368).
SaveAs { after: AfterSave, document: u64, ext: String },
/// Save the document there, then carry on.
SaveAs { after: AfterSave, document: u64 },
/// Save a copy there in this format (`pdf`, `docx`, `png`…).
Export { ext: String },
/// Write the PDF of these print settings there (File › Print › Save these pages as PDF).
@@ -137,30 +82,6 @@ pub(crate) enum AfterPick {
ComparePath { revised: bool },
}
impl AfterPick {
/// Save As for `document`, suggested as `name`: its extension is the format a name typed
/// without one is saved in (`.docx` when it has none).
pub(crate) fn save_as(after: AfterSave, document: u64, name: &str) -> Self {
let ext = std::path::Path::new(name).extension().and_then(std::ffi::OsStr::to_str).filter(|e| !e.is_empty()).unwrap_or("docx");
AfterPick::SaveAs { after, document, ext: ext.to_ascii_lowercase() }
}
/// The path a save or export writes for the `path` picked (#5368): Save As adds the format's
/// extension to a name with none it saves; an export names the file as the built-in browser
/// does (`print_page::export_name`: its format's extension replaces a known document one and
/// is added to any other); Print's Save as PDF adds `.pdf` to a name without it, as
/// `file.printPdf` does. Applied before asking to replace a file too, so the file asked about
/// is the one written.
pub(crate) fn written_path(&self, path: &str) -> String {
match self {
AfterPick::SaveAs { ext, .. } => wordcraft_engine::io::with_save_ext(path, ext),
AfterPick::Export { ext } => crate::print_page::export_name(path, ext),
AfterPick::PrintPdf { .. } => wordcraft_engine::io::with_export_ext(path, "pdf"),
_ => path.to_string(),
}
}
}
/// What to do once Save As has written the document.
pub(crate) enum AfterSave {
Nothing,
@@ -228,7 +149,7 @@ impl WordApp {
}
FileDialogRequest::Save { name, .. } => self.services.pick_save.as_ref().and_then(|f| f(name)),
};
self.finish_system_pick(req, after, picked.into_iter().collect()).map_or(Asked::Pending, Asked::Done)
Asked::Done(self.finish_pick(after, picked))
}
/// Pick up the answer of an open file dialog, if it has arrived (every frame, from `logic`),
@@ -242,7 +163,7 @@ impl WordApp {
};
let d = self.file_dialog.take()?;
match answer {
Ok(picked) => self.finish_system_pick(d.req, d.after, picked),
Ok(picked) => Some(self.finish_picks(d.after, picked)),
Err(reason) => {
log::warn!("no system file dialog ({reason}); showing the built-in file browser");
self.dialog_unavailable(d.req, d.after)
@@ -277,24 +198,6 @@ impl WordApp {
Some(self.finish_pick(after, None))
}
/// Finish what the system dialog was for with its answer. A save or export that writes another
/// name than the one picked (its extension added, #5368) asks first when a file of that name
/// exists: the system dialog only asked about the name it returned (#5368 review). `None`
/// while that question is open in the built-in browser.
fn finish_system_pick(&mut self, req: FileDialogRequest, after: AfterPick, picked: Vec<String>) -> Option<Result<Value, String>> {
#[cfg(not(target_arch = "wasm32"))]
if let Some(p) = picked.first() {
let written = after.written_path(p);
if written != *p && std::path::Path::new(&written).exists() {
self.confirm_replace(req, after, std::path::PathBuf::from(written));
return None;
}
}
#[cfg(target_arch = "wasm32")]
let _ = req;
Some(self.finish_picks(after, picked))
}
/// Do what the dialog was for with the picked paths (none: the user cancelled). Only Add Font
/// takes more than one; the others use the first.
fn finish_picks(&mut self, after: AfterPick, picked: Vec<String>) -> Result<Value, String> {
@@ -344,8 +247,6 @@ impl WordApp {
/// Do what the dialog was for with the picked path (`None`: the user cancelled).
pub(crate) fn finish_pick(&mut self, after: AfterPick, picked: Option<String>) -> Result<Value, String> {
// An export names its file itself, below, and won't replace a file under a new name.
let picked = if matches!(after, AfterPick::Export { .. }) { picked } else { picked.map(|p| after.written_path(&p)) };
match after {
AfterPick::OpenDocument { document } => {
let Some(path) = picked else { return Ok(json!({"cancelled": true})) };
@@ -401,22 +302,21 @@ impl WordApp {
self.clear_export_error();
return Ok(json!({"cancelled": true}));
};
// A system Save dialog lets the user type any name, and the engine picks the format
// by the extension (an explicit format only for an .xml path): the file is named as
// the built-in browser names it (`notes.docx` as PDF is `notes.pdf`, `notes.v2`
// `notes.v2.pdf`, #5368). A file of that name the dialog never confirmed isn't
// replaced (the system dialog's answer asks first, `finish_system_pick`).
let named = crate::print_page::export_name(&path, &ext);
if named != path {
path = named;
if std::path::Path::new(&path).exists() {
// Callers drop the result, so say it where the person sees it.
return Err(self.fail_export(format!("{path} already exists; choose another name")));
}
}
let r = if ext == "png" {
self.run("file.exportPng", json!({"path": path}))
} else if ext == "xml" || ext == crate::print_page::EXPORT_WORD_2003 {
// The engine takes an explicit format only for an .xml path, and a system Save
// dialog lets the user type any name: give it the extension, as the built-in
// browser does (`notes.docx` becomes `notes.xml`, `notes.v2` `notes.v2.xml`).
let named = crate::print_page::export_name(&path, "xml");
if named != path {
path = named;
// The dialog only confirmed the name it was given, not this one.
if std::path::Path::new(&path).exists() {
// Callers drop the result, so say it where the person sees it.
return Err(self.fail_export(format!("{path} already exists; choose another name")));
}
}
// Word XML even over a Word 2003 XML file, which a save by path would keep.
let format = if ext == "xml" { wordcraft_engine::cmd::file::FORMAT_FLAT_OPC } else { crate::print_page::EXPORT_WORD_2003 };
self.run("file.saveAs", json!({"path": path, "format": format}))
@@ -444,7 +344,7 @@ impl WordApp {
}
r
}
AfterPick::SaveAs { after, document, .. } => {
AfterPick::SaveAs { after, document } => {
// The document it was for may wait behind another one: it is shown and saved.
if document != self.session.document_id() {
if !self.session.is_open(document) {
@@ -531,8 +431,7 @@ impl WordApp {
/// Ask where to save, save there, then do `after`.
pub(crate) fn save_as(&mut self, after: AfterSave) -> Asked {
let name = self.default_save_name();
let after = AfterPick::save_as(after, self.session.document_id(), &name);
self.ask_file(FileDialogRequest::Save { name, dir: None }, after)
self.ask_file(FileDialogRequest::Save { name, dir: None }, AfterPick::SaveAs { after, document: self.session.document_id() })
}
/// The user templates folder (#2852): the one File › Options names, else the app's own.
@@ -568,7 +467,7 @@ impl WordApp {
}
let dir = dir.filter(|d| d.is_dir()).map(|d| d.to_string_lossy().into_owned());
let name = format!("{}.dotx", self.title_stem());
let after = AfterPick::save_as(AfterSave::Nothing, self.session.document_id(), &name);
let after = AfterPick::SaveAs { after: AfterSave::Nothing, document: self.session.document_id() };
let _ = self.ask_file(FileDialogRequest::Save { name, dir: dir.clone() }, after);
dir
}
-115
View File
@@ -826,118 +826,3 @@ fn many_failed_fonts_end_with_a_count() {
let msg = a.status_msg.as_ref().map(|(m, _)| m.clone()).unwrap_or_default();
assert_eq!(msg, "Added 0 fonts; 5 couldn't be read: f0.ttf, f1.ttf, f2.ttf and 2 more");
}
/// #5368: a name typed without an extension WordCraft saves is saved in the suggested format, as
/// Word adds .docx, instead of failing (the format is chosen by extension); a template keeps
/// .dotx and an export its own format.
#[test]
fn save_as_adds_the_format_to_a_name_without_one() {
let dir = scratch("save-as-ext");
let (mut a, shown) = async_app();
typed(&mut a);
for (name, saved) in [("Report", "Report.docx"), ("Report v1.2", "Report v1.2.docx"), ("Notes.", "Notes.docx"), ("Kept.DOCX", "Kept.DOCX")] {
a.save_as_dialog();
answer(&shown, Some(&dir.join(name).to_string_lossy()));
assert_eq!(a.poll_file_dialog().unwrap().unwrap()["saved"], true, "{name}");
let path = dir.join(saved);
assert_eq!(a.session.path.as_deref(), Some(path.as_path()), "{name}");
assert_eq!(saved_text(&path), UNSAVED, "{name}");
}
a.services.templates_dir = Some(dir.join("Templates"));
a.run("ui.saveAsTemplate", json!({})).unwrap();
answer(&shown, Some(&dir.join("Templates").join("Memo").to_string_lossy()));
assert_eq!(a.poll_file_dialog().unwrap().unwrap()["saved"], true);
assert!(dir.join("Templates").join("Memo.dotx").is_file(), "a template stays a template");
a.export_dialog("pdf");
answer(&shown, Some(&dir.join("Handout").to_string_lossy()));
assert!(a.poll_file_dialog().unwrap().is_ok());
assert!(std::fs::read(dir.join("Handout.pdf")).unwrap().starts_with(b"%PDF"), "an export keeps its format");
// A name with another document format's extension is still a PDF, named as the built-in
// browser names it (`print_page::export_name`).
a.export_dialog("pdf");
answer(&shown, Some(&dir.join("Flyer.docx").to_string_lossy()));
assert!(a.poll_file_dialog().unwrap().is_ok());
assert!(std::fs::read(dir.join("Flyer.pdf")).unwrap().starts_with(b"%PDF"));
assert!(!dir.join("Flyer.docx").exists(), "no Word file written for a PDF export");
let _ = std::fs::remove_dir_all(&dir);
}
/// #5368 (review): the system dialog asks only about the name it returns. When the save adds an
/// extension to it and a file of that name exists, the built-in browser asks before replacing
/// it: Cancel leaves the file alone, OK replaces it. A new name is written straight away.
#[test]
fn a_name_the_save_extends_asks_before_replacing_its_file() {
use crate::file_browser::Step;
let dir = scratch("save-as-ext-replace");
let (mut a, shown) = async_app();
typed(&mut a);
let target = dir.join("Handout.pdf");
std::fs::write(&target, b"old").unwrap();
let export = |a: &mut WordApp| {
a.export_dialog("pdf");
answer(&shown, Some(&dir.join("Handout.docx").to_string_lossy()));
a.poll_file_dialog()
};
assert!(export(&mut a).is_none(), "nothing written yet: the question is open");
assert_eq!(std::fs::read(&target).unwrap(), b"old");
assert!(a.file_browser.open.is_some(), "the built-in browser asks");
a.close_file_browser(None);
assert_eq!(std::fs::read(&target).unwrap(), b"old", "Cancel keeps the file");
assert!(export(&mut a).is_none());
let step = a.file_browser.open.as_mut().map(|b| b.accept());
assert_eq!(step, Some(Step::Pick(target.clone())), "OK on the name asked about replaces it");
a.close_file_browser(Some(target.clone()));
assert!(std::fs::read(&target).unwrap().starts_with(b"%PDF"), "replaced by the export");
// A name whose extended form doesn't exist yet: no question.
a.export_dialog("pdf");
answer(&shown, Some(&dir.join("Fresh.docx").to_string_lossy()));
assert!(a.poll_file_dialog().is_some_and(|r| r.is_ok()));
assert!(std::fs::read(dir.join("Fresh.pdf")).unwrap().starts_with(b"%PDF"));
assert!(a.file_browser.open.is_none());
let _ = std::fs::remove_dir_all(&dir);
}
/// #1399: the Save dialog's type list has one named entry per format, the suggested one first,
/// every savable extension exactly once.
#[test]
fn save_dialog_lists_one_named_type_per_format() {
let filters = save_filters("report.odt");
assert_eq!(filters.len(), wordcraft_engine::io::SAVE_EXTS.len());
assert_eq!(filters[0].1, vec!["odt".to_string()]);
assert!(filters[0].0.contains("OpenDocument"), "{}", filters[0].0);
let all: Vec<&String> = filters.iter().flat_map(|(_, e)| e).collect();
for e in wordcraft_engine::io::SAVE_EXTS {
assert_eq!(all.iter().filter(|x| x.as_str() == *e).count(), 1, "{e}");
}
assert!(filters.iter().all(|(l, e)| !l.trim().is_empty() && e.len() == 1));
let mut labels: Vec<&String> = filters.iter().map(|(l, _)| l).collect();
labels.sort();
labels.dedup();
assert_eq!(labels.len(), filters.len(), "labels are distinct");
// Unknown names fall back to Word's format first.
assert_eq!(save_filters("no extension")[0].1, vec!["docx".to_string()]);
// The OpenDocument template and flat file have their own names.
assert!(save_filters("plan.fodt")[0].0.starts_with("Flat OpenDocument Text"));
assert!(save_filters("form.ott")[0].0.starts_with("OpenDocument Text Template"));
}
/// #689: the Save dialog's default extension is the suggested name's own format, so a file
/// name the user types without one is saved in the document's format instead of coming back
/// bare and failing.
#[test]
fn save_dialog_defaults_to_the_suggested_format() {
assert_eq!(save_exts("novel.docx")[0], "docx");
assert_eq!(save_exts("report.odt")[0], "odt");
assert_eq!(save_exts("annual report.pdf")[0], "pdf");
assert_eq!(save_exts("notes.md")[0], "md");
assert_eq!(save_exts("notes.markdown")[0], "md");
// A suggested name always has an extension; anything unreadable falls back to Word's.
assert_eq!(save_exts("no extension")[0], "docx");
assert_eq!(save_exts("mystery.rtf2")[0], "docx");
// Every savable format is still offered, once.
let exts = save_exts("novel.docx");
assert!(wordcraft_engine::io::SAVE_EXTS.iter().all(|e| exts.iter().any(|x| x == e)));
assert_eq!(exts.len(), wordcraft_engine::io::SAVE_EXTS.len());
}
+1 -1
View File
@@ -105,7 +105,7 @@ pub use dialogs::dialogs_ribbon;
pub use dialogs::dialogs_smart_art;
pub use dialogs::dialogs_table_style;
pub use dialogs::dialogs_templates;
pub use file_dialogs::{FileDialogAnswer, FileDialogRequest, open_filters, save_filters};
pub use file_dialogs::{FileDialogAnswer, FileDialogRequest, open_filters};
mod app;
mod clock;
+24 -22
View File
@@ -142,33 +142,35 @@ pub fn paint(app: &WordApp, painter: &egui::Painter, t: &Tokens, layout: &DocLay
let ink = Stroke::new(1.5, t.accent);
let hover = painter.ctx().input(|i| i.pointer.hover_pos());
match (tool, app.canvas.table_stroke) {
(TableTool::Draw, Some(st)) => match table_draw::stroke(layout, st.page, st.from.0, st.from.1, st.to.0, st.to.1) {
Some(Kind::Rect(r)) => {
if let (Some(a), Some(b)) = (to_screen(st.page, r.x, r.y), to_screen(st.page, r.right(), r.bottom())) {
painter.rect_stroke(Rect::from_two_pos(a, b), 0.0, ink, egui::StrokeKind::Middle);
(TableTool::Draw, Some(st)) => {
match table_draw::stroke_in(layout, st.page, crate::table_resize::reach(app, layout, st.page), st.from.0, st.from.1, st.to.0, st.to.1) {
Some(Kind::Rect(r)) => {
if let (Some(a), Some(b)) = (to_screen(st.page, r.x, r.y), to_screen(st.page, r.right(), r.bottom())) {
painter.rect_stroke(Rect::from_two_pos(a, b), 0.0, ink, egui::StrokeKind::Middle);
}
}
Some(Kind::Vertical { x, y0, y1 }) => {
if let (Some(a), Some(b)) = (to_screen(st.page, x, y0), to_screen(st.page, x, y1)) {
painter.line_segment([a, b], ink);
}
}
Some(Kind::Horizontal { y, x0, x1 }) => {
if let (Some(a), Some(b)) = (to_screen(st.page, x0, y), to_screen(st.page, x1, y)) {
painter.line_segment([a, b], ink);
}
}
// Not a table or a line yet: the drag's box, dashed and dim.
None => {
if let (Some(a), Some(b)) = (to_screen(st.page, st.from.0, st.from.1), to_screen(st.page, st.to.0, st.to.1)) {
dashed_rect(painter, Rect::from_two_pos(a, b), Stroke::new(1.0, t.text_dim));
}
}
}
Some(Kind::Vertical { x, y0, y1 }) => {
if let (Some(a), Some(b)) = (to_screen(st.page, x, y0), to_screen(st.page, x, y1)) {
painter.line_segment([a, b], ink);
}
}
Some(Kind::Horizontal { y, x0, x1 }) => {
if let (Some(a), Some(b)) = (to_screen(st.page, x0, y), to_screen(st.page, x1, y)) {
painter.line_segment([a, b], ink);
}
}
// Not a table or a line yet: the drag's box, dashed and dim.
None => {
if let (Some(a), Some(b)) = (to_screen(st.page, st.from.0, st.from.1), to_screen(st.page, st.to.0, st.to.1)) {
dashed_rect(painter, Rect::from_two_pos(a, b), Stroke::new(1.0, t.text_dim));
}
}
},
}
(TableTool::Erase, _) => {
if let Some(p) = hover
&& let Some((page, x, y)) = crate::canvas::page_at(pages, layout, scale, p)
&& let Some(e) = table_draw::erase_target(layout, page, x, y)
&& let Some(e) = table_draw::erase_target_in(layout, page, crate::table_resize::reach(app, layout, page), x, y)
&& let (Some(a), Some(b)) = (to_screen(page, e.from.0, e.from.1), to_screen(page, e.to.0, e.to.1))
{
painter.line_segment([a, b], Stroke::new(3.0, t.red));
+8 -3
View File
@@ -99,11 +99,16 @@ pub(crate) fn available(app: &WordApp) -> bool {
&& crate::ink::cursor(app).is_none()
}
/// Which tables the pointer reaches on `page`: a header's and footer's while one is edited (#5558).
pub(crate) fn reach(app: &WordApp, layout: &DocLayout, page: usize) -> table_resize::Reach {
table_resize::Reach::of(layout, &app.session.doc, app.session.sel.focus.story, page)
}
/// The border or handle under screen point `p`, if any.
fn target_at(app: &WordApp, layout: &DocLayout, rects: &[Rect], scale: f32, p: Pos2) -> Option<(usize, f32, f32, ResizeTarget)> {
let (page, x, y) = crate::canvas::page_at(rects, layout, scale, p)?;
let sc = page_scale(rects, layout, scale, page)?;
let t = table_resize::resize_target(layout, &app.session.doc, page, x, y, REACH_PX / sc)?;
let t = table_resize::resize_target_in(layout, &app.session.doc, page, x, y, REACH_PX / sc, reach(app, layout, page))?;
Some((page, x, y, t))
}
@@ -167,7 +172,7 @@ pub(crate) fn grab(app: &mut WordApp, layout: &DocLayout, page: usize, x: f32, y
if !available(app) {
return;
}
if let Some(mut target) = table_resize::resize_target(layout, &app.session.doc, page, x, y, 1.0) {
if let Some(mut target) = table_resize::resize_target_in(layout, &app.session.doc, page, x, y, 1.0, reach(app, layout, page)) {
target.limit_to_selection(&app.session, y);
app.canvas.table_resize = Some(ResizeDrag { page, from: (x, y), to: (x, y), target, ruler: true });
}
@@ -277,7 +282,7 @@ pub fn paint(app: &WordApp, painter: &egui::Painter, t: &Tokens, layout: &DocLay
let Some(p) = painter.ctx().input(|i| i.pointer.hover_pos()) else { return };
let Some((page, x, y)) = crate::canvas::page_at(rects, layout, scale, p) else { return };
let Some(sc) = page_scale(rects, layout, scale, page) else { return };
let Some(tg) = table_resize::table_under(layout, &app.session.doc, page, x, y, REACH_PX / sc) else { return };
let Some(tg) = table_resize::table_under_in(layout, &app.session.doc, page, x, y, REACH_PX / sc, reach(app, layout, page)) else { return };
let h = tg.handle();
if let (Some(a), Some(b)) = (s(page, h.x, h.y), s(page, h.right(), h.bottom())) {
let r = Rect::from_two_pos(a, b);
+105
View File
@@ -8430,6 +8430,111 @@ fn focus_hides_the_ribbon_and_escape_brings_it_back() {
assert!(h.state().session.view.read_mode && shown(&h, "Focus"), "Immersive Reader keeps the status bar");
}
/// #5558: while the header is edited, its table is edited like one in the body: a click puts
/// the caret in the cell under it, typing goes there, and a column border drags to a new width.
#[test]
fn a_table_in_the_header_is_clicked_typed_in_and_resized() {
let ctx = egui::Context::default();
let mut a = app();
a.run("text.insert", json!({"text": "Body text"})).unwrap();
a.run("insert.header", json!({"text": "Head"})).unwrap();
a.run("insert.table", json!({"rows": 2, "cols": 2})).unwrap();
a.run("insert.closeHeader", json!({})).unwrap();
a.run("caret.docStart", json!({})).unwrap();
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 900.0));
let mut t = 0.0;
let mut frame = |a: &mut WordApp, events: Vec<egui::Event>| {
t += 1.0 / 60.0;
let input = egui::RawInput { events, time: Some(t), screen_rect: Some(screen), ..Default::default() };
ctx.run_ui(input, |ui| {
a.logic(ui.ctx());
a.ui(ui);
})
.drop_without_applying_deltas();
};
let btn = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
for _ in 0..20 {
frame(&mut a, Vec::new());
}
a.run("insert.editHeader", json!({"page": 0})).unwrap();
for _ in 0..20 {
frame(&mut a, Vec::new());
}
let hf = a.session.sel.focus.story;
assert_ne!(hf, wordcraft_doc::StoryRef::Body, "editing the header");
let cells = |a: &mut WordApp| {
let l = a.session.layout();
let mut v: Vec<(usize, usize, wordcraft_geom::Rect)> = l.pages[0]
.header
.iter()
.filter_map(|it| match it {
wordcraft_layout::Placed::Cell { rect, row, cell, story, .. } if *story == hf => Some((*row, *cell, *rect)),
_ => None,
})
.collect();
v.sort_by_key(|c| (c.0, c.1));
v
};
let cs = cells(&mut a);
assert_eq!(cs.len(), 4, "the header's table is laid out: {cs:?}");
// A click in the second row's second cell puts the caret there.
let r = cs[3].2;
let at = canvas::page_to_screen(&mut a, 0, r.x + r.w / 2.0, r.y + r.h / 2.0).expect("on screen");
frame(&mut a, vec![egui::Event::PointerMoved(at)]);
frame(&mut a, vec![btn(at, true)]);
frame(&mut a, vec![btn(at, false)]);
for _ in 0..10 {
frame(&mut a, Vec::new());
}
let focus = a.session.sel.focus.clone();
assert_eq!(focus.story, hf);
assert_eq!(focus.path.cell().map(|(_, r, c)| (r, c)), Some((1, 1)), "the caret is in the clicked cell: {focus:?}");
frame(&mut a, vec![egui::Event::Text("X".into())]);
frame(&mut a, Vec::new());
assert!(a.session.doc.plain_text(hf).contains('X'), "typing goes into the cell");
// Dragging the border between the columns moves it.
let width = |a: &WordApp| {
let blocks = a.session.doc.story(hf).expect("the header");
blocks.iter().find_map(|b| b.as_table().map(|t| t.grid.clone())).expect("its table")
};
let before = width(&a);
let border = cs[0].2.right();
let y = cs[0].2.y + cs[0].2.h / 2.0;
let from = canvas::page_to_screen(&mut a, 0, border, y).expect("on screen");
let to = from + egui::vec2(60.0, 0.0);
frame(&mut a, vec![egui::Event::PointerMoved(from)]);
frame(&mut a, vec![btn(from, true)]);
for i in 1..=6 {
frame(&mut a, vec![egui::Event::PointerMoved(from + egui::vec2(10.0 * i as f32, 0.0))]);
}
frame(&mut a, vec![btn(to, false)]);
for _ in 0..5 {
frame(&mut a, Vec::new());
}
let after = width(&a);
assert!(after[0] > before[0] + 10.0, "the first column widened: {before:?} → {after:?}");
assert_eq!(a.session.sel.focus.story, hf, "still editing the header");
// A table copied from the body, pasted with Ctrl+V at the end of the header's text, is a
// table there too.
a.run("insert.closeHeader", json!({})).unwrap();
a.run("caret.docEnd", json!({})).unwrap();
a.run("insert.table", json!({"rows": 1, "cols": 3})).unwrap();
a.run("text.insert", json!({"text": "Copied"})).unwrap();
a.run("table.selectTable", json!({})).unwrap();
let copied = a.run("edit.copy", json!({})).unwrap()["text"].as_str().unwrap_or_default().to_string();
a.run("insert.editHeader", json!({"page": 0})).unwrap();
let blocks = a.session.doc.story(hf).map_or(0, |b| b.len());
let head = wordcraft_doc::Pos { story: hf, path: wordcraft_doc::Path::top(blocks.saturating_sub(1)), off: 4 };
a.run("caret.set", json!({"pos": head})).unwrap();
frame(&mut a, vec![egui::Event::Paste(copied)]);
for _ in 0..5 {
frame(&mut a, Vec::new());
}
let tables: Vec<usize> = a.session.doc.story(hf).expect("the header").iter().filter_map(|b| b.as_table().map(|t| t.cols())).collect();
assert_eq!(tables, vec![2, 3], "the pasted table is a table in the header");
assert_eq!(cells(&mut a).len(), 4 + 3, "and is drawn there");
}
#[test]
fn format_painter_single_click_formats_the_target_word_and_finishes() {
let mut a = app();
+2 -2
View File
File diff suppressed because one or more lines are too long
+5 -5
View File
File diff suppressed because one or more lines are too long