Compare commits

..
Author SHA1 Message Date
autocraft-bot[bot] 43ccc15c24 Merge main (48e07fbc) into the pull request
Resolved the only conflict, in docs/layout-parity.md. I kept main's stat

Resolved the only conflict, in docs/layout-parity.md. I kept main's status line and put the #6331 CREATEDATE entry first, with main's #3986 entry now the first "previously" item. "Last updated" is 2026-11-23. No conflict markers remain. I didn't build or run tests, since only a documentation line changed.
2026-12-02 20:50:35 +00:00
ljkx 7777eba6e4 Merge remote-tracking branch 'origin/main' into fix/createdate-keeps-date
# Conflicts:
#	docs/layout-parity.md
2026-11-23 03:04:48 +01:00
ljkx 554a7d689e #6331: CREATEDATE reads a creation date without seconds
W3CDTF allows hh:mm without seconds (2019-05-05T12:00Z), which
parse_from_rfc3339 refuses, so such a file kept its cached result.
created_at now reads that form too, with Z or an offset.
2026-11-17 04:32:55 +01:00
ljkx 2c32076416 #6331: layout-parity status line and revision row for CREATEDATE at the top 2026-11-17 04:32:54 +01:00
ljkx 19b8dfece6 Merge remote-tracking branch 'upstream/main' into fix/createdate-keeps-date 2026-11-17 04:32:14 +01:00
ljkx 1336bc27cb #6331 review: CREATEDATE in documents from templates, opened files without a date, date-only values
A document made from a template no longer inherits the template's creation
date: it has none until it is saved, so CREATEDATE shows today. A file
opened without a creation date keeps the field's cached result, as one with
an unreadable date already did; only a new, never-saved document uses
today. A date-only creation date (2019-05-05, which W3CDTF allows) shows as
that calendar day in every time zone. The test's expected date for
12:00 UTC now follows the local offset, so it passes east of UTC+12 too.
2026-11-12 14:16:39 +01:00
ljkx a525210f48 #6331: Updating fields keeps CREATEDATE on the document's creation date
CREATEDATE is formatted from the document's creation date (dcterms:created) in local time, not from the clock. A creation date that can't be read keeps the field's result; a document never saved (no creation date yet) still shows today.
2026-11-11 19:03:44 +01:00
25 changed files with 158 additions and 663 deletions
+2 -11
View File
@@ -36,11 +36,9 @@ 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,
@@ -634,13 +632,6 @@ 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)?;
@@ -689,7 +680,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(cli_outputs).collect();
let outputs: Vec<String> = script.iter().flat_map(|c| c.save.iter().cloned()).chain(arg_value(&rest, "--save")).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,64 +564,6 @@ 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");
+1 -5
View File
@@ -300,11 +300,7 @@ 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 = 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)
};
let to = 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)
+2
View File
@@ -342,6 +342,8 @@ pub(crate) fn new_from_template(s: &mut Session, v: &Value) -> CmdResult {
let path = p::req_str(v, "path")?;
let (mut doc, _) = read_document(s, path, v)?;
doc.settings.attached_template = Some(path.to_string());
// A new document: not created when the template was. Saving stamps its creation date.
doc.core.created.clear();
if p::bool(v, "replaceBlank") == Some(true) && s.used_because().is_none() {
s.set_document(doc);
} else {
+31 -1
View File
@@ -422,7 +422,19 @@ pub fn update_fields_in(s: &mut Session, all: bool) -> Result<(), CmdError> {
"DATE" | "TIME" | "CREATEDATE" | "SAVEDATE" | "PRINTDATE" => {
let lang = field_lang(&s.doc, p, k);
let pic = date_picture(instr).unwrap_or_else(|| default_picture(&name, lang.as_deref()));
updates.push((k, text_result(instr, crate::cmd::insert::format_date_in(&pic, lang.as_deref()))));
let created = s.doc.core.created.trim();
// CREATEDATE shows when the document was created (ECMA-376 §17.16.5.11). A new
// document, never saved, has no creation date yet and saving stamps now. A
// file opened without one, or with one that can't be read, keeps the result
// it has.
let text = if name != "CREATEDATE" || (created.is_empty() && s.path.is_none()) {
crate::cmd::insert::format_date_in(&pic, lang.as_deref())
} else if let Some((unix, offset)) = created_at(created) {
crate::cmd::insert::format_date_at_in(&pic, lang.as_deref(), unix, offset)
} else {
continue;
};
updates.push((k, text_result(instr, text)));
}
"REF" | "PAGEREF" => {
let f = FieldCode::parse(instr);
@@ -572,6 +584,24 @@ fn field_lang(doc: &wordcraft_doc::Document, p: &wordcraft_doc::Paragraph, k: us
doc.styles.resolve_char(p.props.style.as_deref(), p.props_of_char(off)).lang
}
/// A core-properties creation date as seconds since the epoch and the UTC offset to show it at:
/// an instant (`2019-05-05T12:00:00Z`, any offset or fraction, or without the seconds,
/// `2019-05-05T12:00Z`, as W3CDTF allows) at the local offset, or a calendar date (`2019-05-05`)
/// at its own midnight, whatever the time zone. `None` for another form or a date before 1970.
fn created_at(stamp: &str) -> Option<(u64, i64)> {
let instant = chrono::DateTime::parse_from_rfc3339(stamp).ok().or_else(|| {
// `%:z` takes `+01:00` but not `Z`.
let utc = stamp.strip_suffix(['Z', 'z']).map(|t| format!("{t}+00:00"));
chrono::DateTime::parse_from_str(utc.as_deref().unwrap_or(stamp), "%Y-%m-%dT%H:%M%:z").ok()
});
if let Some(t) = instant {
let unix = u64::try_from(t.timestamp()).ok()?;
return Some((unix, crate::cmd::local_offset_secs(unix)));
}
let day = chrono::NaiveDate::parse_from_str(stamp, "%Y-%m-%d").ok()?;
Some((u64::try_from(day.and_hms_opt(0, 0, 0)?.and_utc().timestamp()).ok()?, 0))
}
/// Word's default date or time picture when a field instruction carries no `\@` picture switch.
fn default_picture(name: &str, lang: Option<&str>) -> String {
if name == "TIME" { "h:mm am/pm".into() } else { crate::cmd::insert::default_date_picture(lang).into() }
+50
View File
@@ -506,6 +506,56 @@ fn update_fields_all_covers_every_story() {
s.run("references.updateFields", &json!({"all": "yes"})).unwrap();
}
/// CREATEDATE shows when the document was created (ECMA-376 §17.16.5.11), not today's date.
#[test]
fn createdate_keeps_the_creation_date_on_update() {
let mut s = Session::new(wordcraft_doc::Document::new());
s.doc.core.created = "2019-05-05T12:00:00Z".into();
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#, "result": "2019-05"})).unwrap();
s.run("insert.field", &json!({"instr": "CREATEDATE"})).unwrap();
s.run("references.updateFields", &json!({})).unwrap();
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
// 12:00 UTC is 5 May from UTC-12 to UTC+11:59, the next day east of that.
let unix = 1_557_057_600;
let (_, _, day, _, _) = crate::cmd::local_civil(unix, crate::cmd::local_offset_secs(unix));
assert_eq!(results, ["2019-05".to_string(), format!("5/{day}/2019")]);
assert!(day == 5 || day == 6, "{day}");
// W3CDTF may leave out the seconds; that is the same instant.
for minutes in ["2019-05-05T12:00Z", "2019-05-05T14:00+02:00", "2019-05-05T07:00-05:00"] {
// From another date first, so an unread stamp, which keeps the result, shows.
s.doc.core.created = "2001-02-03".into();
s.run("references.updateFields", &json!({})).unwrap();
assert_eq!(fields(&s)[1].1, "2/3/2001");
s.doc.core.created = minutes.into();
s.run("references.updateFields", &json!({})).unwrap();
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
assert_eq!(results, ["2019-05".to_string(), format!("5/{day}/2019")], "{minutes}");
}
// A date without a time is that calendar day in every time zone.
s.doc.core.created = "2019-06-07".into();
s.run("references.updateFields", &json!({})).unwrap();
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
assert_eq!(results, ["2019-06", "6/7/2019"]);
}
/// A creation date that can't be read leaves the field's result as it was; a document that has
/// never been saved is created now (saving stamps that time as its creation date).
#[test]
fn createdate_without_a_readable_creation_date() {
let mut s = Session::new(wordcraft_doc::Document::new());
s.doc.core.created = "sometime in May".into();
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#, "result": "2019-05"})).unwrap();
assert_eq!(fields(&s)[0].1, "2019-05");
// A file opened without a creation date keeps the result too.
s.doc.core.created.clear();
s.path = Some(std::env::temp_dir().join("opened.docx"));
s.run("references.updateFields", &json!({})).unwrap();
assert_eq!(fields(&s)[0].1, "2019-05");
s.path = None;
s.run("references.updateFields", &json!({})).unwrap();
assert_eq!(fields(&s)[0].1, crate::cmd::insert::format_date("yyyy-MM"));
}
#[test]
fn toc_tabs_ignore_nonentries() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Before\nContents\nOld\t9\nAfter"));
+23
View File
@@ -337,6 +337,29 @@ mod tests {
let _ = std::fs::remove_dir_all(&d);
}
/// A document made from a template is created now, not when the template was: it has no
/// creation date until it is saved, so CREATEDATE in it shows today.
#[test]
fn new_from_template_has_no_creation_date_of_its_own_yet() {
let d = scratch("created");
let path = d.join("Dated.dotx");
let mut t = Session::new(wordcraft_doc::Document::new());
t.run("document.setText", &json!({"text": "Dated"})).unwrap();
t.doc.core.created = "2019-05-05T12:00:00Z".into();
crate::io::save_path(&path, &t.doc).unwrap();
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("file.newFromTemplate", &json!({"path": path.to_string_lossy()})).unwrap();
assert_eq!(s.doc.core.created, "");
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy""#, "result": "2019"})).unwrap();
s.run("references.updateFields", &json!({})).unwrap();
assert!(s.doc.plain_text(wordcraft_doc::StoryRef::Body).contains(&crate::cmd::insert::format_date("yyyy")));
// The template itself keeps its date.
let mut again = Session::new(wordcraft_doc::Document::new());
again.run("file.open", &json!({"path": path.to_string_lossy()})).unwrap();
assert_eq!(again.doc.core.created, "2019-05-05T12:00:00Z");
let _ = std::fs::remove_dir_all(&d);
}
/// #3433: a template the platform hands the app takes an untouched blank document's place
/// (`replaceBlank`), as a file `file.open` opens does; otherwise, and without the flag, the
/// new document opens beside the others, as File › New's does. Either way the template on
+1 -33
View File
@@ -80,12 +80,8 @@ impl Session {
};
let l = Arc::new(wordcraft_layout::layout(&self.doc, &mut self.cache, &opts));
let [newest, _] = std::mem::take(&mut self.layout);
// Only preserve the alternate layout slot for the current document revision (e.g. Print vs
// Web/Draft toggling); a superseded revision can never hit `fits()` again and would keep an
// obsolete DocLayout live in memory.
let prev = newest.filter(|e| e.0 == rev);
self.layout =
[Some((rev, width, height, mode, spacing, l.clone(), self.view.proofing, outline, deleted, self.view.numeral, typing, shown)), prev];
[Some((rev, width, height, mode, spacing, l.clone(), self.view.proofing, outline, deleted, self.view.numeral, typing, shown)), newest];
l
}
@@ -279,31 +275,3 @@ impl Session {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn layout_drops_stale_revision_slot_but_keeps_same_revision_mode() {
let mut session = Session::new(Document::new());
let first = session.layout();
let first_weak = Arc::downgrade(&first);
drop(first);
// Switching view mode at the same revision keeps the prior layout in `layout[1]`.
session.view.mode = ViewMode::Draft;
let same_rev_other_mode = session.layout();
assert!(first_weak.upgrade().is_some(), "same-revision alternate view mode stays cached");
let draft_weak = Arc::downgrade(&same_rev_other_mode);
drop(same_rev_other_mode);
// Advancing `rev` makes earlier layouts unreachable: building the new layout must drop them.
session.run("text.insert", &serde_json::json!({"text": "hello"})).expect("insert");
let after_edit = session.layout();
assert!(draft_weak.upgrade().is_none(), "superseded revision layout must be dropped");
assert!(first_weak.upgrade().is_none(), "older revision layout must not remain live");
drop(after_edit);
}
}
-97
View File
@@ -9734,77 +9734,6 @@ 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.
@@ -15415,32 +15344,6 @@ 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"))]
+1 -10
View File
@@ -3416,22 +3416,13 @@ 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", "crh"] {
for tag in ["tr-TR", "az-AZ"] {
for (mode, input, want) in [
("upper", "istanbul", "İSTANBUL"),
("lower", "IŞIK", "ışık"),
+2 -8
View File
@@ -521,18 +521,12 @@ fn fill_headers_footers(
None
}
/// Evict paragraph layouts that weren't used this pass if the cache accumulated too many stale entries.
/// Evict paragraph layouts that weren't used this pass if the cache grew large.
fn evict_unused(cache: &mut LayoutCache) {
if cache.paras.len() + cache.measures.len() > cache.used.len() + cache.used.len().clamp(512, 1024) {
if cache.paras.len() + cache.measures.len() > 4 * cache.used.len().max(1024) {
let used = std::mem::take(&mut cache.used);
cache.paras.retain(|k, _| used.contains(k));
cache.measures.retain(|k, _| used.contains(k));
if cache.paras.capacity() > cache.paras.len().max(512) * 4 {
cache.paras.shrink_to(cache.paras.len() * 2);
}
if cache.measures.capacity() > cache.measures.len().max(256) * 4 {
cache.measures.shrink_to(cache.measures.len() * 2);
}
cache.used = used;
}
}
-16
View File
@@ -18287,19 +18287,3 @@ fn many_list_definitions_keep_the_list_numbering_in_order() {
assert_eq!(labels.first().copied(), Some("1."));
assert_eq!(labels.last().copied(), Some("512."));
}
#[test]
fn evict_unused_caps_stale_entries_across_repeated_edits() {
crate::test_fonts();
let mut d = Document::from_text(&"line\n".repeat(599));
let mut c = LayoutCache::new();
layout(&d, &mut c, &LayoutOptions::default());
let base = c.len();
for pass in 0..80 {
for para_idx in 0..25 {
d.insert_text(&Pos::body(para_idx, 0), if pass % 2 == 0 { "a" } else { "b" }, &Default::default()).unwrap();
}
layout(&d, &mut c, &LayoutOptions::default());
assert!(c.len() <= base + 1025, "stale cache entries must be bounded (got {}, base {base})", c.len());
}
}
+29 -195
View File
@@ -6,74 +6,16 @@
//! Renders now [`take`](ContextPool::take) the kept context, reset to their size, and
//! [`give_back`](ContextPool::give_back) it when done.
use std::ops::{Deref, DerefMut};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Mutex, PoisonError};
use vello_cpu::{RenderContext, RenderSettings};
const MAX_SPARES: usize = 2;
/// Pixel area above a 100%-zoom page even at 2x HiDPI (~2000x2000). Contexts expanded past this
/// (e.g. 200% zoom) are dropped once renders return to normal size so large buffers aren't pinned.
const OVERSIZED_PIXELS: u64 = 4_000_000;
const OVERSIZED_SHRINK_STREAK: u32 = 4;
#[derive(Default)]
struct State {
primary: Option<RenderContext>,
primary_out: bool,
primary_peak_pixels: u64,
primary_small_streak: u32,
spares: Vec<(RenderContext, u64)>,
/// How many contexts (both primary and single-threaded spares) were built.
built: usize,
}
/// Checked-out context from [`ContextPool`]. Dropping without [`ContextPool::give_back`] (e.g.
/// on panic) discards the half-drawn context while still releasing the primary checkout slot.
pub(crate) struct PooledContext<'a> {
pool: &'a ContextPool,
ctx: Option<RenderContext>,
is_primary: bool,
pixels: u64,
}
impl Deref for PooledContext<'_> {
type Target = RenderContext;
fn deref(&self) -> &Self::Target {
#[allow(clippy::expect_used)]
self.ctx.as_ref().expect("PooledContext accessed after give_back")
}
}
impl DerefMut for PooledContext<'_> {
fn deref_mut(&mut self) -> &mut Self::Target {
#[allow(clippy::expect_used)]
self.ctx.as_mut().expect("PooledContext accessed after give_back")
}
}
impl Drop for PooledContext<'_> {
fn drop(&mut self) {
if let Some(ctx) = self.ctx.take() {
if self.is_primary {
let mut state = self.pool.state.lock().unwrap_or_else(PoisonError::into_inner);
state.primary_out = false;
state.primary_peak_pixels = 0;
state.primary_small_streak = 0;
}
drop(ctx);
}
}
}
/// Render contexts kept between renders.
///
/// Keeps one multi-threaded primary context plus a bounded set of single-threaded spares for
/// concurrent background page renders, avoiding spawning/tearing down extra rayon thread pools and
/// retaining zoom-expanded buffers indefinitely.
/// A render context kept between renders.
pub(crate) struct ContextPool {
state: Mutex<State>,
slot: Mutex<Option<RenderContext>>,
/// How many contexts (so thread pools) were built: one, unless renders overlap.
built: AtomicUsize,
}
/// The context page, area and icon renders share.
@@ -81,96 +23,39 @@ pub(crate) static CONTEXTS: ContextPool = ContextPool::new();
impl ContextPool {
pub(crate) const fn new() -> Self {
ContextPool {
state: Mutex::new(State {
primary: None,
primary_out: false,
primary_peak_pixels: 0,
primary_small_streak: 0,
spares: Vec::new(),
built: 0,
}),
ContextPool { slot: Mutex::new(None), built: AtomicUsize::new(0) }
}
/// A context reset to `w`×`h`: the kept one, or a new one with [`crate::default_threads`]
/// workers while another render has it (another thread, or a render inside a render).
pub(crate) fn take(&self, w: u16, h: u16) -> RenderContext {
let kept = self.slot.lock().unwrap_or_else(PoisonError::into_inner).take();
match kept {
Some(mut ctx) => {
ctx.reset_and_resize(w, h);
ctx
}
None => {
self.built.fetch_add(1, Ordering::Relaxed);
RenderContext::new_with(w, h, RenderSettings { num_threads: crate::default_threads(), ..Default::default() })
}
}
}
/// A context reset to `w`×`h`: the kept multi-threaded primary context, a kept single-threaded
/// spare when renders overlap, or a newly built context when none is idle.
pub(crate) fn take(&self, w: u16, h: u16) -> PooledContext<'_> {
let pixels = u64::from(w) * u64::from(h);
let multi_threads = crate::default_threads();
enum Checkout {
PrimaryExisting(RenderContext),
PrimaryNew,
SpareExisting(RenderContext, u64),
SpareNew,
/// Keep `ctx` for the next [`take`](Self::take), unless one is kept already (then `ctx` and
/// its threads go). A render that panics never gets here, so a half-drawn context is dropped
/// rather than reused.
pub(crate) fn give_back(&self, ctx: RenderContext) {
let mut slot = self.slot.lock().unwrap_or_else(PoisonError::into_inner);
if slot.is_none() {
*slot = Some(ctx);
}
let action = {
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
if multi_threads > 0 && !state.primary_out {
state.primary_out = true;
state.primary_peak_pixels = state.primary_peak_pixels.max(pixels);
state.primary_small_streak = if pixels <= OVERSIZED_PIXELS { state.primary_small_streak.saturating_add(1) } else { 0 };
match state.primary.take() {
Some(ctx) => Checkout::PrimaryExisting(ctx),
None => {
state.built += 1;
Checkout::PrimaryNew
}
}
} else if let Some((ctx, peak)) = state.spares.pop() {
Checkout::SpareExisting(ctx, peak)
} else {
state.built += 1;
Checkout::SpareNew
}
};
let (mut ctx, is_primary, tracked_pixels, reset) = match action {
Checkout::PrimaryExisting(ctx) => (ctx, true, pixels, true),
Checkout::PrimaryNew => {
(RenderContext::new_with(w, h, RenderSettings { num_threads: multi_threads, ..Default::default() }), true, pixels, false)
}
Checkout::SpareExisting(ctx, peak) => (ctx, false, peak.max(pixels), true),
Checkout::SpareNew => (RenderContext::new_with(w, h, RenderSettings { num_threads: 0, ..Default::default() }), false, pixels, false),
};
if reset {
ctx.reset_and_resize(w, h);
}
PooledContext { pool: self, ctx: Some(ctx), is_primary, pixels: tracked_pixels }
}
/// Keep `ctx` for the next [`take`](Self::take), dropping oversized contexts once renders return
/// to normal size or when the spare pool is full. A render that panics never gets here, so a
/// half-drawn context is dropped rather than reused.
pub(crate) fn give_back(&self, mut guard: PooledContext<'_>) {
let Some(ctx) = guard.ctx.take() else { return };
let drop_it = {
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
if guard.is_primary {
state.primary_out = false;
if state.primary.is_some() {
Some(ctx)
} else if state.primary_peak_pixels > OVERSIZED_PIXELS && state.primary_small_streak >= OVERSIZED_SHRINK_STREAK {
state.primary_peak_pixels = 0;
state.primary_small_streak = 0;
Some(ctx)
} else {
state.primary = Some(ctx);
None
}
} else if guard.pixels <= OVERSIZED_PIXELS && state.spares.len() < MAX_SPARES {
state.spares.push((ctx, guard.pixels));
None
} else {
Some(ctx)
}
};
drop(drop_it);
}
/// How many contexts this pool has built.
#[cfg(test)]
fn built(&self) -> usize {
self.state.lock().unwrap_or_else(PoisonError::into_inner).built
self.built.load(Ordering::Relaxed)
}
}
@@ -385,55 +270,4 @@ mod tests {
// down here; that it built any shows page renders go through it.
assert!(CONTEXTS.built() >= 1, "page and icon renders take the shared context");
}
#[test]
fn concurrent_spares_are_reused_without_spawning_more_contexts() {
let pool = ContextPool::new();
for _ in 0..4 {
let a = pool.take(240, 160);
let b = pool.take(240, 160);
pool.give_back(a);
pool.give_back(b);
}
assert_eq!(pool.built(), 2, "primary + spare should be reused across overlapping rounds");
}
#[test]
fn oversized_contexts_are_dropped_after_returning_to_small_renders() {
let pool = ContextPool::new();
let big_p = pool.take(2500, 2500);
let big_s = pool.take(2500, 2500);
pool.give_back(big_p);
pool.give_back(big_s);
assert_eq!(pool.built(), 2);
for _ in 0..OVERSIZED_SHRINK_STREAK {
pooled(&pool, 400, 400);
}
// Oversized primary dropped at streak == OVERSIZED_SHRINK_STREAK; next take rebuilds a fresh one.
pooled(&pool, 400, 400);
assert_eq!(pool.built(), 3, "oversized primary should be replaced once back at normal sizes");
}
#[test]
fn spare_pool_caps_retained_contexts_at_max_spares() {
let pool = ContextPool::new();
let retained = MAX_SPARES + usize::from(crate::default_threads() > 0);
let total = retained + 1;
let held: Vec<_> = (0..total).map(|_| pool.take(240, 160)).collect();
assert_eq!(pool.built(), total);
for ctx in held {
pool.give_back(ctx);
}
// Primary (when default_threads() > 0) + MAX_SPARES spares are retained; checking that many out builds nothing new.
let reused: Vec<_> = (0..retained).map(|_| pool.take(240, 160)).collect();
assert_eq!(pool.built(), total, "retained contexts should be reused");
let extra = pool.take(240, 160);
assert_eq!(pool.built(), total + 1, "excess spare beyond MAX_SPARES should have been dropped");
pool.give_back(extra);
for ctx in reused {
pool.give_back(ctx);
}
}
}
+1 -2
View File
@@ -887,9 +887,8 @@ 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 && r != &resolved);
self.ui.recent.retain(|r| r != path);
if self.ui.recent.len() == before {
return Some(Err(format!("`{path}` is not on the recent list")));
}
-3
View File
@@ -23,7 +23,6 @@ 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
}
@@ -36,8 +35,6 @@ 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 };
+1 -17
View File
@@ -143,8 +143,6 @@ pub struct CanvasState {
pub(crate) turning: Option<crate::objects::Turning>,
/// Page content fingerprints of the current layout, for the page revision.
pub(crate) page_keys: PageKeys,
/// Cached `(body.y, body.bottom)` pairs for `PageView::bodies`, keyed by the `DocLayout` instance.
pub(crate) page_bodies: Option<(std::sync::Weak<DocLayout>, std::rc::Rc<Vec<(f64, f64)>>)>,
/// The caret colour last worked out and the key of the place it was worked out for, so a blink doesn't rebuild the
/// page's draw list every frame (`cursor::caret_color_at`).
pub(crate) caret_bg: Option<(u64, Color32)>,
@@ -264,19 +262,6 @@ pub struct CanvasState {
type TablePreviewKey = ((String, serde_json::Value, u64, u64, wordcraft_engine::Selection), Arc<DocLayout>);
impl CanvasState {
/// Returns cached `(body.y, body.bottom)` pairs for `layout`, rebuilding only when the layout changes.
pub(crate) fn cached_page_bodies(&mut self, layout: &Arc<DocLayout>) -> std::rc::Rc<Vec<(f64, f64)>> {
if let Some((weak, bodies)) = &self.page_bodies
&& weak.upgrade().is_some_and(|prev| Arc::ptr_eq(&prev, layout))
{
return std::rc::Rc::clone(bodies);
}
let bodies: std::rc::Rc<Vec<(f64, f64)>> =
std::rc::Rc::new(layout.pages.iter().map(|p| (f64::from(p.body.y), f64::from(p.body.bottom()))).collect());
self.page_bodies = Some((Arc::downgrade(layout), std::rc::Rc::clone(&bodies)));
bodies
}
/// Another document is shown in the window: everything about the page that was shown (drags,
/// menus, the input method's composition, a scroll in progress…) starts afresh. What belongs
/// to the window or the user stays: the colours last applied, the ruler's tab kind and the
@@ -420,7 +405,6 @@ impl Default for CanvasState {
frame_held: false,
turning: None,
page_keys: PageKeys::default(),
page_bodies: None,
caret_bg: None,
markup_facts: Cell::new(None),
scroll_to_caret: true,
@@ -814,7 +798,7 @@ fn show_pages(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: Rec
let hidden = crate::objects::dragged_off_page(app.canvas.object_gesture.as_ref());
let selected = selection_page_rects(app, layout);
let areas = mark_areas(app, layout, &selected);
let bodies = app.canvas.cached_page_bodies(layout);
let bodies: Vec<(f64, f64)> = layout.pages.iter().map(|p| (f64::from(p.body.y), f64::from(p.body.bottom()))).collect();
let show_rulers = app.session.view.ruler
&& app.session.view.mode == wordcraft_layout::ViewMode::Print
&& crate::chrome::Screen::of(&app.session.view) == crate::chrome::Screen::Normal;
-17
View File
@@ -36,23 +36,6 @@ fn the_page_shows_the_table_the_grid_previews() {
assert_eq!(cells(&shown_layout(&mut app)), 0, "no request: the document's own page");
}
#[test]
fn cached_page_bodies_reuses_buffer_for_same_layout_and_rebuilds_on_change() {
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("Lanterns")), crate::Services::default());
let layout_a = app.session.layout();
let first = app.canvas.cached_page_bodies(&layout_a);
let second = app.canvas.cached_page_bodies(&layout_a);
assert!(std::rc::Rc::ptr_eq(&first, &second), "same DocLayout reuses cached bodies Rc");
assert_eq!(first.len(), layout_a.pages.len());
app.run("insert.header", json!({"text": "Header marker."})).unwrap();
let layout_b = app.session.layout();
assert!(!Arc::ptr_eq(&layout_a, &layout_b));
let third = app.canvas.cached_page_bodies(&layout_b);
assert!(!std::rc::Rc::ptr_eq(&first, &third), "new DocLayout rebuilds cached bodies");
assert_eq!(third.len(), layout_b.pages.len());
}
/// #3931 review: the preview's pages are drawn from the copy they were laid out from. The
/// table moves "Kites" down a block, so the document's own block there is not its paragraph.
#[test]
+5 -6
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, EditPolicy, Preview};
use craft::behavior::{EditEvent, Preview};
use craft::keymap::CommandRef;
use craft::pages::ui::PageBody;
use craft::ui::buttons::{Button, ControlPlace, GroupLevel, ToggleButton};
@@ -198,14 +198,13 @@ 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();
// `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);
let combo = ComboBox::new(tl!("Font Size").to_string(), Bind::bound(&mut text), &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, and leaving the box
// without either drops it.
let committed = combo.edit.submitted || combo.edit.events.iter().any(|e| matches!(e, EditEvent::Set { .. }));
// 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 { .. }));
if committed
&& text != size
&& let Ok(x) = text.trim().parse::<f64>()
-22
View File
@@ -980,25 +980,3 @@ 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");
}
}
+1 -3
View File
@@ -347,9 +347,7 @@ impl PreferencesModel for OptionsModel<'_> {
tl!("Tell me when a document's missing fonts can be downloaded"),
app.ui.font_download_notice,
),
RowSpec::new("general.defaultApp", "", RowKind::CustomRows)
.keywords(tl!("Make WordCraft the default for Word documents…"))
.visible(can_default),
custom("general.defaultApp", tl!("Make WordCraft the default for Word documents…")).visible(can_default),
],
),
GroupSpec::new(
-102
View File
@@ -461,105 +461,3 @@ 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,55 +219,3 @@ 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()]);
}
}
+4 -1
View File
@@ -2237,8 +2237,11 @@ fn the_default_app_button_shows_only_with_the_hosts_hook() {
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_eframe(|_| a);
h.run_steps(4);
assert!(h.query_by_label("Show the community button in the title bar").is_some(), "hook {hook}: the Options page rendered");
assert_eq!(h.query_all_by_label_contains(LABEL).count(), hook as usize, "hook {hook}: one caption on the button");
// The row carries the label too (macOS shows it, with Finder's steps instead of a button): ask for the button.
let button = h.query_all_by_role_and_label(egui::accesskit::Role::Button, LABEL).next().is_some();
assert_eq!(button, hook, "hook {hook}: the button");
if hook {
// The button itself, not the row that carries its label.
h.get_by_role_and_label(egui::accesskit::Role::Button, LABEL).click();
h.run_steps(2);
assert_eq!(calls.get(), 1, "the button ran the hook");
File diff suppressed because one or more lines are too long
+2 -3
View File
@@ -73,9 +73,8 @@ 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.
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`
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`
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