mirror of
https://github.com/storytold/wordcraft.git
synced 2026-12-02 22:30:10 +00:00
Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b741bbac9a | ||
|
|
fd948e2015 | ||
|
|
612e92e6c5 | ||
|
|
5ae937d8e3 | ||
|
|
c07395d712 | ||
|
|
e874c67147 | ||
|
|
8d7ed624ec | ||
|
|
17ae08d4b8 | ||
|
|
8edbfcdeef | ||
|
|
19947b9170 | ||
|
|
eeac0d3322 | ||
|
|
6e783bdc6e | ||
|
|
aea58b38b8 |
@@ -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());
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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"))]
|
||||
|
||||
@@ -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"),
|
||||
|
||||
@@ -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")));
|
||||
}
|
||||
|
||||
@@ -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 };
|
||||
|
||||
@@ -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>()
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
|
||||
@@ -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
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user