Compare commits

..
Author SHA1 Message Date
autocraft-bot[bot] c0ec0d83e1 Merge main (2f168645) into the pull request
The only conflict was the long "Last reviewed / Change" line in docs/lay

The only conflict was the long "Last reviewed / Change" line in docs/layout-parity.md. Both sides had put a new entry at the front of the change history, and the rest of the line was identical. I kept both entries. The pull request's entry (a section with a different first page that starts continuously) comes first, then main's hidden-mark entry (#3986) as "previously trivial", then the unchanged older history. No conflict markers are left in the repository. I did not build or run tests, because only documentation changed and the dependency fetch had failed.
2026-12-02 21:11:59 +00:00
Mauro MazzieriandClaude Opus 5.5 989fa17544 Merge main into claude/continuous-section-first-page-header (#5543)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-21 18:52:40 +01:00
Mauro MazzieriandClaude Opus 5.5 6eb03bf4ea Merge storytold/wordcraft main
Resolves the docs/layout-parity.md status line and revision history.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JesQG7ckr7g2qSfBwGkTqM
2026-11-17 15:50:22 +00:00
Mauro MazzieriandClaude Opus 5.5 892235af06 Different first page: a continuous section whose first paragraph runs over still began on the page before
Addresses the CodeRabbit review: the run-over case (with a regression test) and the even-page header in docs/layout-parity.md.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JesQG7ckr7g2qSfBwGkTqM
2026-11-11 16:53:42 +00:00
Mauro MazzieriandClaude Opus 5.5 e14f85661b Merge storytold/wordcraft main
Resolves the docs/layout-parity.md status line and revision history.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JesQG7ckr7g2qSfBwGkTqM
2026-11-11 16:44:02 +00:00
Mauro Mazzieri d3096ed0fb Merge remote-tracking branch 'origin/main' into claude/continuous-section-first-page-header
# Conflicts:
#	crates/layout/src/table_flow.rs
#	docs/layout-parity.md
2026-11-09 15:48:45 +01:00
Mauro MazzieriandClaude Opus 5.5 dc515b6128 Different first page: no first-page header on a continuous section's second page
A page is its section's first page, the one a different first page's header and footer go on,
only if the section begins on it. A page's section is the one at its top, so a section that
starts continuously part-way down a page was taken to begin on the next page, which then showed
the section's first-page header. Word shows the earlier section's header on the page where the
section starts and the section's default header from the next page on: the first-page header of
such a section is never seen (checked in Word for Windows 365 on a synthetic file).

begins_section compares the section's first block with the page's first block, and serves the
drawn headers and footers, header-table obstacles and footer-table wraps alike.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 10:36:33 +01:00
16 changed files with 120 additions and 384 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)
-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"),
+26 -9
View File
@@ -36,6 +36,27 @@ pub(crate) fn section_side(start: SectionStart, restart: Option<u32>, last: u32,
}
}
/// Whether `page` (after `prev`) is its section's first page, the one a different first page's
/// header and footer go on: the page where the section begins. A page's section is the one at its
/// top, so a section that starts continuously part-way down `prev` has no first page of its own:
/// Word shows the earlier section's header there and the section's default one from the next page
/// on, also when its first paragraph begins on `prev` and runs over. `sections` as
/// [`Document::sections`] gives them (each with its last block).
pub(crate) fn begins_section(sections: &[(usize, &SectionProps)], prev: Option<&Page>, page: &Page) -> bool {
if prev.is_some_and(|p| p.section == page.section) {
return false;
}
let start = page.section.checked_sub(1).and_then(|k| sections.get(k)).map_or(0, |(end, _)| end.saturating_add(1));
// A first paragraph (or table) that begins part-way down `prev` and runs over still began
// the section there.
let began_before = prev.is_some_and(|p| {
p.items
.iter()
.any(|it| matches!(it, Placed::Lines { story: StoryRef::Body, path, .. } if path.0.first().is_some_and(|&b| b as usize >= start)))
});
start >= page.first_block && !began_before
}
/// The document's sections with their headers and footers (Word's "link to previous"), each
/// section's resolved once for the whole layout in document order rather than by looking back
/// over the sections before it whenever one is needed.
@@ -174,12 +195,12 @@ pub(crate) fn header_table_areas(ctx: &mut Ctx, pb: &PageBuilder) -> Vec<Rect> {
return Vec::new();
}
let Some(page) = pb.pages.last() else { return Vec::new() };
let first = pb.pages.iter().rev().nth(1).is_none_or(|prev| prev.section != page.section);
let hf = Arc::clone(&ctx.hf);
let first = begins_section(&hf.sections, pb.pages.iter().rev().nth(1), page);
let key = (page.section, page.number, first);
if let Some(areas) = ctx.header_tables.get(&key) {
return areas.clone();
}
let hf = Arc::clone(&ctx.hf);
let Some((_, sect)) = hf.sections.get(page.section) else { return Vec::new() };
if sect.text_direction.is_turned() {
return Vec::new();
@@ -405,13 +426,9 @@ pub(crate) fn headers_footers(ctx: &mut Ctx, pages: &mut [Page], sections: &[(us
let hf = Arc::clone(&ctx.hf);
let even_odd = ctx.doc.settings.even_odd_headers;
let styles = styleref::headers_use_styleref(ctx.doc).then(|| ctx.cache.style_index(ctx.doc));
let mut first_of_section: HashSet<usize> = HashSet::new();
let mut seen = HashSet::new();
for (i, p) in pages.iter().enumerate() {
if seen.insert(p.section) {
first_of_section.insert(i);
}
}
let first_of_section: HashSet<usize> = (0..pages.len())
.filter(|&i| pages.get(i).is_some_and(|p| begins_section(sections, i.checked_sub(1).and_then(|k| pages.get(k)), p)))
.collect();
for (i, page) in pages.iter_mut().enumerate() {
let Some((_, sect)) = sections.get(page.section) else { continue };
// Inherit header/footer references from earlier sections (Word's "link to previous").
+3 -3
View File
@@ -2,7 +2,7 @@ use super::boxes::{BoxInput, clear_of_float_tables, layout_box};
use super::ctx::{Ctx, with_pct_base};
use super::floats::{WrapArea, align_in, body_wraps};
use super::flow::again;
use super::headers::{header_items_cap, header_table_areas, placed_cost};
use super::headers::{begins_section, header_items_cap, header_table_areas, placed_cost};
use super::notes::table_notes;
use super::page::{PageBuilder, PageFrame, page_frame};
use super::placed::Placed;
@@ -14,14 +14,14 @@ pub(crate) fn footer_table_wraps(ctx: &mut Ctx, pb: &PageBuilder) -> Vec<WrapAre
return Vec::new();
}
let Some(page) = pb.pages.last() else { return Vec::new() };
let first = pb.pages.iter().rev().nth(1).is_none_or(|prev| prev.section != page.section);
let hf = Arc::clone(&ctx.hf);
let first = begins_section(&hf.sections, pb.pages.iter().rev().nth(1), page);
let key = (page.section, page.number, first);
if let Some(areas) = ctx.footer_wraps.get(&key) {
return areas.clone();
}
ctx.footer_wraps.insert(key, Vec::new());
let doc = ctx.doc;
let hf = Arc::clone(&ctx.hf);
let Some((_, sect)) = hf.sections.get(page.section) else { return Vec::new() };
if sect.text_direction.is_turned() {
return Vec::new();
+77
View File
@@ -17427,6 +17427,83 @@ fn kept_lines_below_a_tall_first_page_header_move_whole_to_page_two() {
assert_eq!((first.page, last.page), (1, 1), "kept paragraph whole on page 2: {first:?} .. {last:?}");
}
/// A section with a different first page that starts continuously part-way down a page has no
/// first page of its own: Word shows the earlier section's header on the page where it starts
/// (the section at the page's top) and the section's default header from the next page on, so
/// its first-page header is never seen. One that starts on a new page shows it there.
#[test]
fn continuous_section_first_page_header_is_not_shown_on_its_second_page() {
use wordcraft_doc::section::SectionStart;
for start in [SectionStart::Continuous, SectionStart::NextPage] {
let text = (0..140).map(|i| format!("Paragraph {i}")).collect::<Vec<_>>().join("\n");
let mut d = Document::from_text(&text);
let part = |d: &mut Document, t: &str| {
d.add_part(wordcraft_doc::PartKind::Header, vec![wordcraft_doc::para_block(Paragraph::with_text(t, Default::default()))])
};
let (one, first, two) = (part(&mut d, "ONE"), part(&mut d, "FIRST"), part(&mut d, "TWO"));
let mut s1 = d.last_section.clone();
s1.headers.default = Some(one);
d.para_mut(StoryRef::Body, &Path::top(19)).unwrap().section = Some(Box::new(s1));
d.last_section.start = start;
d.last_section.title_page = true;
d.last_section.headers.first = Some(first);
d.last_section.headers.default = Some(two);
let l = lay(&d);
let begins = l.caret(&Pos::body(20, 0)).unwrap().page;
let shown: Vec<_> = l.pages.iter().map(|p| p.header_story).collect();
assert!(l.pages.len() > begins + 2, "{start:?}: the second section runs over several pages");
match start {
SectionStart::Continuous => {
assert!(l.caret(&Pos::body(19, 0)).unwrap().page == begins, "the second section starts part-way down a page");
assert_eq!(shown[begins], Some(one), "{start:?}: the page where it starts keeps the first section's header");
assert!(
shown[begins + 1..].iter().all(|h| *h == Some(two)),
"{start:?}: then its default header, never its first-page one: {shown:?}"
);
assert!(l.pages[begins + 1..].iter().all(|p| p.hf_slot == crate::HfSlot::Default), "{start:?}");
}
_ => {
assert_eq!(shown[begins], Some(first), "{start:?}: a section on a new page shows its first-page header there");
assert_eq!(l.pages[begins].hf_slot, crate::HfSlot::First);
assert!(shown[begins + 1..].iter().all(|h| *h == Some(two)), "{start:?}: {shown:?}");
}
}
}
}
/// The same when the continuous section's first paragraph begins part-way down a page and runs
/// over onto the next: the section began on the page before, so the next shows its default
/// header, not its first-page one.
#[test]
fn continuous_section_first_paragraph_running_over_keeps_first_page_header_hidden() {
use wordcraft_doc::section::SectionStart;
let mut paras: Vec<String> = (0..44).map(|i| format!("Paragraph {i}")).collect();
// Section 2's first paragraph: long enough to start low on page 1 and run onto page 2.
paras.push("word ".repeat(1200));
paras.extend((0..60).map(|i| format!("After {i}")));
let mut d = Document::from_text(&paras.join("\n"));
let part = |d: &mut Document, t: &str| {
d.add_part(wordcraft_doc::PartKind::Header, vec![wordcraft_doc::para_block(Paragraph::with_text(t, Default::default()))])
};
let (one, first, two) = (part(&mut d, "ONE"), part(&mut d, "FIRST"), part(&mut d, "TWO"));
let mut s1 = d.last_section.clone();
s1.headers.default = Some(one);
d.para_mut(StoryRef::Body, &Path::top(43)).unwrap().section = Some(Box::new(s1));
d.last_section.start = SectionStart::Continuous;
d.last_section.title_page = true;
d.last_section.headers.first = Some(first);
d.last_section.headers.default = Some(two);
let l = lay(&d);
let begins = l.caret(&Pos::body(44, 0)).unwrap().page;
assert_eq!(l.caret(&Pos::body(43, 0)).unwrap().page, begins, "the second section starts part-way down a page");
let next = begins + 1;
assert!(l.pages.get(next).is_some_and(|p| p.first_block == 44), "its first paragraph runs over onto the next page");
let shown: Vec<_> = l.pages.iter().map(|p| p.header_story).collect();
assert_eq!(shown[begins], Some(one));
assert!(shown[next..].iter().all(|h| *h == Some(two)), "{shown:?}");
assert!(l.pages[next..].iter().all(|p| p.hf_slot == crate::HfSlot::Default));
}
/// Sections starting continuously one after another still go onto new pages: a paragraph that
/// doesn't fit below the text above it moves on rather than running off the page (#3907). A
/// hundred one-line sections lay out like a hundred plain paragraphs.
+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 };
+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");
}
}
-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()]);
}
}
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