Compare commits

...
Author SHA1 Message Date
autocraft-bot[bot] b741bbac9a Merge pull request #3503 2026-12-02 20:54:13 +00:00
autocraft-bot[bot] fd948e2015 Merge pull request #8260 2026-12-02 20:54:13 +00:00
autocraft-bot[bot] 612e92e6c5 Merge pull request #8219 2026-12-02 20:54:13 +00:00
autocraft-bot[bot] 5ae937d8e3 Merge pull request #8216 2026-12-02 20:54:13 +00:00
autocraft-bot[bot] c07395d712 Merge pull request #8188 2026-12-02 20:54:13 +00:00
batistalucasv e874c67147 caret: Page Up/Down reach the story's ends on the first and last page (#8200) 2026-12-01 14:09:32 -03:00
batistalucasv 8d7ed624ec Prefs: store recent files relative to the home directory (#8189) 2026-11-30 18:19:21 -03:00
17ae08d4b8 Floating toolbar: a size typed into the Font Size box applies on Enter
Typing a size into the floating toolbar's Font Size box and pressing
Enter left the text at its old size. Only a pick from the list worked.
The box's text is rebuilt from the selection's size on every pass and
was bound write-through, so the next pass put the old size back before
Enter could commit the typed one.

The box now binds its text with EditPolicy::OnCommit, which keeps what
is typed in the box until it is committed. craft's text field also
commits when focus leaves it, so the code after the box now counts
only Enter or a pick from the list, as its comment says: a size left
in the box by a click elsewhere is not applied, as in v0.19.1. The
test from the previous commit passes.

Co-Authored-By: GPT-6.2 Astra <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 20:26:29 +11:00
8edbfcdeef test(ui-egui): a size typed into the floating toolbar's size box applies on Enter
The test selects text and types 20, then 16.5, into the floating
toolbar's Font Size box with real pointer and key events. It checks
that typing alone changes nothing, that Enter applies the typed size and
that the selection stays. It fails without the fix in the next commit.

Co-Authored-By: GPT-6.2 Astra <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 20:26:23 +11:00
Zaxaerith 19947b9170 fix(cli): honor repeated --save options in run (#8177) 2026-11-30 17:17:43 +08:00
FredApps eeac0d3322 Merge origin/main into fix/turkish-change-case-dotted-i 2026-11-28 05:18:24 +07:00
Divyanshu Gupta 6e783bdc6e fix(engine): preserve AutoCorrect İ lowering for non-Turkic languages
Keep AutoCorrect's specific mapping of İ -> i for non-Turkic languages while allowing Change Case to use Unicode-default lowering, and add regression tests for English two-initial-capitals and caps-lock.
2026-10-22 00:43:17 +05:30
Divyanshu Gupta aea58b38b8 fix(engine): apply Turkic case mapping in Change Case for Turkish, Azerbaijani, and Crimean Tatar
In Change Case, resolve the effective run language and apply language-aware casing for Turkish, Azerbaijani, and Crimean Tatar (mapping i <-> İ and ı <-> I). Non-Turkic languages continue to use default Unicode casing.

Closes #3479
2026-10-21 23:49:45 +05:30
12 changed files with 371 additions and 12 deletions
+11 -2
View File
@@ -36,9 +36,11 @@ USAGE:
page can't be drawn or a picture is missing or undecodable
(report on stderr, as for convert --strict)
wordcraft-cli run [--file F | --template T] [--script FILE|-] [--cmd 'id={json}' …]
[--save OUT] [--page N] [--scale S] [--print] [--author NAME]
[--save OUT …] [--page N] [--scale S] [--print] [--author NAME]
run commands headlessly, then save (--author names
who tracked changes and comments are by).
Repeat --save OUT to write multiple outputs in order,
after any outputs from --script.
PNG saves use --page (1-based, default 1) and --scale (default 2).
--script runs a JSON file (- is stdin) first:
{\"file\"?, \"template\"?, \"commands\": [{\"command\": id,
@@ -632,6 +634,13 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
}
}
validate_options("run", &rest, RUN_OPTIONS)?;
let mut cli_outputs = Vec::new();
for (i, arg) in rest.iter().enumerate() {
if arg == "--save" {
let path = rest.get(i + 1).filter(|value| !value.is_empty() && !value.starts_with("--")).ok_or("run: --save requires a path")?;
cli_outputs.push(path.clone());
}
}
let page = parse_page_arg("run", &rest)?;
let scale = parse_scale_arg("run", &rest)?;
let password = password_from(&rest)?;
@@ -680,7 +689,7 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
i += 1;
}
}
let outputs: Vec<String> = script.iter().flat_map(|c| c.save.iter().cloned()).chain(arg_value(&rest, "--save")).collect();
let outputs: Vec<String> = script.iter().flat_map(|c| c.save.iter().cloned()).chain(cli_outputs).collect();
// Check every output can be made before writing any, so a bad one leaves no half-done job.
for out in &outputs {
let parent = Path::new(out).parent().filter(|p| !p.as_os_str().is_empty());
+58
View File
@@ -564,6 +564,64 @@ fn script_builds_a_document_and_saves_docx_and_pdf_relative_to_the_script() {
assert!(json.contains("Hello script") && json.contains("\"bold\":true"));
}
#[test]
fn run_saves_each_cli_output_and_still_accepts_a_single_save() {
let dir = script_dir("cli-saves");
let input = dir.join("in.docx");
let docx = dir.join("out.docx");
let pdf = dir.join("out.pdf");
run(&args(&["run", "--template", "sample", "--save", &input.to_string_lossy()])).unwrap();
run(&args(&["run", "--file", &input.to_string_lossy(), "--save", &docx.to_string_lossy(), "--save", &pdf.to_string_lossy()])).unwrap();
assert_eq!(listed_text(&open(&docx, None).unwrap().doc).unwrap(), listed_text(&open(&input, None).unwrap().doc).unwrap());
assert!(std::fs::read(pdf).unwrap().starts_with(b"%PDF"));
}
#[test]
fn run_saves_script_and_cli_outputs() {
let dir = script_dir("mixed-saves");
let script = write_script(&dir, r#"{"commands":["caret.docEnd"],"save":["script.txt","script.docx"]}"#);
let first = dir.join("cli.txt");
let second = dir.join("cli.docx");
run(&args(&["run", "--save", &first.to_string_lossy(), "--script", &script, "--save", &second.to_string_lossy()])).unwrap();
for path in [dir.join("script.txt"), dir.join("script.docx"), first, second] {
assert!(path.is_file(), "{} was not written", path.display());
}
}
#[test]
fn run_rejects_a_missing_second_save_path_before_writing() {
let dir = script_dir("missing-save");
let first = dir.join("first.docx");
let first_path = first.to_string_lossy();
for tail in [vec!["--save"], vec!["--save", "--print"], vec!["--save", ""]] {
let mut argv: Vec<&str> = vec!["run", "--save", &first_path];
argv.extend(tail);
assert_eq!(run(&args(&argv)), Err("run: --save requires a path".into()));
assert!(!first.exists());
}
}
#[test]
fn run_preflights_script_and_cli_outputs_in_order_before_writing() {
let dir = script_dir("preflight-saves");
let first = dir.join("first.docx");
let invalid = dir.join("missing/later.docx");
let last = dir.join("missing-too/last.docx");
let mut script = write_script(&dir, r#"{"commands":["caret.docEnd"],"save":["missing-script/script.docx"]}"#);
let first_path = first.to_string_lossy();
let invalid_path = invalid.to_string_lossy();
let last_path = last.to_string_lossy();
let argv = |script: &str| args(&["run", "--save", &first_path, "--save", &invalid_path, "--script", script, "--save", &last_path]);
let err = run(&argv(&script)).unwrap_err().to_string();
assert!(err.contains("script.docx"), "{err}");
assert!(!first.exists());
script = write_script(&dir, r#"{"commands":["caret.docEnd"],"save":["script.docx"]}"#);
let err = run(&argv(&script)).unwrap_err().to_string();
assert!(err.contains("later.docx"), "{err}");
assert!(!first.exists() && !dir.join("script.docx").exists());
}
#[test]
fn script_with_a_bad_output_writes_no_output() {
let dir = script_dir("badout");
+5 -1
View File
@@ -300,7 +300,11 @@ fn page(s: &mut Session, v: &Value, dir: i32) -> CmdResult {
}
let Some(c) = l.caret_on(&from, s.page_hint) else { return sel_result(s) };
let np = if dir < 0 { c.page.saturating_sub(1) } else { (c.page + 1).min(l.pages.len().saturating_sub(1)) };
let to = l.hit(np, c.x, c.top + 1.0, from.story).unwrap_or(from);
let to = if np == c.page {
if dir < 0 { s.doc.start_of(from.story) } else { s.doc.end_of(from.story) }
} else {
l.hit(np, c.x, c.top + 1.0, from.story).unwrap_or(from)
};
s.page_hint = np;
apply(s, to, ext);
sel_result(s)
+97
View File
@@ -9734,6 +9734,77 @@ fn change_case_keeps_each_runs_formatting_when_lengths_change() {
assert_eq!(text(&s), "Q");
}
/// #3479: Change Case follows language-aware mapping for Turkish, Azerbaijani, and Crimean Tatar (i↔İ, ı↔I).
#[test]
fn change_case_follows_turkic_language_mapping() {
// 1. Turkish (tr-TR): all 5 modes
// Capitalize Each Word (title)
let mut s = s();
run(&mut s, "review.language", json!({"lang": "tr-TR", "default": true}));
run(&mut s, "text.insert", json!({"text": "istanbul ışık", "raw": true}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": "title"}));
assert_eq!(text(&s), "İstanbul Işık");
// UPPERCASE
run(&mut s, "format.changeCase", json!({"mode": "upper"}));
assert_eq!(text(&s), "İSTANBUL IŞIK");
// lowercase
run(&mut s, "format.changeCase", json!({"mode": "lower"}));
assert_eq!(text(&s), "istanbul ışık");
// sentence case
let mut s = self::s();
run(&mut s, "review.language", json!({"lang": "tr-TR", "default": true}));
run(&mut s, "text.insert", json!({"text": "istanbul. ışık.", "raw": true}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": "sentence"}));
assert_eq!(text(&s), "İstanbul. Işık.");
// toggle case
let mut s = self::s();
run(&mut s, "review.language", json!({"lang": "tr-TR", "default": true}));
run(&mut s, "text.insert", json!({"text": "İstanbul Işık", "raw": true}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": "toggle"}));
assert_eq!(text(&s), "iSTANBUL ıŞIK");
// 2. Azerbaijani (az-AZ)
let mut s = self::s();
run(&mut s, "review.language", json!({"lang": "az-AZ", "default": true}));
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": "title"}));
assert_eq!(text(&s), "İstanbul");
// 3. Crimean Tatar (crh)
let mut s = self::s();
run(&mut s, "review.language", json!({"lang": "crh", "default": true}));
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": "title"}));
assert_eq!(text(&s), "İstanbul");
// 4. English control (en-US): unchanged Unicode default
let mut s = self::s();
run(&mut s, "review.language", json!({"lang": "en-US", "default": true}));
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": "title"}));
assert_eq!(text(&s), "Istanbul");
// 5. Mixed-language selection: Turkish run followed by English run
let mut s = self::s();
run(&mut s, "review.language", json!({"lang": "tr-TR"}));
run(&mut s, "text.insert", json!({"text": "istanbul ", "raw": true}));
run(&mut s, "review.language", json!({"lang": "en-US"}));
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.changeCase", json!({"mode": "title"}));
assert_eq!(text(&s), "İstanbul Istanbul");
}
#[test]
fn change_case_sentence_ignores_decimal_points() {
// #3485: Sentence case should not capitalize after decimal points.
@@ -15344,6 +15415,32 @@ 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");
}
#[test]
fn page_down_and_up_reach_the_ends_on_first_and_last_page() {
let mut s = s();
for i in 0..80 {
if i > 0 {
run(&mut s, "text.newParagraph", json!({}));
}
run(&mut s, "text.insert", json!({"text": format!("Paragraph {i}")}));
}
let pages = s.layout().pages.len();
assert!(pages >= 2, "expected a multi-page document, got {pages}");
run(&mut s, "caret.docStart", json!({}));
let start = s.sel.focus.clone();
// Advance page by page until the last page, then one more PageDown must reach the end.
for _ in 0..pages {
run(&mut s, "caret.pageDown", json!({}));
}
let end = s.doc.end_of(wordcraft_doc::StoryRef::Body);
assert_eq!(s.sel.focus, end, "PageDown on the last page reaches the end of the document");
// Step back page by page until page 0, then one more PageUp must reach the start.
for _ in 0..pages {
run(&mut s, "caret.pageUp", json!({}));
}
assert_eq!(s.sel.focus, start, "PageUp on the first page reaches the start of the document");
}
/// #5428: an inserted or pasted picture fits where it goes, as in Word: a table cell's width
/// (a nested cell's too), a column's, not the whole page's text width.
#[cfg(not(target_arch = "wasm32"))]
+10 -1
View File
@@ -3416,13 +3416,22 @@ fn autocorrect_capitalisation_follows_turkic_case_mapping() {
run(&mut s, "review.language", json!({"lang": "en-US", "default": true}));
typ(&mut s, "İNgilizce ");
assert_eq!(s.doc.plain_text(StoryRef::Body), "İngilizce ", "no combining dot in any language");
// #3503: two initial capitals and caps-lock with a stray İ in English.
let mut s = self::s();
run(&mut s, "review.language", json!({"lang": "en-US", "default": true}));
typ(&mut s, "Wİrd ");
assert_eq!(s.doc.plain_text(StoryRef::Body), "Wird ", "two initial capitals lowercases İ to i in English");
let mut s = self::s();
run(&mut s, "review.language", json!({"lang": "en-US", "default": true}));
typ(&mut s, "wİRD ");
assert_eq!(s.doc.plain_text(StoryRef::Body), "Wird ", "caps-lock slip fixes wİRD to Wird in English");
}
/// #3479: Format > Change Case follows the same Turkic case mapping as AutoCorrect, using
/// each run's own language; other languages keep the Unicode default.
#[test]
fn change_case_follows_turkic_case_mapping() {
for tag in ["tr-TR", "az-AZ"] {
for tag in ["tr-TR", "az-AZ", "crh"] {
for (mode, input, want) in [
("upper", "istanbul", "İSTANBUL"),
("lower", "IŞIK", "ışık"),
+2 -1
View File
@@ -887,8 +887,9 @@ impl WordApp {
let Some(path) = p.get("path").and_then(Value::as_str) else {
return Some(Err("`path` must name a document on the recent list".into()));
};
let resolved = crate::prefs::expand_recent_path(path);
let before = self.ui.recent.len();
self.ui.recent.retain(|r| r != path);
self.ui.recent.retain(|r| r != path && r != &resolved);
if self.ui.recent.len() == before {
return Some(Err(format!("`{path}` is not on the recent list")));
}
+3
View File
@@ -23,6 +23,7 @@ impl WordApp {
ui.keyboard = Shortcuts(self.session.keymap().clone());
ui.ribbon = self.session.ribbon.clone();
ui.ink_pens = self.session.view.draw.pens.clone();
ui.recent = ui.recent.iter().map(|p| crate::prefs::contract_recent_path(p)).collect();
ui
}
@@ -35,6 +36,8 @@ impl WordApp {
self.ui.tab = DEFAULT_TAB.into();
let recent_fonts = recent_fonts_from(self.ui.font_picker.recent.iter().map(String::as_str));
self.ui.font_picker.recent = recent_fonts;
let mut seen_recent = std::collections::HashSet::with_capacity(self.ui.recent.len());
self.ui.recent = self.ui.recent.iter().map(|p| crate::prefs::expand_recent_path(p)).filter(|p| seen_recent.insert(p.clone())).collect();
// Settings from before the theme setting: their dark-mode switch picks Dark or Light.
if let Some(dark) = self.ui.legacy_dark.take() {
self.ui.theme = if dark { theme::Appearance::Dark } else { theme::Appearance::Light };
+6 -5
View File
@@ -2,7 +2,7 @@
//! formatting controls. The framework's selection task bar places it (above the selection, flipped
//! and clamped inside the document area); this module decides when it shows and what it holds.
use craft::behavior::{EditEvent, Preview};
use craft::behavior::{EditEvent, EditPolicy, Preview};
use craft::keymap::CommandRef;
use craft::pages::ui::PageBody;
use craft::ui::buttons::{Button, ControlPlace, GroupLevel, ToggleButton};
@@ -198,13 +198,14 @@ pub(crate) fn members(app: &mut WordApp, ui: &mut Ui, preview: bool) {
.map(|s| Entry::new(number_text(f64::from(*s)), number_text(f64::from(*s))))
.collect();
let mut text = size.clone();
let combo = ComboBox::new(tl!("Font Size").to_string(), Bind::bound(&mut text), &sizes).show(ui);
// `text` is rebuilt from the selection on every pass: the box keeps what is typed until Enter.
let combo = ComboBox::new(tl!("Font Size").to_string(), Bind::bound(&mut text).policy(EditPolicy::OnCommit), &sizes).show(ui);
follow_list(app, preview, &combo.preview, |v| {
v.trim().parse::<f64>().ok().map(|x| ("format.size".to_string(), json!({"size": x})))
});
// Only a pick or Enter applies the size: typing alone is an edit of the box's draft.
let committed =
combo.edit.submitted || combo.edit.events.iter().any(|e| matches!(e, EditEvent::Set { .. } | EditEvent::Commit { .. }));
// Only a pick or Enter applies the size: typing alone is an edit of the box's draft, and leaving the box
// without either drops it.
let committed = combo.edit.submitted || combo.edit.events.iter().any(|e| matches!(e, EditEvent::Set { .. }));
if committed
&& text != size
&& let Ok(x) = text.trim().parse::<f64>()
+22
View File
@@ -980,3 +980,25 @@ fn automatic_and_no_color_preview_on_hover() {
assert_eq!(h.state().canvas.command_previewed, None, "{button} {item_label}: Escape clears the preview");
}
}
/// A size typed into the bar's size box applies when Enter is pressed. The box's
/// text was rebuilt from the selection on every pass, so what was typed was gone by then.
#[test]
fn a_size_typed_into_the_bar_size_box_applies_on_enter() {
let mut h = bar_over("brown fox");
for typed in ["20", "16.5"] {
h.state_mut().run("select.text", json!({"text": "brown fox"})).unwrap();
steps(&mut h);
let selection = h.state().session.sel.clone();
let before = format_state(&mut h).get("size").and_then(Value::as_f64);
let at = size_box(&h).center();
click_at(&mut h, at);
press_key(&mut h, egui::Key::A, egui::Modifiers { ctrl: true, command: true, ..Default::default() });
h.event(egui::Event::Text(typed.into()));
steps(&mut h);
assert_eq!(format_state(&mut h).get("size").and_then(Value::as_f64), before, "typing {typed} alone changes nothing");
press_key(&mut h, egui::Key::Enter, egui::Modifiers::NONE);
assert_eq!(format_state(&mut h).get("size").and_then(Value::as_f64), typed.parse::<f64>().ok(), "Enter applies the typed size {typed}");
assert_eq!(h.state().session.sel, selection, "the selection stays");
}
}
+102
View File
@@ -461,3 +461,105 @@ pub fn import_legacy_window(bytes: &[u8], store: &mut craft::window::restore::St
#[cfg(test)]
mod tests;
/// Returns the user's home directory from `HOME` or `USERPROFILE`, if set and non-empty.
fn home_dir() -> Option<std::path::PathBuf> {
std::env::var_os("HOME")
.filter(|h| !h.is_empty())
.or_else(|| std::env::var_os("USERPROFILE").filter(|h| !h.is_empty()))
.map(std::path::PathBuf::from)
}
fn strip_tilde_prefix(path: &str) -> Option<&str> {
if cfg!(windows) { path.strip_prefix("~/").or_else(|| path.strip_prefix("~\\")) } else { path.strip_prefix("~/") }
}
fn split_tilde_rest(rest: &str) -> impl Iterator<Item = &str> {
let is_sep = |c: char| c == '/' || (cfg!(windows) && c == '\\');
rest.split(is_sep).filter(|s| !s.is_empty())
}
fn strip_home_prefix<'a>(path: &'a std::path::Path, home: &std::path::Path) -> Option<Vec<std::path::Component<'a>>> {
if cfg!(not(windows)) {
return path.strip_prefix(home).ok().map(|rel| rel.components().collect());
}
let mut path_comps = path.components();
for h in home.components() {
let p = path_comps.next()?;
let matches = match (h, p) {
(std::path::Component::Prefix(a), std::path::Component::Prefix(b)) => {
a.as_os_str().to_string_lossy().eq_ignore_ascii_case(&b.as_os_str().to_string_lossy())
}
(std::path::Component::RootDir, std::path::Component::RootDir) | (std::path::Component::CurDir, std::path::Component::CurDir) => true,
(std::path::Component::ParentDir, std::path::Component::ParentDir) => true,
(std::path::Component::Normal(a), std::path::Component::Normal(b)) => {
a.to_string_lossy().to_lowercase() == b.to_string_lossy().to_lowercase()
}
_ => false,
};
if !matches {
return None;
}
}
Some(path_comps.collect())
}
/// Contracts a path inside `home` to `~/...` with `/` separators for cross-OS profile sync (#8189).
/// Paths outside `home`, containing `..`, or (on Unix) literal backslashes are returned unchanged.
pub(crate) fn contract_recent_path_with(path: &str, home: Option<&std::path::Path>) -> String {
if let Some(rest) = strip_tilde_prefix(path) {
let parts: Vec<_> = split_tilde_rest(rest).collect();
return if parts.is_empty() { path.to_string() } else { format!("~/{}", parts.join("/")) };
}
let Some(home) = home else {
return path.to_string();
};
let Some(rel) = strip_home_prefix(std::path::Path::new(path), home) else {
return path.to_string();
};
let mut parts = Vec::new();
for c in rel {
match c {
std::path::Component::Normal(s) => {
let s = s.to_string_lossy();
if s.contains('\\') {
return path.to_string();
}
parts.push(s);
}
std::path::Component::CurDir => {}
std::path::Component::ParentDir | std::path::Component::RootDir | std::path::Component::Prefix(_) => {
return path.to_string();
}
}
}
if parts.is_empty() { path.to_string() } else { format!("~/{}", parts.join("/")) }
}
/// Expands a `~/...` recent-file path against `home`; other paths (or entries whose components
/// would replace `home`, such as `..` or a Windows drive prefix) are returned unchanged (#8189).
pub(crate) fn expand_recent_path_with(path: &str, home: Option<&std::path::Path>) -> String {
let Some(rest) = strip_tilde_prefix(path) else {
return path.to_string();
};
let Some(home) = home else {
return path.to_string();
};
let mut out = home.to_path_buf();
for part in split_tilde_rest(rest) {
let mut comps = std::path::Path::new(part).components();
if !matches!((comps.next(), comps.next()), (Some(std::path::Component::Normal(_)), None)) {
return path.to_string();
}
out.push(part);
}
out.to_string_lossy().into_owned()
}
pub(crate) fn contract_recent_path(path: &str) -> String {
contract_recent_path_with(path, home_dir().as_deref())
}
pub(crate) fn expand_recent_path(path: &str) -> String {
expand_recent_path_with(path, home_dir().as_deref())
}
+52
View File
@@ -219,3 +219,55 @@ fn recent_list_edits_are_final_and_persist() {
assert!(c.ui.recent.is_empty());
let _ = std::fs::remove_dir_all(&dir);
}
/// #8189: recent paths inside the user's home directory are stored as `~/...` and resolved on load.
#[test]
fn recent_paths_inside_home_contract_and_expand() {
use std::path::Path;
let home = Path::new("/home/alice");
let inside = home.join("Docs").join("test.docx");
let contracted = super::contract_recent_path_with(&inside.to_string_lossy(), Some(home));
assert_eq!(contracted, "~/Docs/test.docx");
assert_eq!(super::expand_recent_path_with(&contracted, Some(home)), inside.to_string_lossy());
// Paths outside home, with `..`, and the home directory itself stay unchanged.
assert_eq!(super::contract_recent_path_with("/tmp/outside.docx", Some(home)), "/tmp/outside.docx");
assert_eq!(super::contract_recent_path_with("/home/alice/../etc/passwd", Some(home)), "/home/alice/../etc/passwd");
assert_eq!(super::contract_recent_path_with(&home.to_string_lossy(), Some(home)), home.to_string_lossy());
if cfg!(not(windows)) {
let literal_backslash = "/home/alice/Docs/a\\b.docx";
assert_eq!(super::contract_recent_path_with(literal_backslash, Some(home)), literal_backslash);
assert_eq!(super::expand_recent_path_with("~/Docs/a\\b.docx", Some(home)), literal_backslash);
// Case-sensitive on Unix.
assert_eq!(super::contract_recent_path_with("/home/Alice/Docs/test.docx", Some(home)), "/home/Alice/Docs/test.docx");
} else {
let win_home = Path::new(r"C:\Users\Alice");
assert_eq!(super::contract_recent_path_with(r"c:\users\alice\Docs\test.docx", Some(win_home)), "~/Docs/test.docx");
assert_eq!(super::expand_recent_path_with("~/Docs/C:notes.docx", Some(win_home)), "~/Docs/C:notes.docx");
}
assert_eq!(super::expand_recent_path_with("~/Docs/../outside.docx", Some(home)), "~/Docs/../outside.docx");
assert_eq!(super::expand_recent_path_with("/tmp/outside.docx", Some(home)), "/tmp/outside.docx");
assert_eq!(super::expand_recent_path_with("~/Docs/test.docx", None), "~/Docs/test.docx");
// Round-trip through WordApp::prefs / apply_prefs using the process home directory.
let real_home = std::env::var_os("HOME")
.filter(|h| !h.is_empty())
.or_else(|| std::env::var_os("USERPROFILE").filter(|h| !h.is_empty()))
.map(std::path::PathBuf::from);
if let Some(real_home) = real_home {
let doc = real_home.join("WordCraftSyncTest").join("notes.docx");
let doc_str = doc.to_string_lossy().into_owned();
let mut a = app();
a.ui.recent = vec![doc_str.clone(), "/tmp/outside.docx".into()];
let saved = a.prefs();
assert_eq!(saved.recent, vec!["~/WordCraftSyncTest/notes.docx".to_string(), "/tmp/outside.docx".to_string()]);
let mut loaded = saved;
loaded.recent.push(doc_str.clone());
a.apply_prefs(loaded);
assert_eq!(a.ui.recent, vec![doc_str, "/tmp/outside.docx".to_string()]);
assert!(a.run("ui.recentRemove", json!({"path": "~/WordCraftSyncTest/notes.docx"})).is_ok());
assert_eq!(a.ui.recent, vec!["/tmp/outside.docx".to_string()]);
}
}
+3 -2
View File
@@ -73,8 +73,9 @@ PDF in one run without a window:
`file` (a document to open) and `template` are optional, and `--file` / `--template` on the command
line win. A command is `{"command": id, "params": {…}}` or just the id. `save` is a path or a list;
each output's format follows its extension. Relative `file` and `save` paths resolve against the
script's folder (the working folder for stdin). `--cmd` flags run after the script's commands and
`--save` after its outputs. The run starts with one open document. `file.new` and `file.open`
script's folder (the working folder for stdin). `--cmd` flags run after the script's commands.
Repeat `--save OUT` to write additional outputs in command-line order, after the script's outputs.
Each `--save` requires a path. The run starts with one open document. `file.new` and `file.open`
open another one and make it active; later commands and the saves work on the active document.
`view.switchWindows` lists the open documents (with `--print` their ids show), and
`view.switchWindows={"id": n}` makes one active. A failing command stops the run with `command N (id): …` and exit