Compare commits

..
Author SHA1 Message Date
autocraft-bot[bot] dcd16d463d Merge main (72e54545) into the pull request
The only conflict was in the 'Last reviewed / Change' line of docs/layou

The only conflict was in the 'Last reviewed / Change' line of docs/layout-parity.md. I kept main's new entry (hidden-mark paragraph, #3986) and put the pull request's footnote entry in front of it as the newest 'trivial' change. The older entry now reads 'previously trivial'. No conflict markers remain. I did not build or run tests, since only a doc file changed.
2026-12-02 20:35:36 +00:00
Kevin Joseph 8654ed1319 Merge remote-tracking branch 'origin/main' into fix/footnote-continued-bottom
# Conflicts:
#	docs/layout-parity.md
2026-11-24 09:46:34 +01:00
Kevin Joseph 4afcb2812f docs: widow/orphan control in a split footnote, and the page's first note that gives it up 2026-11-18 15:58:28 +01:00
Kevin Joseph 834c8054cf Footnotes: the beneath-text test asserts the separator's gap; docs say the bottom margin is for page-bottom notes 2026-11-18 15:48:40 +01:00
Kevin Joseph 540bd57931 Layout: a page of continued notes is aligned once, before its notes go on it
A centred or bottom-aligned section whose last note continued over pages of notes alone moved
each such page down again when the next one started, its notes past the bottom margin.
finish_pages now finishes every page through finish_page, which aligns it and then leaves it
top-aligned. Tests: the bottom-margin test also runs with widow control and checks every note
line is placed once; a note beneath the text stays under it when it continues.
2026-11-18 14:22:41 +01:00
Kevin Joseph 11790205d1 Merge remote-tracking branch 'origin/main' into fix/footnote-continued-bottom
# Conflicts:
#	docs/layout-parity.md
2026-11-18 14:04:31 +01:00
Kevin Joseph 6997afcc34 Word for Mac 16.114.4 is the version these were measured in, not 16.113.4
The commit messages before this one name 16.113.4 too; the measurements were made in the Word
for Mac installed here, which reports 16.114.4.
2026-11-09 16:11:28 +01:00
Kevin Joseph 0074cb6ac6 Layout: orphan control in a footnote split across pages
Rather than leave a note paragraph's first line alone at the bottom of a page, Word for Mac
16.113.4 moves the line holding the reference on to the next page with it. WordCraft kept the
line and one note line on the page. The least of a note that stays with its reference is now
two lines of a paragraph with widow/orphan control (or the paragraph whole); the page's first
note still splits where it must rather than overrun the page.

Found by the word-compare footnotes probe, which now matches Word line for line (it differed
by up to 37.6 pt on page 1, one body line on the wrong page). The 30 footnote-split probes
still match.

Test: orphan_control_keeps_two_lines_of_a_split_footnote_with_its_reference, failing without
the change.
2026-11-09 13:49:31 +01:00
Kevin Joseph 3c44fc6443 Layout: a continued footnote ends on the bottom margin; widow control in it
When a footnote continues on the next page, Word for Mac 16.113.4 keeps the note area's last
line on the page's bottom margin and leaves the room above the separator; WordCraft placed the
notes right under the text. With widow control in the note's paragraph, Word takes one more line
along rather than leave its last line alone on the next page; WordCraft left it alone.

Measured with cargo xtask word-compare: a long footnote whose reference moves down the page one
body line at a time (Georgia 11, notes 9, widow control on and off), 30 documents; all 30 now
match Word's PDFs line for line (9 differed in the note area's position, 1 in its line breaks).

Tests: a_footnote_continuing_on_the_next_page_ends_on_the_bottom_margin and
widow_control_leaves_two_lines_of_a_split_footnote_on_the_next_page, each failing without its
half of the fix.
2026-11-09 13:30:03 +01:00
32 changed files with 297 additions and 1325 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");
+9 -37
View File
@@ -21,32 +21,26 @@ pub fn use_settings_dir(dir: PathBuf) -> Result<(), String> {
/// an environment variable a child or a wrapper might have inherited. `WORDCRAFT_PROFILE_DIR`
/// overrides the entire folder for isolated runs otherwise.
pub fn settings_dir() -> Option<PathBuf> {
settings_dir_with(CHOSEN.get(), |k| std::env::var_os(k))
}
fn settings_dir_with(chosen: Option<&PathBuf>, mut env: impl FnMut(&str) -> Option<std::ffi::OsString>) -> Option<PathBuf> {
if let Some(path) = chosen {
if let Some(path) = CHOSEN.get() {
return Some(path.clone());
}
if let Some(path) = env("WORDCRAFT_PROFILE_DIR").filter(|p| !p.is_empty()) {
if let Some(path) = std::env::var_os("WORDCRAFT_PROFILE_DIR").filter(|p| !p.is_empty()) {
return Some(PathBuf::from(path));
}
platform_settings_dir_for(env)
platform_settings_dir()
}
/// The platform's own folder, when nothing chose one (see [`settings_dir`]).
#[cfg(test)]
fn platform_settings_dir() -> Option<PathBuf> {
platform_settings_dir_for(|k| std::env::var_os(k))
}
fn platform_settings_dir_for(mut env: impl FnMut(&str) -> Option<std::ffi::OsString>) -> Option<PathBuf> {
if cfg!(target_os = "macos") {
env("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/WordCraft"))
std::env::var_os("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/WordCraft"))
} else if cfg!(windows) {
env("APPDATA").map(|a| PathBuf::from(a).join("WordCraft"))
std::env::var_os("APPDATA").map(|a| PathBuf::from(a).join("WordCraft"))
} else {
env("XDG_CONFIG_HOME").map(PathBuf::from).or_else(|| env("HOME").map(|h| PathBuf::from(h).join(".config"))).map(|c| c.join("wordcraft"))
std::env::var_os("XDG_CONFIG_HOME")
.map(PathBuf::from)
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))
.map(|c| c.join("wordcraft"))
}
}
@@ -115,26 +109,4 @@ mod tests {
assert_eq!(key_path(dir, 7981), dir.join("control-key.local-7981"));
}
}
#[test]
fn settings_dir_is_the_apps_folder() {
let default_dir = settings_dir_with(None, |key| match key {
"HOME" | "APPDATA" | "XDG_CONFIG_HOME" => Some("/tmp/base".into()),
_ => None,
})
.expect("settings_dir should return Some when platform env var is set");
let default_name = default_dir.file_name().and_then(|n| n.to_str()).unwrap_or("");
assert!(default_name == "wordcraft" || default_name == "WordCraft", "{}", default_dir.display());
assert_eq!(settings_dir_with(None, |_| None), None);
let override_dir = settings_dir_with(None, |key| (key == "WORDCRAFT_PROFILE_DIR").then(|| "/tmp/profile".into()));
assert_eq!(override_dir.as_deref(), Some(Path::new("/tmp/profile")));
let empty_override = settings_dir_with(None, |key| match key {
"WORDCRAFT_PROFILE_DIR" => Some("".into()),
"HOME" | "APPDATA" | "XDG_CONFIG_HOME" => Some("/tmp/base".into()),
_ => None,
});
assert_eq!(empty_override, Some(default_dir));
}
}
+3 -52
View File
@@ -230,26 +230,10 @@ impl ChartAxis {
pub const MAX_FMT: usize = 128;
/// A number format code: control characters as spaces, ends trimmed, at most [`MAX_FMT`]
/// characters. A trailing space stays when it is part of the code: the character after `_`,
/// `*` or `\`, or text inside quotes.
/// characters.
pub fn clean_fmt(s: &str) -> String {
let chars: Vec<char> = s.chars().take(MAX_FMT * 4).skip_while(|c| c.is_whitespace() || c.is_control()).take(MAX_FMT).collect();
let mut keep = 0;
let mut quoted = false;
let mut operand = false;
for (i, &c) in chars.iter().enumerate() {
if !c.is_control() && (!c.is_whitespace() || operand || quoted) {
keep = i + 1;
}
if operand {
operand = false;
} else if c == '"' {
quoted = !quoted;
} else if !quoted && matches!(c, '_' | '*' | '\\') {
operand = true;
}
}
chars[..keep].iter().map(|&c| if c.is_control() { ' ' } else { c }).collect()
let s: String = s.chars().take(MAX_FMT * 4).map(|c| if c.is_control() { ' ' } else { c }).collect();
s.trim().chars().take(MAX_FMT).collect::<String>().trim_end().to_string()
}
/// A chart WordCraft can edit.
@@ -528,37 +512,4 @@ mod tests {
spec.sanitize();
assert_eq!(spec.series[0].line_w, Some(20.0), "a wild width clamps to 20 pt");
}
#[test]
fn format_keeps_a_trailing_space_that_is_an_operand() {
// `_`, `*` and `\` take the next character, so a final space after one is part of the code.
assert_eq!(clean_fmt("0_ "), "0_ ");
assert_eq!(clean_fmt("#,##0_ "), "#,##0_ ");
assert_eq!(clean_fmt("0* "), "0* ");
assert_eq!(clean_fmt("0\\ "), "0\\ ");
assert_eq!(clean_fmt("0_ \n "), "0_ ");
assert_eq!(clean_fmt("0\"a "), "0\"a ", "a space inside quotes is text");
// Other spaces at the ends, and control characters, still go.
assert_eq!(clean_fmt(" 0.00 \t"), "0.00");
assert_eq!(clean_fmt("0_\n"), "0_");
assert_eq!(clean_fmt("0\"a\" "), "0\"a\"");
assert_eq!(clean_fmt("\\_ "), "\\_", "an escaped `_` takes no operand");
assert_eq!(clean_fmt("0\u{1}0"), "0 0");
assert_eq!(clean_fmt("_\u{1}"), "_");
assert_eq!(clean_fmt(" \n "), "");
let long = format!("{}_ ", "0".repeat(MAX_FMT - 2));
assert_eq!(clean_fmt(&long), long, "a code of exactly MAX_FMT characters keeps its operand");
// Axis and series formats both go through the cleaner.
let mut a = ChartAxis { fmt: Some("0_ ".into()), ..Default::default() };
a.sanitize();
assert_eq!(a.fmt.as_deref(), Some("0_ "));
let mut spec = ChartSpec {
series: vec![ChartSeries { name: "s".into(), values: vec![Some(1.0)], fmt: Some("#,##0_ ".into()), ..Default::default() }],
categories: vec!["a".into()],
..Default::default()
};
spec.sanitize();
assert_eq!(spec.series[0].fmt.as_deref(), Some("#,##0_ "));
}
}
+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)
+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"),
+24 -3
View File
@@ -210,10 +210,31 @@ impl NoteBox {
cuts
}
/// The least of the note that must stay with its reference: its first line (all of it if it
/// can't be split).
/// Whether widow/orphan control in the note's paragraphs forbids splitting at `cut`: a
/// paragraph's first line alone above it (an orphan) or its last line alone below it (a
/// widow), as in Word for Mac 16.114.4.
pub(crate) fn breaks_widow_control(&self, cut: f32) -> bool {
self.items.iter().filter(|it| self.splittable(it)).any(|it| {
let Placed::Lines { para, l0, l1, y, .. } = it else { return false };
let Some(first) = para.lines.get(*l0) else { return false };
let ends_at = |k: usize| para.lines.get(k).is_some_and(|l| (y + l.top - first.top + l.height - cut).abs() < 0.01);
let n = para.lines.len();
para.rp.widow_control && n >= 2 && ((*l0 == 0 && *l1 >= 2 && ends_at(0)) || (*l1 == n && ends_at(n - 2)))
})
}
/// Where the note may be split with its paragraphs' widow/orphan control kept, ascending.
pub(crate) fn kept_cuts(&self) -> Vec<f32> {
let mut cuts = self.cuts();
cuts.retain(|&c| !self.breaks_widow_control(c));
cuts
}
/// The least of the note that must stay with its reference: its first line, or more under
/// widow/orphan control (all of it if it can't be split).
pub(crate) fn first_piece(&self) -> f32 {
self.cuts().first().copied().unwrap_or(self.h).min(self.h)
// Widow/orphan control may keep more lines together (two, or a short paragraph whole).
self.kept_cuts().first().copied().unwrap_or(self.h).min(self.h)
}
/// Split the note at line bottom `cut`: the part above (`cut` tall) and the rest, moved up to
+24 -4
View File
@@ -160,7 +160,7 @@ impl PageBuilder<'_> {
// The note area starts below the text (a page of continued notes alone: at its top).
let area = self.bottom.max(self.body_floor());
let fits = total <= self.orig_bottom - area + 0.01;
let top = match (fits, self.beneath) {
let mut top = match (fits, self.beneath) {
(false, _) => area,
// Below the page's last line of text.
(true, true) => self.body_floor().min(self.orig_bottom - total),
@@ -173,12 +173,15 @@ impl PageBuilder<'_> {
let mut placed = Vec::new();
// Where the continuation notice goes, below a note that continues on the next page.
let mut notice_y = None;
// The bottom of what is placed (with the notice).
let mut end = y;
let mut rest = notes.into_iter();
while let Some(n) = rest.next() {
let room = self.orig_bottom - y;
if fits || n.h <= room + 0.01 {
let ny = y;
y += n.h;
end = y;
placed.push((n, ny));
continue;
}
@@ -186,21 +189,38 @@ impl PageBuilder<'_> {
// always leaves something here (its first line, or all of it if it can't be split),
// so continuing ends.
let first = placed.is_empty();
let cuts = n.cuts();
// Widow/orphan control in the note keeps two of a paragraph's lines on either side;
// the page's first note gives that up before it gives up the page's room.
let room = room - self.seps.notice_h();
match cuts.iter().rev().find(|&&c| c <= room + 0.01).or(cuts.first().filter(|_| first)).copied() {
let fit = |cuts: Vec<f32>| cuts.into_iter().rev().find(|&c| c <= room + 0.01);
let cut = fit(n.kept_cuts()).or_else(|| if first { fit(n.cuts()).or(n.cuts().first().copied()) } else { None });
match cut {
Some(c) => {
let (head, tail) = n.split(c);
notice_y = Some(y + head.h);
end = y + head.h + self.seps.notice_h();
placed.push((head, y));
self.carry.push(tail);
}
None if first => placed.push((n, y)),
None if first => {
end = y + n.h;
placed.push((n, y));
}
None => self.carry.push(n),
}
self.carry.extend(rest.by_ref());
break;
}
// Notes that continue on the next page still end on the bottom margin, the room left
// going above the separator (Word for Mac 16.114.4), unless they go beneath the text.
if !fits && !self.beneath {
let shift = (self.orig_bottom - end).max(0.0);
top += shift;
notice_y = notice_y.map(|ny| ny + shift);
for (_, ny) in &mut placed {
*ny += shift;
}
}
if let Some(pg) = self.pages.last_mut() {
match if cont { &self.seps.cont } else { &self.seps.sep } {
Some((items, _)) => pg.items.extend(items.iter().cloned().map(|mut it| {
+7 -12
View File
@@ -445,9 +445,10 @@ fn section_endnotes(ctx: &mut Ctx, pb: &mut PageBuilder, endnotes: &mut VecDeque
/// the turned pages of vertical sections.
fn finish_pages(pb: PageBuilder, doc: &Document, sections: &[(usize, &SectionProps)], web: bool) -> Vec<Page> {
let mut pb = pb;
pb.close_column_lines();
pb.apply_valign();
pb.flush_notes();
// Each page is aligned once, before its notes go on it: `finish_page` leaves the page
// top-aligned after, so a page of continued notes isn't moved down again past the bottom
// margin when the next one starts.
pb.finish_page();
let last_block = doc.body.len().saturating_sub(1);
for _ in 0..MAX_NOTE_PAGES {
if pb.carry.is_empty() {
@@ -455,7 +456,7 @@ fn finish_pages(pb: PageBuilder, doc: &Document, sections: &[(usize, &SectionPro
}
let top = pb.top;
pb.new_page(last_block, top);
pb.flush_notes();
pb.finish_page();
}
pb.carry.clear();
pb.raise_front();
@@ -521,18 +522,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;
}
}
+150 -16
View File
@@ -11306,6 +11306,156 @@ fn long_footnotes_continue_on_the_next_page() {
assert!(own_note.top > p1.3, "own note after the continued one: {own_note:?} {p1:?}");
}
/// A document of `body` one-line paragraphs, the last of them referencing a footnote of `note`
/// sentences, with widow control `widow` in the note; the note's id.
fn long_note_after(body: usize, note: usize, widow: bool) -> (Document, u32) {
let mut d = Document::from_text(&"Body text line.\n".repeat(body));
let mut p = wordcraft_doc::Paragraph::with_text(&"A long footnote that runs on. ".repeat(note), Default::default());
p.props.widow_control = Some(widow);
p.props.space_after = Some(0.0);
let id = d.add_part(wordcraft_doc::PartKind::Footnote, vec![wordcraft_doc::para_block(p)]);
d.insert_object(
&Pos::body(body.saturating_sub(1), 4),
InlineObject::NoteRef { kind: wordcraft_doc::para::NoteKind::Footnote, id, custom: String::new() },
&Default::default(),
)
.unwrap();
(d, id)
}
#[test]
fn a_footnote_continuing_on_the_next_page_ends_on_the_bottom_margin() {
crate::test_fonts();
// Observed in Word for Mac 16.114.4: whatever room the split leaves goes above the
// separator, the note's last line on the page sitting on the bottom margin.
let bottom = Document::default().last_section.page_h - Document::default().last_section.margin_bottom;
let mut slack = Vec::new();
// With widow/orphan control too, which can leave more room than a plain cut.
for (body, widow) in (11..24).flat_map(|b| [(b, false), (b, true)]) {
let (d, id) = long_note_after(body, 60, widow);
let l = lay(&d);
let pieces = note_pieces(&l, id);
assert!(pieces.len() >= 2 && pieces[0].0 == 0 && pieces[1].0 == 1, "{body} {widow}: {pieces:?}");
// Every line of the note is placed once, in order.
let lines = l.pages[0]
.items
.iter()
.find_map(|it| if let Placed::Lines { story: StoryRef::Part(s), para, .. } = it { (*s == id).then(|| para.lines.len()) } else { None })
.unwrap();
assert_eq!(pieces.windows(2).find(|w| w[0].2 != w[1].1), None, "{body} {widow}: pieces follow on: {pieces:?}");
assert_eq!((pieces[0].1, pieces.last().map(|p| p.2)), (0, Some(lines)), "{body} {widow}: all {lines} lines: {pieces:?}");
let (para, l0, l1, y) = l.pages[0]
.items
.iter()
.find_map(|it| match it {
Placed::Lines { story: StoryRef::Part(s), para, l0, l1, y, .. } if *s == id => Some((para.clone(), *l0, *l1, *y)),
_ => None,
})
.unwrap();
let end = item_bottom(y, &para, l0, l1).unwrap();
slack.push(bottom - end);
}
assert!(slack.iter().all(|s| s.abs() < 0.05), "room left under the note: {slack:?}");
}
#[test]
fn a_footnote_beneath_the_text_stays_under_it_when_it_continues() {
crate::test_fonts();
// Footnotes placed beneath the text (`w:pos w:val="beneathText"`) start right under the page's
// last line even when one continues on the next page: the room left stays below them, not
// above the separator as for notes at the page bottom.
use wordcraft_doc::section::{NotePos, NoteProps};
let mut gaps = Vec::new();
for body in 11..24 {
let (mut d, id) = long_note_after(body, 60, false);
d.settings.footnote_pr = NoteProps { pos: Some(NotePos::BeneathText), ..Default::default() };
let l = lay(&d);
let pieces = note_pieces(&l, id);
assert!(pieces.len() >= 2 && pieces[0].0 == 0, "{body}: {pieces:?}");
let body_bottom = l.pages[0]
.items
.iter()
.filter_map(
|it| if let Placed::Lines { story: StoryRef::Body, y, para, l0, l1, .. } = it { item_bottom(*y, para, *l0, *l1) } else { None },
)
.fold(0.0f32, f32::max);
gaps.push(pieces[0].3 - body_bottom);
}
// Under the last line by the default separator's height, whatever the body's length.
assert!(gaps.iter().all(|g| (g - crate::notes::NOTE_SEP).abs() < 0.05), "the note starts the separator's height under the text: {gaps:?}");
}
#[test]
fn a_footnote_continued_onto_pages_of_notes_stays_above_the_bottom_margin_when_centred() {
crate::test_fonts();
// A centred (or bottom-aligned) section whose last page's note runs on over pages of notes
// alone: each page is aligned once, before its notes are placed, so no note line is moved
// past the bottom margin by aligning a page again after its notes went on it.
use wordcraft_doc::section::PageVAlign;
let bottom = Document::default().last_section.page_h - Document::default().last_section.margin_bottom;
for va in [PageVAlign::Center, PageVAlign::Bottom] {
let (mut d, id) = long_note_after(3, 400, false);
d.last_section.valign = va;
let l = lay(&d);
let pieces = note_pieces(&l, id);
assert!(pieces.iter().map(|p| p.0).max().unwrap_or(0) >= 2, "{va:?}: the note runs over pages of notes alone: {pieces:?}");
for (pi, p) in l.pages.iter().enumerate() {
for it in &p.items {
if let Placed::Lines { story: StoryRef::Part(s), para, l0, l1, y, .. } = it
&& *s == id
{
let end = item_bottom(*y, para, *l0, *l1).unwrap();
assert!(end <= bottom + 0.05, "{va:?}: page {pi} note lines end at {end}, below the bottom margin {bottom}");
}
}
}
}
}
#[test]
fn widow_control_leaves_two_lines_of_a_split_footnote_on_the_next_page() {
crate::test_fonts();
// Observed in Word for Mac 16.114.4: a note that would leave its last line alone on the next
// page takes one more line along when its paragraph has widow control.
let lines_after = |body: usize, widow: bool| {
let (d, id) = long_note_after(body, 60, widow);
let pieces = note_pieces(&lay(&d), id);
pieces.get(1).filter(|p| p.0 == 1).map(|p| p.2 - p.1)
};
let widows: Vec<usize> = (9..26).filter(|&b| lines_after(b, false) == Some(1)).collect();
assert!(!widows.is_empty(), "no body length leaves one line of the note on page 2");
for b in widows {
assert_eq!(lines_after(b, true), Some(2), "body of {b} lines");
}
}
#[test]
fn orphan_control_keeps_two_lines_of_a_split_footnote_with_its_reference() {
crate::test_fonts();
// Observed in Word for Mac 16.114.4: rather than leave a note paragraph's first line alone at
// the bottom of the page, the line with the reference goes on to the next page with it.
let first_piece = |body: usize, widow: bool| {
let (mut d, id) = long_note_after(body, 60, widow);
// Body lines as tall as the note's, so the room under the text shrinks a note line at a time.
for block in &mut d.body {
if let Block::Para(para) = Arc::make_mut(block) {
para.props.space_after = Some(0.0);
}
}
let l = lay(&d);
let refs = l.caret(&Pos::body(body - 1, 4)).unwrap().page;
let pieces = note_pieces(&l, id);
(refs, pieces.first().map(|p| (p.0, p.2 - p.1)))
};
let orphans: Vec<usize> = (20..60).filter(|&b| first_piece(b, false).1.is_some_and(|p| p.1 == 1)).collect();
assert!(!orphans.is_empty(), "no body length leaves one line of the note with its reference");
for b in orphans {
let (refs, piece) = first_piece(b, true);
assert_eq!(piece.map(|p| p.0), Some(refs), "body of {b} lines: the note starts on its reference's page");
assert!(piece.is_some_and(|p| p.1 >= 2), "body of {b} lines: {piece:?}");
}
}
#[test]
fn short_footnotes_stay_whole() {
crate::test_fonts();
@@ -18287,19 +18437,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);
}
}
}
+16 -196
View File
@@ -1,9 +1,8 @@
//! Responsiveness and memory probe: runs the real WordCraft UI headless (like `ui_shot`, without a
//! window or focus), opens a document (or generates a `--synthetic` workload), and times the frames
//! that handle idle rendering, typing, edit/undo bursts, scrolling, zooming, ribbon tabs, and
//! window resizes. Prints numbers only (JSON), never document text.
//! Responsiveness probe: runs the real WordCraft UI headless (like `ui_shot`, without a window or
//! focus), opens a document, and times the frames that handle typing, scrolling, zooming,
//! ribbon tabs and window resizes. Prints numbers only (JSON), never document text.
//!
//! `cargo run --release -p wordcraft-ui-egui --example perf_probe -- [--synthetic | doc.docx] [block]`
//! `cargo run --release -p wordcraft-ui-egui --example perf_probe -- doc.docx [block]`
//!
//! A frame's time is the CPU time of one harness step (`WordApp::logic` + `ui`: layout, page
//! rasterisation, widgets). What the user sees adds the wait for the next frame and the
@@ -15,9 +14,6 @@ use std::time::Instant;
use craft::automation::control::{ControlChannel, ControlRequest};
use serde_json::{Value, json};
use wordcraft_doc::para::InlineObject;
use wordcraft_doc::table::{Cell, Table};
use wordcraft_doc::{Block, Document, Path, Pos, StoryRef};
use wordcraft_engine::Session;
use wordcraft_ui_egui::{Services, WordApp};
@@ -25,118 +21,6 @@ static READY: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new
type Harness<'a> = egui_kittest::Harness<'a, WordApp>;
/// Drains `TexturesDelta` every frame instead of letting `egui_kittest::LazyRenderer::Uninitialized`
/// hoard every uploaded page/tile image across the probe run.
struct DrainRenderer;
impl egui_kittest::TestRenderer for DrainRenderer {
fn handle_delta(&mut self, delta: &mut egui::TexturesDelta) {
delta.clear();
}
fn render(&mut self, _ctx: &egui::Context, _output: &egui::FullOutput) -> Result<image::RgbaImage, String> {
Err("perf_probe runs headless without framebuffer readback".into())
}
}
fn round1(v: f64) -> f64 {
(v * 10.0).round() / 10.0
}
/// Reads Linux `/proc/self/status` for current resident memory (`VmRSS`) and peak (`VmHWM`) in MiB.
fn memory_mb() -> Value {
#[cfg(target_os = "linux")]
{
let Ok(status) = std::fs::read_to_string("/proc/self/status") else {
return Value::Null;
};
let parse_kb = |prefix: &str| -> Option<f64> {
status.lines().find_map(|line| {
let rest = line.strip_prefix(prefix)?.trim();
let kb: f64 = rest.split_whitespace().next()?.parse().ok()?;
Some(round1(kb / 1024.0))
})
};
json!({"rss_mb": parse_kb("VmRSS:"), "hwm_mb": parse_kb("VmHWM:")})
}
#[cfg(not(target_os = "linux"))]
{
Value::Null
}
}
/// Builds a deterministic in-memory workload combining styled paragraphs, a large table, embedded
/// PNG images, and tracked revisions so baselines need no external `.docx` fixture.
fn synthetic_session() -> Session {
let mut text = String::new();
let sentence = "The quick brown fox jumps over the lazy dog while layout, styles, numbering, and proofing run across pages.";
for i in 0..1156 {
if i == 100 {
text.push_str(&format!("Paragraph {i}: "));
for rep in 0..25 {
if rep > 0 {
text.push(' ');
}
text.push_str(sentence);
}
text.push('\n');
} else {
text.push_str(&format!("Paragraph {i}: {sentence}\n"));
}
}
let mut doc = Document::from_text(&text);
for i in (0..1156).step_by(20) {
let _ = doc.format_paragraphs(&Pos::body(i, 0), &Pos::body(i, 0), &|p| p.style = Some("Heading1".into()));
}
let mut table = Table::new(250, 8, 468.0);
for (r, row) in table.rows.iter_mut().enumerate() {
for (c, cell) in row.cells.iter_mut().enumerate() {
let w = cell.props.width;
*cell = Cell::with_text(&format!("R{r} C{c} value {}", r * 8 + c));
cell.props.width = w;
}
}
let _ = doc.insert_block(StoryRef::Body, &Path::top(50), Block::Table(table));
for img_idx in 0..16_u8 {
let mut rgba = image::RgbaImage::new(256, 256);
for (x, y, px) in rgba.enumerate_pixels_mut() {
*px = image::Rgba([
img_idx.wrapping_mul(17).wrapping_add((x % 256) as u8),
img_idx.wrapping_mul(31).wrapping_add((y % 256) as u8),
200_u8.wrapping_sub(img_idx.wrapping_mul(11)),
255,
]);
}
if let Ok(png) = wordcraft_geom::picture::encode_png(&image::DynamicImage::ImageRgba8(rgba)) {
let key = doc.add_media(png, "png");
let block_idx = 2 + usize::from(img_idx) * 2;
let _ = doc.insert_object(
&Pos::body(block_idx, 0),
InlineObject::Image {
media: key,
w: 144.0,
h: 144.0,
alt: format!("Synthetic image {img_idx}"),
float: Default::default(),
crop: [0.0; 4],
fx: Default::default(),
ole: None,
},
&Default::default(),
);
}
}
let mut session = Session::new(doc);
let _ = session.run("review.trackChanges", &json!({"enabled": true}));
let _ = session.run("caret.set", &json!({"pos": {"story": "body", "path": [0], "off": 0}}));
let _ = session.run("text.insert", &json!({"text": "Tracked prefix "}));
let _ = session.run("review.trackChanges", &json!({"enabled": false}));
session
}
/// Queues a control request; the app answers it in the logic phase of a following frame.
fn request(tx: &Sender<ControlRequest>, method: &str, params: Value) {
let (req, _reply) = ControlRequest::new(method, params);
@@ -162,34 +46,22 @@ fn stats(v: &[f64]) -> Value {
let mut s = v.to_vec();
s.sort_by(f64::total_cmp);
let at = |q: f64| s.get(((s.len() as f64 - 1.0) * q).round() as usize).copied().unwrap_or(0.0);
json!({"n": s.len(), "med": round1(at(0.5)), "p95": round1(at(0.95)), "max": round1(at(1.0))})
json!({"n": s.len(), "med": (at(0.5) * 10.0).round() / 10.0, "p95": (at(0.95) * 10.0).round() / 10.0, "max": (at(1.0) * 10.0).round() / 10.0})
}
/// Opens the document named on the command line (or builds `--synthetic`) and prints JSON timings
/// and memory metrics for start-up, idle, typing, edit/undo bursts, scrolling, zooming, ribbon
/// tabs and window resizes.
/// Opens the document named on the command line and prints JSON timings for start-up, typing,
/// scrolling, zooming, ribbon tabs and window resizes.
fn main() {
let path = std::env::args().nth(1).expect("usage: perf_probe [--synthetic | doc.docx] [block]");
let path = std::env::args().nth(1).expect("usage: perf_probe doc.docx [block]");
let block: Option<usize> = std::env::args().nth(2).and_then(|b| b.parse().ok());
let mem_start = memory_mb();
let t_open = Instant::now();
let session = if path == "--synthetic" {
synthetic_session()
} else {
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("file.open", &json!({"path": path})).expect("open");
s
};
let mut session = Session::new(wordcraft_doc::Document::new());
session.run("file.open", &json!({"path": path})).expect("open");
let open_ms = t_open.elapsed().as_secs_f64() * 1000.0;
let mem_after_open = memory_mb();
let (tx, rx) = std::sync::mpsc::channel::<ControlRequest>();
let app = WordApp::new(session, Services::default()).with_control(ControlChannel::new(rx));
let mut h = egui_kittest::Harness::builder()
.renderer(DrainRenderer)
.with_size(egui::vec2(1440.0, 900.0))
.with_pixels_per_point(2.0)
.with_max_steps(1_000_000)
.build_ui_state(
let mut h =
egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_pixels_per_point(2.0).with_max_steps(1_000_000).build_ui_state(
|ui, app: &mut WordApp| {
if !READY.load(std::sync::atomic::Ordering::Relaxed) {
return;
@@ -210,18 +82,8 @@ fn main() {
}
READY.store(true, std::sync::atomic::Ordering::Relaxed);
let first: Vec<f64> = (0..6).map(|_| step(&mut h)).collect();
let mem_after_first = memory_mb();
let idle: Vec<f64> = (0..60).map(|_| step(&mut h)).collect();
let mem_after_idle = memory_mb();
let mut out = json!({
"source": if path == "--synthetic" { "synthetic" } else { "file" },
"open_ms": round1(open_ms),
"pages": h.state_mut().session.layout().pages.len(),
"first_frames_ms": first.iter().map(|x| round1(*x)).collect::<Vec<_>>(),
"idle_60_frames_ms": stats(&idle),
});
let mut out =
json!({"open_ms": (open_ms * 10.0).round() / 10.0, "first_frames_ms": first.iter().map(|x| (x * 10.0).round() / 10.0).collect::<Vec<_>>()});
// Typing: the caret in the middle of `block` (default: the longest paragraph), 40 characters.
let doc_block = block.unwrap_or_else(|| {
@@ -264,24 +126,6 @@ fn main() {
if let Some(t) = table {
out["typing_table"] = typing(&mut h, json!({"story": "body", "path": [t, 0, 0, 0], "off": 0}));
}
let mem_after_typing = memory_mb();
// Edit/Undo burst: 40 discrete paragraph insertions followed by 40 undos.
let mut edit_burst = Vec::new();
let mut undo_burst = Vec::new();
for k in 0..40 {
h.state_mut().session.close_typing();
exec(&tx, "text.insert", json!({"text": format!(" {k}")}));
edit_burst.push(step(&mut h));
}
let mem_after_edits = memory_mb();
for _ in 0..40 {
exec(&tx, "edit.undo", json!({}));
undo_burst.push(step(&mut h));
}
let mem_after_undo = memory_mb();
out["edit_burst_40_ms"] = stats(&edit_burst);
out["undo_burst_40_ms"] = stats(&undo_burst);
// Scrolling: mouse wheel (120 pt notches) and trackpad (20 pt gestures) over the canvas.
let scroll = |h: &mut Harness<'_>, dy: f32, n: usize| -> Value {
@@ -298,7 +142,6 @@ fn main() {
};
out["scroll_wheel"] = scroll(&mut h, -120.0, 120);
out["scroll_trackpad"] = scroll(&mut h, -20.0, 300);
let mem_after_scroll = memory_mb();
// Zoom, ribbon tabs, resize: the frame after the change.
let mut zoom = Vec::new();
@@ -306,49 +149,26 @@ fn main() {
exec(&tx, "view.zoom", json!({"value": z}));
let a = step(&mut h);
let b = step(&mut h);
zoom.push(json!({"zoom": z, "frame_ms": round1(a), "next_ms": round1(b)}));
zoom.push(json!({"zoom": z, "frame_ms": (a * 10.0).round() / 10.0, "next_ms": (b * 10.0).round() / 10.0}));
}
out["zoom"] = json!(zoom);
let mem_after_zoom = memory_mb();
let mut tabs = Vec::new();
for t in ["Insert", "Draw", "Design", "Layout", "References", "Mailings", "Review", "View", "Home"] {
exec(&tx, "ui.tab", json!({"tab": t}));
tabs.push(step(&mut h));
}
out["ribbon_tab_ms"] = stats(&tabs);
let mem_after_ribbon = memory_mb();
let mut rs = Vec::new();
for w in (800..=1440).rev().step_by(40).chain((800..=1440).step_by(40)) {
h.set_size(egui::vec2(w as f32, 900.0));
rs.push(step(&mut h));
}
out["resize_ms"] = stats(&rs);
let mem_after_resize = memory_mb();
// Accept all (if the document has tracked changes).
if !h.state().session.doc.revisions.is_empty() {
exec(&tx, "review.acceptAll", json!({}));
let f = step(&mut h);
out["accept_all"] = json!({"frame_ms": round1(f)});
out["accept_all"] = json!({"frame_ms": (f * 10.0).round() / 10.0});
}
let mem_end = memory_mb();
let tex_mgr = h.ctx.tex_manager();
let tm = tex_mgr.read();
let tex_bytes: usize = tm.allocated().map(|(_, m)| m.size[0] * m.size[1] * m.bytes_per_pixel).sum();
out["textures_end"] = json!({"count": tm.num_allocated(), "mb": round1(tex_bytes as f64 / (1024.0 * 1024.0))});
drop(tm);
out["memory"] = json!({
"start": mem_start,
"after_open": mem_after_open,
"after_first_frames": mem_after_first,
"after_idle": mem_after_idle,
"after_typing": mem_after_typing,
"after_edits": mem_after_edits,
"after_undo": mem_after_undo,
"after_scroll": mem_after_scroll,
"after_zoom": mem_after_zoom,
"after_ribbon": mem_after_ribbon,
"after_resize": mem_after_resize,
"end": mem_end,
});
println!("{out}");
}
+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;
+1 -14
View File
@@ -65,12 +65,11 @@ pub(crate) fn page_rulers(app: &mut WordApp, ui: &mut Ui, out: &craft::pages::ui
row_cells.first().map(|f| std::iter::once(f.x).chain(row_cells.iter().map(|b| b.right())).collect()).unwrap_or_default();
// While a column marker is dragged the markers show where the preview puts their borders (the ruler draws them
// where it is told), so the grabbed marker follows the pointer and the ones right of it move along.
let caret_row_idx = app.session.sel.focus.path.cell().map(|(_, r, _)| r);
let mods = crate::table_resize::mods_now(ui.ctx());
let borders: Vec<f32> = borders_page
.iter()
.enumerate()
.map(|(line, &x)| to_start(crate::table_resize::caret_drag(app, pi).and_then(|d| d.ruler_line_x(mods, caret_row_idx, line)).unwrap_or(x)))
.map(|(line, &x)| to_start(app.canvas.table_resize.as_ref().and_then(|d| d.ruler_line_x(mods, line)).unwrap_or(x)))
.collect();
let row_y = row_cells.first().map_or(0.0, |b| b.y + b.h / 2.0);
let bottoms = row_bottoms(app, layout, pi);
@@ -102,18 +101,6 @@ pub(crate) fn page_rulers(app: &mut WordApp, ui: &mut Ui, out: &craft::pages::ui
.mirrored_even(mirrored)
.show_at(ui, canvas_rect);
if crate::table_resize::measuring(app, ui.ctx(), pi) {
let bar = output.ruler.edit.response.rect;
let painter = ui.painter_at(bar);
let t = ui.visuals();
for (mid, w) in crate::table_resize::widths(app, ui.ctx(), layout, pi) {
let at = egui::pos2(placed.rect.min.x + mid * placed.scale as f32, bar.center().y);
let text = painter.layout_no_wrap(app.session.format_length(w), egui::FontId::proportional(9.5), t.text_color());
painter.rect_filled(egui::Rect::from_center_size(at, text.size() + egui::vec2(4.0, 0.0)), 1.0, t.window_fill());
painter.galley(at - text.size() / 2.0, text, t.text_color());
}
}
if let Some(k) = output.ruler.kind {
app.canvas.tab_kind = doc_align(k);
}
-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 -80
View File
@@ -118,8 +118,7 @@ fn clicked(phase: &PressPhase) -> bool {
}
/// The frames and title tabs of the content controls, their check boxes and the list or date button of the control
/// the caret is in. The check boxes and the button are parts, so a press on one never reaches the page tool, and it
/// keeps the page's keyboard focus: a list or calendar opened from the page gives the focus back to it as it closes.
/// the caret is in. The check boxes and the button are parts, so a press on one never reaches the page tool.
#[derive(craft::ui::contract::Component, craft::ui::contract::Props)]
#[component(canvas_control)]
struct ContentControls<'a> {
@@ -189,14 +188,14 @@ impl Component for ContentControls<'_> {
let handle = HitPriority::new(HitLevel::Handle, 0);
for (i, r) in self.checks.iter().enumerate() {
cx.part(CHECK.at(i as u64), HitShape::Rect(grown(*r, cx.style)))
.sense(Sense::CLICK | Sense::KEEP_FOCUS)
.sense(Sense::CLICK)
.priority(handle)
.cursor(CursorIcon::PointingHand)
.pointer_only("Developer > Check Box ticks the control the caret is in");
}
if let Some(b) = self.button.map(|last| button_rect(last, cx.style)) {
cx.part(PartRef::from(BUTTON), HitShape::Rect(b))
.sense(Sense::CLICK | Sense::KEEP_FOCUS)
.sense(Sense::CLICK)
.priority(handle)
.cursor(CursorIcon::PointingHand)
.pointer_only("Developer > Choose Item and Set Date run the same commands");
@@ -393,14 +392,6 @@ mod tests {
app.run("text.insert", json!({"text": "tail text"})).unwrap();
app.run("caret.docStart", json!({})).unwrap();
app.run("developer.dropDown", json!({"items": ["A", "B"]})).unwrap();
let h = harness(app);
let before = h.state().session.sel.focus.clone();
assert!(h.state().session.doc.control_at(&before).is_some(), "the caret starts in the control");
h
}
/// `app` in a window, with the comments pane closed.
fn harness(mut app: WordApp) -> egui_kittest::Harness<'static, WordApp> {
app.run("view.commentsPane", json!({"value": false})).unwrap();
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|ui, app: &mut WordApp| {
@@ -413,35 +404,11 @@ mod tests {
for _ in 0..6 {
h.step();
}
let before = h.state().session.sel.focus.clone();
assert!(h.state().session.doc.control_at(&before).is_some(), "the caret starts in the control");
h
}
/// Presses and releases the primary button over `at` as a person does: the pointer arrives a
/// frame before the press, and the release is a frame of its own.
fn click_at(h: &mut egui_kittest::Harness<'static, WordApp>, at: egui::Pos2) {
let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
h.event(egui::Event::PointerMoved(at));
crate::test_harness::frames(h, 1);
h.event(button(true));
crate::test_harness::frames(h, 1);
h.event(button(false));
crate::test_harness::frames(h, 3);
}
/// Gives the page the keyboard without moving the caret.
fn focus_page(h: &mut egui_kittest::Harness<'static, WordApp>) {
let ctx = h.ctx.clone();
h.state_mut().canvas.focus_page(&ctx);
crate::test_harness::frames(h, 2);
assert!(page_focused(h), "the page has the keyboard");
}
/// Whether the page has the keyboard, for the framework and in the access tree a screen reader reads.
fn page_focused(h: &egui_kittest::Harness<'static, WordApp>) -> bool {
let document = egui_kittest::kittest::By::new().role(egui::accesskit::Role::Canvas).label("Document");
h.state().canvas.focused(&h.ctx) && h.query_all(document).any(|n| n.is_focused())
}
/// #5389: pressing a drop-down's list button opens the list and leaves the caret in the
/// control, even when text follows the control and the button hangs over it.
#[test]
@@ -485,46 +452,4 @@ mod tests {
assert!(!popup_open(h.state()), "the press did not open the list");
assert!(h.state().session.undo_depth() > depth, "the stroke ran table.draw");
}
/// #7862: a press on the list button leaves the keyboard with the page, so the list gives it
/// back to the page when it closes, by Escape or by a pick.
#[test]
fn closing_the_list_gives_the_keyboard_back_to_the_page() {
let mut h = dropdown_harness();
focus_page(&mut h);
let button = h.get_by_label("Choose item").rect().center();
click_at(&mut h, button);
assert!(popup_open(h.state()), "the list is open");
h.key_press(egui::Key::Escape);
crate::test_harness::frames(&mut h, 2);
assert!(!popup_open(h.state()), "Escape closes the list");
assert!(page_focused(&h), "Escape gives the keyboard back to the page");
click_at(&mut h, button);
assert!(popup_open(h.state()), "the list opens again");
let row = h.get_by_role_and_label(egui::accesskit::Role::MenuItem, "B").rect().center();
click_at(&mut h, row);
assert!(!popup_open(h.state()), "the pick closes the list");
assert!(page_focused(&h), "the pick gives the keyboard back to the page");
}
/// #7862: a click on a check box control ticks it and leaves the keyboard with the page.
#[test]
fn ticking_a_check_box_leaves_the_keyboard_with_the_page() {
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
app.run("developer.checkBox", json!({})).unwrap();
let mut h = harness(app);
focus_page(&mut h);
let tick = h.get_by_role_and_label(egui::accesskit::Role::CheckBox, "Check box").rect().center();
click_at(&mut h, tick);
let ticked = h
.state()
.session
.doc
.control_ranges(wordcraft_doc::StoryRef::Body)
.iter()
.any(|r| matches!(r.control.kind, ControlKind::CheckBox { checked: true, .. }));
assert!(ticked, "the click ticks the box");
assert!(page_focused(&h), "the page keeps the keyboard");
}
}
+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(
+3 -11
View File
@@ -2,7 +2,7 @@ use craft::behavior::{EditEvent, IconId, Selection};
use craft::review::ThreadId;
use craft::review::ui::CommentsPanelState;
use craft::ui::buttons::Button;
use craft::ui::contract::{Bind, Props, Show, ShowContainer, Sizing};
use craft::ui::contract::{Bind, Props, Show, ShowContainer};
use craft::ui::display::Text;
use craft::ui::layout_components::{Row, Stack};
use craft::ui::primitives::IconSpec;
@@ -128,12 +128,6 @@ pub(crate) fn state_has_drafts(state: &CommentsPanelState) -> bool {
/// is cut off in a balloon that isn't selected (#3382).
pub(crate) const COMMENT_ROWS: usize = 10;
/// The lines a comment or reply field in the pane shows at least. A field of one line is a single-line field, which
/// doesn't wrap (#7906); from two lines it wraps its text and grows with it up to [`COMMENT_ROWS`]. The fields take
/// the card's width, as they did before the port: a field measures its lines at the width it is offered, so one drawn
/// at its own, narrower length would come out lines short of its text.
const FIELD_LINES: usize = 2;
/// A comment's text, editable in place. Typing stays in a draft until the field's value lands (focus leaves it);
/// then [`commit_comment`] writes it back with one `review.editComment`, so each editing session is one undo step.
/// Escape gives back the text from before, so the draft goes.
@@ -146,9 +140,8 @@ fn comment_field(app: &mut WordApp, ui: &mut Ui, document: u64, id: u32) {
let field = ui.make_persistent_id(("comment_edit", document, id));
let out = TextField::new(tl!("Comment").to_owned(), Bind::given(shown))
.id(field)
.lines(FIELD_LINES)
.lines(1)
.max_lines(COMMENT_ROWS)
.sizing(Sizing::FillWidth)
.placeholder(tl!("Add a comment").to_owned())
.enabled(editable)
.show(ui);
@@ -205,9 +198,8 @@ fn reply_field(app: &mut WordApp, ui: &mut Ui, document: u64, id: u32) -> bool {
let field = reply_id(document, id);
let out = TextField::new(tl!("Reply").to_owned(), Bind::given(shown))
.id(field)
.lines(FIELD_LINES)
.lines(1)
.max_lines(COMMENT_ROWS)
.sizing(Sizing::FillWidth)
.placeholder(tl!("Write a reply").to_owned())
.enabled(editable)
.show(ui);
-137
View File
@@ -273,143 +273,6 @@ fn a_long_comment_card_keeps_its_buttons_and_the_next_card_in_view() {
assert!(go_to[1].min.y > go_to[0].max.y, "the second card sits below the first: {go_to:?}");
}
/// #7906: the Comments pane's comment and reply fields wrap their text, so a long comment or reply shows on as many
/// lines as it needs, up to the ten-line cap (#3382), and Enter starts a new line in them.
#[cfg(not(target_arch = "wasm32"))]
mod comment_wrapping {
use egui::accesskit::Role;
use egui_kittest::kittest::Queryable;
type H = egui_kittest::Harness<'static, crate::WordApp>;
/// A sentence of comment text, longer than one line of the pane.
const SENTENCE: &str = "This comment is long enough to need more than one line of the Comments pane. ";
/// A window whose paragraphs carry one comment each, with `texts`, and the Comments pane open. Each frame hands the
/// runtime the app's input first, as the app's driver does. The window is tall enough to show every card.
fn pane(texts: &[String]) -> H {
let words = ["Alpha", "Beta", "Gamma", "Delta"];
let body = words.iter().map(|w| format!("{w} paragraph.")).collect::<Vec<_>>().join("\n\n");
let mut app = crate::WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text(&body)), crate::Services::default());
for (word, text) in words.iter().zip(texts) {
app.run("select.text", serde_json::json!({"text": word})).unwrap();
app.run("review.newComment", serde_json::json!({"text": text})).unwrap();
}
app.run("view.commentsPane", serde_json::json!({"value": true})).unwrap();
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 1600.0)).build_ui_state(
|ui, app: &mut crate::WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
app,
);
crate::test_harness::frames(&mut h, 6);
h
}
/// The rects of the pane's fields named `label`, top to bottom.
fn fields(h: &H, label: &str) -> Vec<egui::Rect> {
let mut rects: Vec<egui::Rect> = [Role::TextInput, Role::MultilineTextInput]
.into_iter()
.flat_map(|role| h.query_all_by_role_and_label(role, label).map(|n| n.rect()).collect::<Vec<_>>())
.collect();
rects.sort_by(|a, b| a.min.y.total_cmp(&b.min.y));
rects
}
/// A primary click at `at`: press and release a frame apart, then frames to settle.
fn click_at(h: &mut H, at: egui::Pos2) {
h.event(egui::Event::PointerMoved(at));
for pressed in [true, false] {
h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE });
crate::test_harness::frame(h);
}
crate::test_harness::frames(h, 3);
}
/// A press and release of `key`, then frames to settle.
fn press_key(h: &mut H, key: egui::Key) {
for pressed in [true, false] {
h.event(egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE });
}
crate::test_harness::frames(h, 4);
}
/// Types `text` into the field that has the keyboard.
fn type_text(h: &mut H, text: &str) {
h.event(egui::Event::Text(text.into()));
crate::test_harness::frames(h, 4);
}
/// The box of the pane's field named `label` that holds `text`, and the boxes of the lines (`TextRun`s) its text is
/// laid out in. A line outside the field's box is out of sight until the field scrolls to it.
fn field_lines(h: &H, label: &str, text: &str) -> (egui::Rect, Vec<egui::Rect>) {
let field = [Role::TextInput, Role::MultilineTextInput]
.into_iter()
.find_map(|role| h.query_all_by_role_and_label(role, label).find(|n| n.value().as_deref() == Some(text)))
.unwrap_or_else(|| panic!("no {label} field holds {text:?}"));
let lines = field.query_all_by_role(Role::TextRun).map(|line| line.rect()).collect();
(field.rect(), lines)
}
/// Whether `line` lies inside the field's box `field`.
fn in_sight(field: egui::Rect, line: egui::Rect) -> bool {
line.top() >= field.top() - 0.5 && line.bottom() <= field.bottom() + 0.5
}
/// A long comment shows every line in its field, which grows past a short comment's to hold them; a longer one
/// shows ten lines, and the rest of its text scrolls inside the field.
#[test]
fn a_long_comment_shows_every_line_up_to_the_cap() {
let (short, long, capped) = ("Short note.".to_owned(), SENTENCE.repeat(3), SENTENCE.repeat(30));
let h = pane(&[short.clone(), long.clone(), capped.clone()]);
let (short_field, _) = field_lines(&h, "Comment", &short);
let (field, lines) = field_lines(&h, "Comment", &long);
assert!(lines.len() > 2, "a long comment wraps onto several lines: {lines:?}");
assert!(lines.iter().all(|line| in_sight(field, *line)), "every line of it is in sight: {field:?} {lines:?}");
assert!(field.height() > short_field.height(), "its field is taller than a short comment's: {short_field:?} {field:?}");
let (field, lines) = field_lines(&h, "Comment", &capped);
let shown = lines.iter().filter(|line| in_sight(field, **line)).count();
assert_eq!(shown, crate::panes::comments::COMMENT_ROWS, "a longer comment shows ten lines: {field:?}");
assert!(lines.len() > shown, "and the rest of it scrolls inside the field");
}
/// A long reply shows every line in its field as it is typed: the field grows with the text.
#[test]
fn a_long_reply_shows_every_line_as_it_is_typed() {
let mut h = pane(&["Short note.".to_owned()]);
let reply = h.get_by_role_and_label(Role::Button, "Reply").rect().center();
click_at(&mut h, reply);
let typed = SENTENCE.repeat(3);
type_text(&mut h, &typed);
let (field, lines) = field_lines(&h, "Reply", &typed);
assert!(lines.len() > 2, "the reply wraps onto several lines: {lines:?}");
assert!(lines.iter().all(|line| in_sight(field, *line)), "every line of it is in sight: {field:?} {lines:?}");
}
/// Enter starts a new line in a comment's field and writes nothing; leaving the field writes the edit, both lines,
/// as one undo step.
#[test]
fn enter_starts_a_new_line_in_a_comment_and_leaving_writes_it_once() {
let mut h = pane(&["Parent comment.".to_owned()]);
let depth = h.state().session.undo_depth();
let field = fields(&h, "Comment").first().map(|r| r.center()).expect("the comment's field");
click_at(&mut h, field);
press_key(&mut h, egui::Key::End);
type_text(&mut h, " Edited.");
press_key(&mut h, egui::Key::Enter);
type_text(&mut h, "Second line.");
assert_eq!(h.state().session.undo_depth(), depth, "nothing is written while the comment is typed, Enter included");
let page = h.state().canvas.page_rects().next().map(|(_, r)| r.center()).expect("a page is shown");
click_at(&mut h, page);
let doc = &h.state().session.doc;
let text = doc.comments.values().next().map(|c| doc.plain_text(wordcraft_doc::StoryRef::Part(c.part))).unwrap_or_default();
assert_eq!(text, "Parent comment. Edited.\nSecond line.", "leaving the field wrote both lines");
assert_eq!(h.state().session.undo_depth(), depth + 1, "as one undo step");
}
}
/// Numbered headings are listed with the number they show, and numbered body paragraphs in
/// the same list still count (#3418).
#[test]
-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()]);
}
}
+3 -49
View File
@@ -81,13 +81,12 @@ impl ResizeDrag {
/// Where grid line `line` (the table's left edge is 0) stands on the page while a ruler drag of a column border is
/// in progress, with the keys `mods` held; `None` when no such drag runs. The ruler's markers follow it: the
/// framework ruler draws each marker where the app says its border is.
pub(crate) fn ruler_line_x(&self, mods: Mods, row: Option<usize>, line: usize) -> Option<f32> {
if !matches!(self.target.edge, Edge::Column(_)) {
pub(crate) fn ruler_line_x(&self, mods: Mods, line: usize) -> Option<f32> {
if !self.ruler || !matches!(self.target.edge, Edge::Column(_)) {
return None;
}
let plan = self.plan(mods);
let row = row.or_else(|| plan.cells.first().map(|(r, _)| *r));
Some(self.target.planned_x(&plan, row, line))
Some(self.target.planned_x(&plan, plan.cells.first().map(|(r, _)| *r), line))
}
/// Whether the pointer has moved from where it went down.
@@ -96,51 +95,6 @@ impl ResizeDrag {
}
}
pub(crate) fn caret_drag(app: &WordApp, page: usize) -> Option<&ResizeDrag> {
let caret = app.session.sel.focus.path.cell().map(|(tp, _, _)| tp);
app.canvas
.table_resize
.as_ref()
.filter(|d| d.page == page && d.target.story == app.session.sel.focus.story && caret.as_ref() == Some(&d.target.table))
}
/// Whether the rulers show the caret's table's column widths: Alt is held while one of its
/// column borders (or its left edge) is dragged on `page`, as in Word.
pub(crate) fn measuring(app: &WordApp, ctx: &egui::Context, page: usize) -> bool {
ctx.input(|i| i.modifiers.alt) && caret_drag(app, page).is_some_and(|d| matches!(d.target.edge, Edge::Column(_)))
}
/// The column widths of the caret table row during an Alt drag.
pub(crate) fn widths(app: &WordApp, ctx: &egui::Context, layout: &DocLayout, page: usize) -> Vec<(f32, f32)> {
if !measuring(app, ctx, page) {
return Vec::new();
}
let story = app.session.sel.focus.story;
let caret = app.session.sel.focus.path.cell().map(|(tp, r, _)| (tp, r));
let Some((tp, r)) = caret else { return Vec::new() };
let mut row: Vec<wordcraft_geom::Rect> = layout.pages.get(page).map_or(Vec::new(), |p| {
p.items
.iter()
.filter_map(|it| match it {
wordcraft_layout::Placed::Cell { rect, table, row, story: cell_story, .. } if *cell_story == story && *table == tp && *row == r => {
Some(*rect)
}
_ => None,
})
.collect()
});
row.sort_by(|a, b| a.x.total_cmp(&b.x));
let Some(first) = row.first() else { return Vec::new() };
let borders_page: Vec<f32> = std::iter::once(first.x).chain(row.iter().map(|b| b.right())).collect();
let mods = mods_now(ctx);
let borders: Vec<f32> = borders_page
.iter()
.enumerate()
.map(|(line, &x)| caret_drag(app, page).and_then(|d| d.ruler_line_x(mods, Some(r), line)).unwrap_or(x))
.collect();
borders.windows(2).map(|w| ((w[0] + w[1]) / 2.0, w[1] - w[0])).collect()
}
/// Page y of the bottom of `tg`'s row `row` with `plan` applied (rows above it that change move
/// it too); `None` when the row isn't drawn on the page.
fn planned_bottom(tg: &ResizeTarget, plan: &Plan, row: usize) -> Option<f32> {
-76
View File
@@ -380,79 +380,3 @@ fn double_clicking_a_column_border_fits_the_column() {
assert!((b1.w - b.w).abs() < 1.0 && (b1.x - b.x - (a1.w - a.w)).abs() < 1.0, "the next column keeps its width and moves along");
assert_eq!(h.state().session.undo_depth(), depth + 1, "one undo step");
}
/// The widths Alt shows on the ruler are in the File › Options unit, written the region's way:
/// centimetres with a decimal comma in Brazil, not inches (#5231).
#[test]
fn alt_column_widths_are_in_the_regions_unit() {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
a.session.system_region = wordcraft_engine::Region::from_tag("pt-BR");
a.run("insert.table", json!({"rows": 2, "cols": 3})).unwrap();
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_step_dt(0.25).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
a,
);
steps(&mut h, 2);
let a = cell(&mut h, 0, 0);
let y = a.y + a.h / 2.0;
let (start, end) = (screen(&mut h, a.right(), y), screen(&mut h, a.right() + 18.0, y));
h.event(egui::Event::PointerMoved(start));
h.app_frame();
button(&h, start, true);
h.app_frame();
h.event(egui::Event::PointerMoved(end));
h.event(egui::Event::ModifiersChanged(egui::Modifiers::ALT));
h.app_frame();
let layout = h.state_mut().session.layout();
let w = super::widths(h.state(), &h.ctx, &layout, 0);
let want = h.state().session.format_length(w[0].1);
assert!(want.ends_with(" cm") && want.contains(','), "{want}");
fn texts(s: &egui::Shape, out: &mut Vec<String>) {
match s {
egui::Shape::Text(t) => out.push(t.galley.text().to_string()),
egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)),
_ => {}
}
}
let mut shown = Vec::new();
h.output().shapes.iter().for_each(|s| texts(&s.shape, &mut shown));
assert!(shown.contains(&want), "{want} not among {shown:?}");
h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE));
button(&h, end, false);
h.app_frame();
}
/// Alt while a column border is dragged reports each column's width on the ruler, as it is
/// going to be (#7586).
#[test]
fn alt_shows_the_column_widths_while_dragging() {
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
app.run("insert.table", json!({"rows": 2, "cols": 3})).unwrap();
let layout = app.session.layout();
let cell_rect = |c| {
layout.pages[0]
.items
.iter()
.find_map(|it| match it {
wordcraft_layout::Placed::Cell { rect, row: 0, cell, .. } if *cell == c => Some(*rect),
_ => None,
})
.unwrap()
};
let (a, b) = (cell_rect(0), cell_rect(1));
let y = a.y + a.h / 2.0;
let target = table_resize::resize_target(&layout, &app.session.doc, 0, a.right(), y, 1.0).unwrap();
app.canvas.table_resize = Some(ResizeDrag { page: 0, from: (a.right(), y), to: (a.right() + 18.0, y), target, ruler: false });
let ctx = egui::Context::default();
assert!(super::widths(&app, &ctx, &layout, 0).is_empty(), "not without Alt");
ctx.input_mut(|i| i.modifiers = egui::Modifiers::ALT);
let w = super::widths(&app, &ctx, &layout, 0);
assert_eq!(w.len(), 3, "{w:?}");
assert!((w[0].1 - (a.w + 18.0)).abs() < 0.5 && (w[1].1 - (b.w - 18.0)).abs() < 0.5, "{w:?}");
app.canvas.table_resize = None;
assert!(super::widths(&app, &ctx, &layout, 0).is_empty(), "gone with the drag");
}
+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