Compare commits

..
Author SHA1 Message Date
autocraft-bot[bot] be5ef437e9 Merge main (f87e9cd6) into the pull request
There was one conflict, in the RTL table row of docs/layout-parity.md. I

There was one conflict, in the RTL table row of docs/layout-parity.md. I kept the pull request's new wording: cell margins stay on the sides they name, and only the left and right borders are mirrored. I also kept the sentence the default branch added about Latin text keeping its digits, spaces and punctuation in order in right-to-left text (#2150). No conflict markers remain anywhere in the tree. I didn't build or run tests, since the only file touched is a doc.
2026-12-02 19:34:57 +00:00
pakiat dfbeffd34a Merge commit 'c369c3a20befef8742f8913128cacd79002435d6' into m/6941
# Conflicts:
#	docs/layout-parity.md
2026-11-23 07:41:25 +07:00
pakiat 514a95b80f Merge commit '6ef13b2cc8a60e6391d7a5b92459ec47598d58a9' into m/6941
# Conflicts:
#	docs/gaps.md
2026-11-18 22:32:58 +07:00
pakiat 01b9ce4b81 Merge commit '22a73d9f2d10de6ee52780ab4a6019b864d9c598' into m/6941
# Conflicts:
#	docs/gaps.md
2026-11-18 06:09:07 +07:00
pakiatandClaude Opus 5.5 b946229d38 Tables: a right-to-left table keeps its cell margins on the sides they name
Measured in Word for Windows 16.0.20527 (modes 14 and 15): in a
w:bidiVisual table a cell's w:left margin stays on its left and w:right on
its right, the cell's (w:tcMar) and the table's (w:tblCellMar) alike, and
w:start/w:end the same. Only the cell's left and right borders are drawn
mirrored. WordCraft mirrored the margins as well, so text in a cell with
unequal margins started 6 to 18 pt off.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 21:20:23 +07:00
51 changed files with 133 additions and 1871 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
View File
@@ -745,15 +745,6 @@ fn main() -> eframe::Result {
}
let spool = Spool::new(host.jobs_shared().clone());
let mut app = WordApp::new(session, services(spool.clone(), intake, nightly)).with_host(host).with_settings(settings.clone());
// Drawn by the processor (WARP, llvmpipe; #2221), animations that follow the system stop.
if let Some(state) = &cc.wgpu_render_state {
let info = state.adapter.get_info();
let software = info.device_type == eframe::wgpu::DeviceType::Cpu;
if software {
log::warn!("graphics: drawing in software on {} ({:?}): animations that follow the system are off", info.name, info.backend);
}
app.set_software_drawing(software);
}
// PLAN: writer note 9 puts `with_settings` after `with_control`; it comes first here because
// the region check below reads the saved region the settings apply.
if std::env::var("WORDCRAFT_FILE_DIALOG").is_ok_and(|v| v.trim().eq_ignore_ascii_case("builtin")) {
+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)
+11 -21
View File
@@ -279,22 +279,6 @@ fn content_base(s: &Session, r: &ControlRange) -> CharProps {
content_props(&s.doc, &props)
}
/// The formatting of what replaces a control's content: typed text, a list entry, a date or a
/// check box's mark. In place of the placeholder, that is the control's own run properties
/// (ECMA-376 §17.5.2.27), else the content's formatting without the placeholder style: the
/// showing placeholder's own character style is that style, whatever a producer called it (Word
/// localizes only the id; another program may localize the name too). In place of a value, it is
/// that value's formatting.
fn replacement_props(s: &Session, r: &ControlRange) -> CharProps {
if !r.control.showing_placeholder {
return content_base(s, r);
}
match &r.control.run_props {
Some(rp) => content_props(&s.doc, rp),
None => CharProps { style: None, ..content_base(s, r) },
}
}
// ---------------------------------------------------------------------------------------------
// Rules for typing and deleting
@@ -343,8 +327,14 @@ pub fn prepare_edit(s: &mut Session) -> Result<Option<CharProps>, CmdError> {
if !r.control.showing_placeholder || !r.contains(&b) {
return Ok(None);
}
// Text typed in place of the placeholder takes the control's own run properties, as in Word.
let props = replacement_props(s, &r);
// Text typed in place of the placeholder takes the control's own run properties (Word, and
// ECMA-376 §17.5.2.27), else the content's formatting without the placeholder style. The
// showing placeholder's own character style is that style, whatever a producer called it
// (Word localizes only the id; another program may localize the name too).
let props = match &r.control.run_props {
Some(rp) => content_props(&s.doc, rp),
None => CharProps { style: None, ..content_base(s, &r) },
};
s.sel = Selection { anchor: r.content_start(), focus: r.end.clone() };
if let Some(c) = s.doc.control_mut(&r.start) {
c.showing_placeholder = false;
@@ -676,7 +666,7 @@ fn toggle_check_box(s: &mut Session, v: &Value) -> CmdResult {
}
let now = p::bool(v, "value").unwrap_or(!checked);
let (ch, font) = if now { (*checked_char, checked_font) } else { (*unchecked_char, unchecked_font) };
let mut props = replacement_props(s, &r);
let mut props = content_base(s, &r);
if !font.is_empty() {
props.font = Some(font.clone());
}
@@ -706,7 +696,7 @@ fn choose_item(s: &mut Session, v: &Value) -> CmdResult {
return Err(CmdError::Params("give index, value or text".into()));
};
let Some(item) = item.cloned() else { return Err(CmdError::Params("no such entry".into())) };
let props = replacement_props(s, &r);
let props = content_base(s, &r);
let end = set_content(s, &r, &item.display, &props)?;
if let Some(c) = s.doc.control_mut(&r.start) {
if let ControlKind::ComboBox { last_value, .. } | ControlKind::DropDown { last_value, .. } = &mut c.kind {
@@ -726,7 +716,7 @@ fn set_date(s: &mut Session, v: &Value) -> CmdResult {
}
let (y, m, d) = p::str(v, "date").and_then(parse_date).ok_or_else(|| CmdError::Params("date: YYYY-MM-DD".into()))?;
let text = format_date_value(format, y, m, d);
let props = replacement_props(s, &r);
let props = content_base(s, &r);
let end = set_content(s, &r, &text, &props)?;
if let Some(c) = s.doc.control_mut(&r.start) {
if let ControlKind::Date { full_date, .. } = &mut c.kind {
+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);
}
}
-100
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.
@@ -9877,9 +9806,6 @@ fn insert_icon_places_a_picture_of_the_requested_size_that_saves_and_recolours()
#[test]
fn markup_pdf_takes_the_track_changes_option_colours() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Governed by Kansas law."));
// A fixed creation date: without one each PDF is stamped with the current time, and the
// exports compared below differ when a clock second ticks over between them.
s.doc.core.created = "2026-01-01T00:00:00Z".into();
s.run("review.trackChanges", &json!({"value": true})).unwrap();
s.run("select.text", &json!({"text": "Kansas"})).unwrap();
s.run("text.insert", &json!({"text": "Missouri"})).unwrap();
@@ -15415,32 +15341,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"),
@@ -1,90 +0,0 @@
//! A value chosen in a content control in place of its placeholder (a list entry, a date, a check
//! box's mark) takes the control's own run properties (`w:sdtPr/w:rPr`, ECMA-376 Part 1
//! §17.5.2.27), as typed text does (#3116). Packages are hand-written: the controls WordCraft
//! inserts carry no run properties.
use serde_json::json;
use wordcraft_doc::StoryRef;
use wordcraft_doc::props::CharProps;
use wordcraft_engine::Session;
use wordcraft_engine::io::{open_bytes, save_bytes};
const W: &str =
r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml""#;
const RELS: &str = r#"xmlns="http://schemas.openxmlformats.org/package/2006/relationships""#;
const TYPE: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
/// Opens a package with `body` and a grey Placeholder Text character style.
fn open(body: &str) -> wordcraft_doc::Document {
let styles = r#"<w:style w:type="character" w:styleId="PlaceholderText"><w:name w:val="Placeholder Text"/><w:rPr><w:color w:val="808080"/></w:rPr></w:style>"#;
let mut zip = craft_zip::Writer::new();
for (name, value) in [
(
"_rels/.rels",
format!(r#"<Relationships {RELS}><Relationship Id="rId1" Type="{TYPE}/officeDocument" Target="word/document.xml"/></Relationships>"#),
),
(
"word/_rels/document.xml.rels",
format!(r#"<Relationships {RELS}><Relationship Id="rId1" Type="{TYPE}/styles" Target="styles.xml"/></Relationships>"#),
),
("word/document.xml", format!(r#"<w:document {W}><w:body>{body}</w:body></w:document>"#)),
("word/styles.xml", format!(r#"<w:styles {W}>{styles}</w:styles>"#)),
] {
zip.add(name, value.as_bytes(), craft_zip::Compression::Deflated).unwrap();
}
open_bytes("form.docx", &zip.finish().unwrap()).unwrap()
}
/// A paragraph holding a control of `kind` (its `w:sdtPr` type element) tagged `tag`. Its
/// placeholder is grey and boxed; its run properties ask for blue Source Serif 4 at 14 pt.
fn control(tag: &str, kind: &str) -> String {
let own = r#"<w:rPr><w:rFonts w:ascii="Source Serif 4" w:hAnsi="Source Serif 4"/><w:color w:val="1F4E79"/><w:sz w:val="28"/></w:rPr>"#;
let shown =
r#"<w:rPr><w:rStyle w:val="PlaceholderText"/><w:color w:val="808080"/><w:bdr w:val="single" w:sz="4" w:space="0" w:color="808080"/></w:rPr>"#;
format!(
r#"<w:p><w:sdt><w:sdtPr>{own}<w:tag w:val="{tag}"/><w:showingPlcHdr/>{kind}</w:sdtPr><w:sdtContent><w:r>{shown}<w:t>Choose</w:t></w:r></w:sdtContent></w:sdt></w:p>"#
)
}
/// The formatting of the control's first character, and the control's own run properties.
fn formatting(d: &wordcraft_doc::Document, tag: &str) -> (CharProps, CharProps) {
let r = d.control_ranges(StoryRef::Body).into_iter().find(|r| r.control.tag == tag).unwrap();
let at = r.content_start();
(d.para_at(&at).unwrap().props_of_char(at.off).clone(), r.control.run_props.clone().unwrap())
}
/// What shows of a run's formatting here: colour, font, size and box.
fn look(p: &CharProps) -> impl PartialEq + std::fmt::Debug {
(p.color, p.font.clone(), p.size, p.border)
}
/// A list entry, a date or a check box's mark chosen in place of the placeholder takes the
/// control's run properties, as typed text does; it kept the placeholder's grey and box. A saved
/// file keeps the value's formatting.
#[test]
fn choosing_over_a_placeholder_takes_the_controls_formatting() {
let entries = r#"<w:listItem w:displayText="Small" w:value="S"/><w:listItem w:displayText="Large" w:value="L"/>"#;
let choices = [
("size", format!("<w:dropDownList>{entries}</w:dropDownList>"), "developer.chooseItem", json!({"control": "size", "index": 1})),
(
"due",
r#"<w:date><w:dateFormat w:val="d MMMM yyyy"/></w:date>"#.into(),
"developer.setDate",
json!({"control": "due", "date": "2026-12-01"}),
),
("ok", r#"<w14:checkbox><w14:checked w14:val="0"/></w14:checkbox>"#.into(), "developer.toggleCheckBox", json!({"control": "ok"})),
];
let body: String = choices.iter().map(|(tag, kind, ..)| control(tag, kind)).collect();
let mut s = Session::new(open(&body));
for (tag, _, command, params) in &choices {
let (placeholder, own) = formatting(&s.doc, tag);
assert_ne!(look(&placeholder), look(&own), "{tag}: the placeholder is formatted apart from its control");
s.run(command, params).unwrap_or_else(|e| panic!("{command}: {e}"));
assert_eq!(look(&formatting(&s.doc, tag).0), look(&own), "{tag}: {command} gives the control's run properties");
}
let saved = open_bytes("form.docx", &save_bytes("form.docx", &s.doc).unwrap()).unwrap();
for (tag, ..) in &choices {
let (value, own) = formatting(&saved, tag);
assert_eq!(look(&value), look(&own), "{tag}: the saved value keeps the control's run properties");
}
}
-1
View File
@@ -1,5 +1,4 @@
mod comment_ids;
mod content_controls;
mod date_fields;
mod macro_packages;
mod odt_charts;
+2 -8
View File
@@ -521,18 +521,12 @@ fn fill_headers_footers(
None
}
/// Evict paragraph layouts that weren't used this pass if the cache accumulated too many stale entries.
/// Evict paragraph layouts that weren't used this pass if the cache grew large.
fn evict_unused(cache: &mut LayoutCache) {
if cache.paras.len() + cache.measures.len() > cache.used.len() + cache.used.len().clamp(512, 1024) {
if cache.paras.len() + cache.measures.len() > 4 * cache.used.len().max(1024) {
let used = std::mem::take(&mut cache.used);
cache.paras.retain(|k, _| used.contains(k));
cache.measures.retain(|k, _| used.contains(k));
if cache.paras.capacity() > cache.paras.len().max(512) * 4 {
cache.paras.shrink_to(cache.paras.len() * 2);
}
if cache.measures.capacity() > cache.measures.len().max(256) * 4 {
cache.measures.shrink_to(cache.measures.len() * 2);
}
cache.used = used;
}
}
+6 -5
View File
@@ -589,8 +589,7 @@ fn table_frame(ctx: &mut Ctx, t: &Table, avail: f32, depth: usize, style: Option
indent - first_cell_left_margin_in(t, margins_def)
};
// The reading view fits the table into what the start offset leaves of the column, mirrored or not (#7988).
// Keep at least half the fitted width so the position clamp can reduce an excessive indent (#8063).
let room = (avail - start_offset.max(0.0)).max(acc.min(avail) / 2.0).max(1.0);
let room = (avail - start_offset.max(0.0)).max(1.0);
if ctx.opts.view == ViewMode::Read && acc > room && !matches!(t.props.align, Some(Align::Center | Align::Right)) {
let k = room / acc;
colx.iter_mut().for_each(|c| *c *= k);
@@ -649,11 +648,13 @@ pub fn layout_table(ctx: &mut Ctx, story: StoryRef, t: &Table, path: &[u32], ava
let span = cell.span();
let x0 = colx.get(g).copied().unwrap_or(acc);
let x1 = colx.get((g + span).min(ncols)).copied().unwrap_or(acc);
// Right to left: grid columns run from the right edge, and the start (left) margin
// is on the cell's right.
// Right to left: grid columns run from the right edge. The margins stay on the sides
// they name: Word for Windows keeps a cell's `w:left` (or `w:start`) margin on its
// left in a right-to-left table, the cell's and the table's alike, though it draws the
// cell's `w:left` border on its right.
let (x0, x1) = if rtl { ((acc - x1).max(0.0), (acc - x0).max(0.0)) } else { (x0, x1) };
let m = cell.props.resolved_margins(margins_def);
let margins = if rtl { [row_top, m[3], row_bottom, m[1]] } else { [row_top, m[1], row_bottom, m[3]] };
let margins = [row_top, m[1], row_bottom, m[3]];
let cw = (x1 - x0 - margins[1] - margins[3]).max(4.0);
let region = region_of(t, style.as_ref(), ri, g, span, ncols);
// Conditional formatting, later parts winning (ECMA-376 §17.7.6): whole table, column
-53
View File
@@ -685,43 +685,6 @@ fn reading_layout_fits_a_wide_table_to_the_column() {
}
}
#[test]
fn reading_layout_preserves_table_width_with_an_excessive_indent() {
crate::test_fonts();
for rtl in [false, true] {
let frame = |indent, view| {
let mut doc = Document::from_text("Before.");
doc.settings.compat_mode = 15;
let mut table = Table::new(2, 4, 468.0);
table.props.fixed = true;
table.props.indent = Some(indent);
table.props.bidi_visual = rtl;
doc.insert_block(StoryRef::Body, &Path::top(1), Block::Table(table)).unwrap();
let opts = LayoutOptions { view, web_width: 360.0, read_height: 600.0, ..Default::default() };
let layout = layout(&doc, &mut LayoutCache::new(), &opts);
let page = &layout.pages[0];
let cells: Vec<_> = page.items.iter().filter_map(|item| if let Placed::Cell { rect, .. } = item { Some(*rect) } else { None }).collect();
assert_eq!(cells.len(), 8);
let (left, right) = cells.iter().fold((f32::INFINITY, f32::NEG_INFINITY), |(l, r), cell| (l.min(cell.x), r.max(cell.x + cell.w)));
let start = if rtl { page.body.x + page.body.w - right } else { left - page.body.x };
(start, right - left, page.body.w)
};
let (start, width, column) = frame(0.0, ViewMode::Read);
let (indented, _, _) = frame(36.0, ViewMode::Read);
assert!((indented - start - 36.0).abs() < 0.5, "ordinary indent is preserved");
for indent in [400.0, column - 12.0] {
let (start, fitted, _) = frame(indent, ViewMode::Read);
assert!(fitted + 0.5 >= width / 2.0, "rtl {rtl}, indent {indent}: table is only {fitted} pt wide vs {width} pt without indent");
assert!(start >= -0.5 && start + fitted <= column + 0.5, "table fits within the reading column");
assert!(start < indent, "reduce the indent to make space for the table");
}
let (print_start, print_width, _) = frame(0.0, ViewMode::Print);
let (print_indented, print_indented_width, _) = frame(400.0, ViewMode::Print);
assert!((print_indented - print_start - 400.0).abs() < 0.5, "print layout keeps the authored indent");
assert!((print_indented_width - print_width).abs() < 0.5, "print layout keeps the table width");
}
}
#[test]
fn hit_and_caret_agree() {
crate::test_fonts();
@@ -18287,19 +18250,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());
}
}
+6 -4
View File
@@ -564,7 +564,8 @@ fn inline_picture_in_rtl_text_sits_in_its_place() {
/// A right-to-left table (`w:bidiVisual`, #362): the first logical column stands at the right
/// edge, the table is start-aligned against the right margin, and each cell's start (left)
/// margin and border are drawn on its right. Clicks find cells by where they are drawn.
/// border is drawn on its right. Its left margin stays on its left, as Word for Windows lays it
/// out (`w:left` and `w:start` alike). Clicks find cells by where they are drawn.
#[test]
fn rtl_table_lays_its_columns_out_right_to_left() {
crate::test_fonts();
@@ -573,7 +574,7 @@ fn rtl_table_lays_its_columns_out_right_to_left() {
let mut d = Document::from_text("before\nafter");
let mut t = Table::new(1, 3, 300.0);
t.props.bidi_visual = true;
// Start margin 10pt, end margin 2pt.
// Left margin 10pt, right margin 2pt.
t.props.cell_margins = Some([0.0, 10.0, 0.0, 2.0]);
for (i, c) in t.rows[0].cells.iter_mut().enumerate() {
c.blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text(&format!("c{i}"), Default::default()))];
@@ -592,10 +593,11 @@ fn rtl_table_lays_its_columns_out_right_to_left() {
assert!(c0.x > c1.x && c1.x > c2.x, "{c0:?} {c1:?} {c2:?}");
assert!((c1.right() - c0.x).abs() < 0.01 && (c2.right() - c1.x).abs() < 0.01);
assert!((c2.x - (right - 300.0)).abs() < 2.0, "{c2:?}");
// The first cell's text sits its end margin (2pt) in from the cell's left edge.
// The first cell's text sits its left margin (10pt) in from the cell's left edge, not its
// right margin (2pt): Word doesn't mirror the margins (measured in Word for Windows).
let text_x =
items.iter().find_map(|i| if let Placed::Lines { path, x, .. } = i { (path.0 == [1, 0, 0, 0]).then_some(*x) } else { None }).unwrap();
assert!((text_x - (c0.x + 2.0)).abs() < 0.5, "text at {text_x}, cell {c0:?}");
assert!((text_x - (c0.x + 10.0)).abs() < 0.5, "text at {text_x}, cell {c0:?}");
// The thick start border is drawn on the cell's right edge.
let thick: Vec<f32> = items
.iter()
+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 -9
View File
@@ -120,7 +120,6 @@ impl WordApp {
control: None,
capture_token: 0,
native_scale: 1.0,
software_drawing: false,
auto_scale_limit: f32::INFINITY,
legacy_interface_size: None,
applied_editing: None,
@@ -215,18 +214,11 @@ impl WordApp {
.wheel_speed(WheelSpeed::new(line, point))
.alt_code_pages(AltCodePages::new(ansi, oem))
.set(ComponentSet::Productivity);
env.motion = self.ui.animations.motion_drawn(self.software_drawing);
env.motion = self.ui.animations.motion();
env.sizes = std::sync::Arc::clone(&APP_SIZES);
env
}
/// The window is drawn by the processor (`on`), as the desktop app finds once it knows the
/// graphics adapter. Animations that follow the system then stop: the caret blinks without
/// fading or gliding, and nothing fades, slides or spins. On in File › Options still animates.
pub fn set_software_drawing(&mut self, on: bool) {
self.software_drawing = on;
}
/// What this frame's mode and motion choices resolve to: the system's answer replaces `System`.
/// Before the first frame there is no context to ask, and the system reports nothing.
pub(crate) fn resolved_root(&self) -> ResolvedRoot {
+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);
}
-129
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]
@@ -2622,115 +2605,3 @@ fn the_caret_blinks_only_while_the_window_is_active() {
h.app_frame();
assert!(next_frame(&h) <= blink, "active again, the caret blinks again");
}
/// #5602: clicking a picture that is partly off the window's edge, or taller than a small
/// window, selects it without scrolling the view (the selection used to be followed like a
/// caret).
#[test]
fn clicking_a_picture_in_a_small_window_does_not_scroll_the_view() {
for width in [160, 700] {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
for i in 0..70 {
a.run("text.insert", json!({"text": format!("Line {i} of the body text")})).unwrap();
a.run("text.newParagraph", json!({})).unwrap();
}
a.run("view.commentsPane", json!({"value": false})).unwrap();
a.run("caret.docStart", json!({})).unwrap();
let img = image::RgbaImage::from_pixel(40, 20, image::Rgba([200, 30, 30, 255]));
let png = wordcraft_geom::picture::encode_format(&image::DynamicImage::ImageRgba8(img).clone(), image::ImageFormat::Png).unwrap();
a.run("insert.picture", json!({"data": wordcraft_engine::cmd::insert::base64_encode(&png), "width": width})).unwrap();
let pos = wordcraft_engine::cmd::objects::selected(&a.session).unwrap().0;
a.session.sel = wordcraft_engine::Selection::caret(Pos::body(3, 0));
let mut h = crate::test_harness::builder().with_size(egui::vec2(900.0, 420.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
a,
);
steps(&mut h, 6);
let rect = h.state_mut().session.layout().object(&pos, 0).expect("the picture is laid out").rect;
let corner = |h: &mut H, x: f32, y: f32| page_to_screen(h.state_mut(), 0, x, y).expect("the picture is on screen");
let view = h.state().canvas.view_rect().expect("the canvas has been shown");
// Scroll until the picture's top edge is above the window's: part of it is out of view.
let top = corner(&mut h, rect.x, rect.y).y;
h.state_mut().canvas.view.offset.1 += f64::from(top - view.top()) + 40.0;
steps(&mut h, 6);
let before = h.state().canvas.view.offset;
let (min, max) = (corner(&mut h, rect.x, rect.y), corner(&mut h, rect.x + rect.w, rect.y + rect.h));
let shown = egui::Rect::from_min_max(min, max);
assert!(shown.top() < view.top(), "{width}: the picture starts above the window: {shown:?} {view:?}");
let at = pos2(shown.center().x, shown.center().y.clamp(view.top() + 10.0, view.bottom() - 10.0));
assert!(shown.contains(at), "{width}: the click lands on the picture {shown:?} {view:?}");
h.event(egui::Event::PointerMoved(at));
h.app_frame();
for pressed in [true, false] {
h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() });
h.app_frame();
}
steps(&mut h, 10);
assert_eq!(wordcraft_engine::cmd::objects::selected(&h.state().session).map(|o| o.0), Some(pos), "{width}: the picture is selected");
assert_eq!(h.state().canvas.view.offset, before, "{width}: the view stayed where it was");
}
}
/// #5602: Shift-clicking a picture that is partly above the window's top edge adds it to the
/// selection without scrolling the view back to the picture selected first.
#[test]
fn shift_clicking_a_picture_does_not_scroll_the_view() {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
let img = image::RgbaImage::from_pixel(40, 20, image::Rgba([200, 30, 30, 255]));
let png = wordcraft_geom::picture::encode_format(&image::DynamicImage::ImageRgba8(img).clone(), image::ImageFormat::Png).unwrap();
let data = wordcraft_engine::cmd::insert::base64_encode(&png);
a.run("insert.picture", json!({"data": data, "width": 160})).unwrap();
let first = wordcraft_engine::cmd::objects::selected(&a.session).unwrap().0;
// The inserted picture is selected: a caret after it, or typing would replace it.
a.run("caret.docEnd", json!({})).unwrap();
for i in 0..10 {
a.run("text.insert", json!({"text": format!("Line {i} of the body text")})).unwrap();
a.run("text.newParagraph", json!({})).unwrap();
}
a.run("insert.picture", json!({"data": data, "width": 160})).unwrap();
let second = wordcraft_engine::cmd::objects::selected(&a.session).unwrap().0;
assert_ne!(first, second);
a.run("view.commentsPane", json!({"value": false})).unwrap();
let end = Pos { off: first.off + wordcraft_doc::para::OBJ.len_utf8(), ..first.clone() };
a.run("select.range", json!({"anchor": first, "focus": end})).unwrap();
let mut h = crate::test_harness::builder().with_size(egui::vec2(900.0, 420.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
a,
);
steps(&mut h, 6);
let rect = h.state_mut().session.layout().object(&second, 0).expect("the second picture is laid out").rect;
let corner = |h: &mut H, x: f32, y: f32| page_to_screen(h.state_mut(), 0, x, y).expect("the picture is on screen");
let view = h.state().canvas.view_rect().expect("the canvas has been shown");
// Scroll until the second picture's top edge is above the window's: part of it is out of view.
let top = corner(&mut h, rect.x, rect.y).y;
h.state_mut().canvas.view.offset.1 += f64::from(top - view.top()) + 20.0;
steps(&mut h, 6);
let before = h.state().canvas.view.offset;
let shown = egui::Rect::from_min_max(corner(&mut h, rect.x, rect.y), corner(&mut h, rect.x + rect.w, rect.y + rect.h));
assert!(shown.top() < view.top(), "the picture starts above the window: {shown:?} {view:?}");
let at = pos2(shown.center().x, shown.center().y.clamp(view.top() + 10.0, view.bottom() - 10.0));
assert!(shown.contains(at), "the click lands on the picture {shown:?} {view:?}");
assert_eq!(
wordcraft_engine::cmd::objects::picked_objects(&h.state().session),
vec![first.clone()],
"the first picture is selected before the click: {:?}",
h.state().session.sel
);
h.event(egui::Event::PointerMoved(at));
h.app_frame();
let press = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::SHIFT };
h.event_modifiers(press, egui::Modifiers::SHIFT);
h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() });
steps(&mut h, 10);
let picked = wordcraft_engine::cmd::objects::picked_objects(&h.state().session);
assert!(picked.contains(&first) && picked.contains(&second), "both pictures are selected: {picked:?} {:?} at {at:?}", h.state().session.sel);
assert_eq!(h.state().canvas.view.offset, before, "the view stayed where it was");
}
+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");
}
}
+3 -12
View File
@@ -269,21 +269,12 @@ impl WordForm for MergeRecordsForm {
})
});
self.choice = choice;
// Typing a number picks the range. One row, "[from] To: [to]": the From: radio captions the first box, the
// second needs its own (#7976).
let (from, to) = (self.from, self.to);
let (from, to) = ui
.horizontal(|ui| {
let from = NumberField::new(tl!("From:"), Bind::given(from)).show(ui).value().copied();
let to = labelled(ui, tl!("To:"), |name, ui| NumberField::new(name, Bind::given(to)).show(ui).value().copied()).flatten();
(from, to)
})
.inner;
if let Some(v) = from {
// Typing a number picks the range.
if let Some(v) = NumberField::new(tl!("From:"), Bind::given(self.from)).show(ui).value().copied() {
self.from = v;
self.choice = 2;
}
if let Some(v) = to {
if let Some(v) = NumberField::new(tl!("To:"), Bind::given(self.to)).show(ui).value().copied() {
self.to = v;
self.choice = 2;
}
-36
View File
@@ -73,15 +73,8 @@ fn note_global_names() {
});
}
/// Text egui itself draws over the app in debug builds, such as its warning that `request_discard`
/// was called several frames in a row. The app does not draw it, so it is not interface text.
fn egui_debug_text(text: &str) -> bool {
text.starts_with("egui PERF WARNING:")
}
fn texts(shape: &egui::Shape, out: &mut Vec<String>) {
match shape {
egui::Shape::Text(t) if egui_debug_text(t.galley.text()) => {}
egui::Shape::Text(t) => out.push(t.galley.text().to_string()),
egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)),
_ => {}
@@ -348,34 +341,6 @@ fn math_placeholders_are_exact_math_input_only() {
assert!(!set.contains("Translate"), "ordinary interface wording is not exempt");
}
#[test]
fn egui_debug_warnings_are_not_interface_text() {
// A discard in every pass makes egui draw its PERF WARNING from the fourth frame on.
let ctx = egui::Context::default();
let mut shapes = Vec::new();
for _ in 0..5 {
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| ui.ctx().request_discard("test"));
out.textures_delta.clear();
shapes = out.shapes;
}
let raw: Vec<String> = shapes
.iter()
.filter_map(|s| match &s.shape {
egui::Shape::Text(t) => Some(t.galley.text().to_string()),
_ => None,
})
.collect();
// egui draws the warning only in builds with `debug_assertions`.
if cfg!(debug_assertions) {
assert!(raw.iter().any(|t| t.starts_with("egui PERF WARNING:")), "egui draws its warning: {raw:?}");
}
let mut drawn = Vec::new();
for s in &shapes {
texts(&s.shape, &mut drawn);
}
assert!(drawn.is_empty(), "the audit reads no egui debug text: {drawn:?}");
}
/// Runtime data is exempt (links, the clock's dates and times), wording is not (#7463), and
/// Check for Updates never reaches the network.
#[test]
@@ -778,7 +743,6 @@ fn disabled_reasons() -> std::collections::BTreeSet<String> {
fn frame_at(ctx: &egui::Context, app: &mut WordApp, width: f32) -> Vec<(String, f32)> {
fn collect(shape: &egui::Shape, out: &mut Vec<(String, f32)>) {
match shape {
egui::Shape::Text(t) if egui_debug_text(t.galley.text()) => {}
egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.pos.x)),
egui::Shape::Vec(v) => v.iter().for_each(|s| collect(s, out)),
_ => {}
+1 -9
View File
@@ -527,14 +527,7 @@ pub(crate) fn show(ui: &mut Ui, app: &mut WordApp, ribbon: &RibbonOutput<String>
let ctx = ui.ctx().clone();
// Alt during an object drag is part of the drag (Alt moves an object freely), not a keytip tap.
// PLAN: `CanvasState::object_gesture` is canvas-w9's (cv.A10).
let mut enabled = app.ui.keytips_enabled && app.canvas.object_gesture().is_none();
let backstage_key = egui::Id::unique(("wc_backstage_keytips_active", app.windows.shown()));
let was_backstage_keytips: bool = ctx.data(|d| d.get_temp(backstage_key)).unwrap_or(false);
if was_backstage_keytips && !app.ui.backstage {
// #4981: the Backstage closed while its badges show (the back chevron, a mouse Save) ends them.
enabled = false;
}
let enabled = app.ui.keytips_enabled && app.canvas.object_gesture().is_none();
// A tab the ribbon shows has an element id this pass; one in the overflow menu has none and gets no badge.
// PLAN: assumed `RibbonOutput::tab_ids: Vec<(T, egui::Id)>` (ribbon-w3, S-L361).
@@ -586,7 +579,6 @@ pub(crate) fn show(ui: &mut Ui, app: &mut WordApp, ribbon: &RibbonOutput<String>
app.keytip_cache = Some(cache);
// PLAN: `WordApp::keytips_active` is app-hub's (rb.A11).
app.keytips_active = out.active;
ctx.data_mut(|d| d.insert_temp(backstage_key, app.ui.backstage && out.active));
if let Some(tab) = out.tab.as_deref().and_then(tab_of_badge) {
let _ = app.run("ui.tab", serde_json::json!({ "tab": tab }));
}
-29
View File
@@ -582,32 +582,3 @@ fn keytips_update_controls_when_switching_tabs() {
crate::test_harness::frames(&mut h, 3);
assert!(bold(&mut h), "Home keytip badge {bold_badge} runs format.bold after switching back from Insert");
}
/// #4981: the Backstage closed while its badges show (the back chevron, a mouse Save)
/// ends them. The next letter is typed, and never picks a page with the Backstage gone: C used
/// to close the document and S to save it.
#[test]
fn closing_the_backstage_ends_its_keytips() {
let mut h = harness(app());
let key = |key| key_event(key, true, egui::Modifiers::NONE);
h.input_mut().events.push(key(egui::Key::F10));
crate::test_harness::frame(&mut h);
assert!(h.state().keytips_active, "F10 activates keytips");
h.input_mut().events.extend([key(egui::Key::F), egui::Event::Text("f".into())]);
crate::test_harness::frames(&mut h, 2);
assert!(h.state().ui.backstage, "F opens Backstage");
assert!(h.state().keytips_active, "keytips active in Backstage");
// What the back chevron does.
h.state_mut().ui.backstage = false;
let ctx = h.ctx.clone();
h.state_mut().canvas.focus_page(&ctx);
crate::test_harness::frames(&mut h, 2);
assert!(!h.state().keytips_active, "the badges end with the Backstage");
h.input_mut().events.extend([key(egui::Key::C), egui::Event::Text("c".into())]);
crate::test_harness::frames(&mut h, 2);
assert!(!h.state().keytips_active);
assert!(h.state().has_document(), "C does not close the document");
assert!(!h.state().ui.backstage);
assert_eq!(h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body).trim(), "c", "C is typed");
}
-5
View File
@@ -458,11 +458,6 @@ pub struct WordApp {
/// The display scale (native pixels per point) seen in the last frame, 1.0 before the first;
/// `ui.interfaceSize` reports the size Auto draws at with it.
native_scale: f32,
/// The window is drawn by the processor, not a graphics card (WARP on Windows, llvmpipe on
/// Linux; #2221): the desktop app sets it once it knows the adapter. Every animated frame is
/// then the whole window drawn in software, so animations that follow the system stop
/// ([`WordApp::set_software_drawing`]).
software_drawing: bool,
/// The most pixels per point Auto may draw at on this screen ([`theme::auto_scale_limit`], #4030).
auto_scale_limit: f32,
/// A pre-#822 interface size (percent on top of the display scale) waiting for the first frame
+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");
}
}
+6 -10
View File
@@ -564,7 +564,7 @@ impl ObjectGesture {
|| (mods.cmd && mods.shift && wordcraft_engine::cmd::objects::picked_objects(&app.session).contains(&object.pos()));
let shift_only = mods.shift && !mods.cmd;
if adding && selected(app).is_some() && (shift_only || !again) {
let _ = app.run_keep_view("select.addObject", json!({"pos": object.pos()}));
let _ = app.run("select.addObject", json!({"pos": object.pos()}));
return Some(Self::inert());
}
// While editing a header/footer, a click on its Behind Text picture where no header/footer
@@ -582,8 +582,7 @@ impl ObjectGesture {
}
let pos = object.pos();
let end = Pos { off: pos.off + OBJ.len_utf8(), ..pos.clone() };
// Under the pointer, so in view: the selection is not followed like a caret (#5602).
let _ = app.run_keep_view("select.range", json!({"anchor": pos, "focus": end}));
let _ = app.run("select.range", json!({"anchor": pos, "focus": end}));
// A header/footer picture repeats on every page: select the copy clicked, as `select_at` does.
app.session.page_hint = object.page;
if selected(app).is_none() {
@@ -605,7 +604,7 @@ impl ObjectGesture {
if self.pending_behind {
let pos = object.pos();
let end = Pos { off: pos.off + OBJ.len_utf8(), ..pos.clone() };
let _ = app.run_keep_view("select.range", json!({"anchor": pos, "focus": end}));
let _ = app.run("select.range", json!({"anchor": pos, "focus": end}));
// The text click path has been tracking the pointer until it became a drag.
app.canvas.cancel_text_drag();
self.pending_behind = false;
@@ -759,8 +758,8 @@ fn press_member(app: &mut WordApp, layout: &DocLayout, body: &PageBody, at: Pos2
}
let pos = object.pos();
let end = Pos { off: pos.off + OBJ.len_utf8(), ..pos.clone() };
let _ = app.run_keep_view("select.range", json!({"anchor": pos, "focus": end}));
if app.run_keep_view("select.member", json!({"index": index})).is_err() {
let _ = app.run("select.range", json!({"anchor": pos, "focus": end}));
if app.run("select.member", json!({"index": index})).is_err() {
return Some(ObjectGesture::inert());
}
ObjectGesture::start(body, object, at)
@@ -912,10 +911,7 @@ pub fn select_at(app: &mut WordApp, layout: &DocLayout, body: &PageBody, at: Pos
// Already selected (alone or among several picked for Group): keep the selection.
if !wordcraft_engine::cmd::objects::picked_objects(&app.session).contains(&pos) {
let end = Pos { off: pos.off + OBJ.len_utf8(), ..pos.clone() };
// The object is under the pointer, so it is in view: following the new selection would
// scroll a picture taller than the window, or one partly off its edge, as it is clicked
// (#5602).
let _ = app.run_keep_view("select.range", json!({"anchor": pos, "focus": end}));
let _ = app.run("select.range", json!({"anchor": pos, "focus": end}));
}
// A header/footer picture repeats on every page: its frame belongs on the page clicked, not
// the one last edited.
+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(
-14
View File
@@ -221,20 +221,6 @@ fn animation_effects_is_an_accessibility_option() {
assert_eq!(system_help(&h), None, "only said while the system is followed");
}
/// #2221: a window drawn by the processor stops the animations that follow the system; On still plays.
#[test]
fn software_drawing_stops_animations_that_follow_the_system() {
use crate::theme::Animations;
use craft::behavior::MotionMode;
let mut a = app();
assert_eq!(a.ui.animations, Animations::System);
assert_ne!(a.resolved_root().motion, MotionMode::Off, "a graphics card animates");
a.set_software_drawing(true);
assert_eq!(a.resolved_root().motion, MotionMode::Off);
a.ui.animations = Animations::On;
assert_eq!(a.resolved_root().motion, MotionMode::Full, "the person's own choice stands");
}
/// #838: in a Polish region lengths read `2,54 cm` (the region's unit and decimal comma).
#[test]
fn length_fields_follow_the_region() {
+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()]);
}
}
+1 -1
View File
@@ -351,7 +351,7 @@ pub(super) fn home(row: &mut RibbonRow<'_>, app: &mut WordApp) {
Divider::horizontal().show(ui);
MenuItem::command(CommandRef::new("list.define")).label(tl!("Define New Multilevel List…").to_string()).show(ui);
Divider::horizontal().show(ui);
for lv in 0..9u64 {
for lv in 0..5u64 {
MenuItem::command(CommandRef::with_params("para.listLevel", json!({"level": lv})))
.label(format!("Change to Level {}", lv + 1))
.show(ui);
+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");
-6
View File
@@ -231,12 +231,6 @@ impl Animations {
}
}
/// [`Self::motion`] for a window drawn by the processor when `software`: `System` is then no
/// motion at all, since every animated frame is the whole window drawn in software (#2221).
pub fn motion_drawn(self, software: bool) -> MotionChoice {
if software && self == Animations::System { MotionChoice::Off } else { self.motion() }
}
/// The runtime's motion choice: `System` is the OS's reduced-motion answer, else full motion.
pub fn motion(self) -> MotionChoice {
match self {
+4 -83
View File
@@ -1,14 +1,10 @@
use std::path::Path;
use std::sync::Arc;
use craft::font_manager::Catalog;
use craft::font_manager::craft_font_catalog::{FontEnv, Limits, Os, Source};
use craft::font_manager::picker::FontPickerSettings;
use craft::font_manager::craft_font_catalog::{Limits, Source};
use craft::ui::buttons::IconButton;
use craft::ui::contract::{Bind, Props as _, Show as _};
use craft::ui::contract::{Props as _, Show as _};
use egui::Key;
use egui::accesskit::Role;
use egui::{Key, vec2};
use egui_kittest::kittest::{By, NodeT, Queryable};
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::{Value, json};
use wordcraft_engine::Session;
@@ -226,78 +222,3 @@ fn drawn_buttons_fade_in_on_hover_and_darken_while_pressed() {
let fill_after = find_button_fill(&h.output().shapes, rect);
assert_eq!(fill_after, None, "Save button must clear hover fill after unhovering");
}
/// #7317: typing in WordCraft's `font_picker` updates the popup list on the same frame as the
/// keystroke, shows the Recently Used Fonts section again when cleared, and narrows immediately
/// on subsequent typing.
#[test]
fn the_typed_list_shows_on_the_frame_of_the_keystroke() {
let env = FontEnv { os: Os::None, ..Default::default() };
let catalog = Arc::new(Catalog::new(env).with_font_service(false));
catalog.set_app_dirs(vec![Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts")]);
catalog.rescan();
assert!(catalog.families().iter().any(|f| f == "Inter"), "fixed catalog loaded assets/fonts");
let mut settings = FontPickerSettings::default();
settings.recent = vec!["Source Serif 4".to_string()];
let mut family = String::new();
let mut h = crate::test_harness::builder().with_size(vec2(400.0, 900.0)).build_ui(move |ui| {
let _ = super::font_picker("Font", Bind::bound(&mut family), &catalog, Bind::bound(&mut settings), &[], None).show(ui);
});
h.run_steps(2);
h.get(By::new().role(Role::TextInput)).click();
h.run_steps(2);
let erase = || {
vec![
egui::Event::Key { key: Key::Backspace, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE },
egui::Event::Key { key: Key::Backspace, physical_key: None, pressed: false, repeat: false, modifiers: egui::Modifiers::NONE },
]
};
let send = |h: &mut egui_kittest::Harness<'static, ()>, events: Vec<egui::Event>| {
for ev in events {
h.event(ev);
}
h.step();
};
let frames: [(Vec<egui::Event>, &[&str], &[&str]); 7] = [
// Typing an unmatched query clears the list; one Backspace restores recents + all fonts on that frame.
(vec![egui::Event::Text("x".into())], &[], &["Source Serif 4", "Inter", "JetBrains Mono"]),
(erase(), &["Source Serif 4", "Inter", "JetBrains Mono"], &[]),
// Typing narrows immediately on the keystroke frame and excludes non-matching families.
(vec![egui::Event::Text("jet".into())], &["JetBrains Mono"], &["Inter", "Source Serif 4"]),
(erase(), &["JetBrains Mono"], &["Inter"]),
(erase(), &["JetBrains Mono"], &["Inter"]),
(erase(), &["Source Serif 4", "Inter", "JetBrains Mono"], &[]),
(vec![egui::Event::Text("int".into())], &["Inter"], &["JetBrains Mono"]),
];
fn collect_texts(shape: &egui::Shape, out: &mut Vec<String>) {
match shape {
egui::Shape::Vec(children) => {
for child in children {
collect_texts(child, out);
}
}
egui::Shape::Text(text) => out.push(text.galley.text().to_owned()),
_ => {}
}
}
for (n, (events, expected, excluded)) in frames.into_iter().enumerate() {
send(&mut h, events);
let mut texts = Vec::new();
for clipped in &h.output().shapes {
collect_texts(&clipped.shape, &mut texts);
}
for label in expected {
assert!(texts.iter().any(|t| t == label), "keystroke {n}: expected {label:?} to be drawn on the frame, got texts: {texts:?}");
}
for label in excluded {
assert!(texts.iter().all(|t| t != label), "keystroke {n}: expected {label:?} to be filtered out on the frame, got texts: {texts:?}");
}
}
}
-1
View File
@@ -168,7 +168,6 @@ impl WordApp {
ime_origin: _,
user_origin: _,
native_scale: _,
software_drawing: _,
auto_scale_limit: _,
legacy_interface_size: _,
applied_editing: _,
+1 -28
View File
@@ -211,13 +211,8 @@ pub fn poll(app: &mut WordApp, ctx: &egui::Context) {
}
match r {
Ok(o) => {
let first_err = o.errors.first().cloned();
app.zotero.last = Some(json!({"command": name, "completed": o.completed, "calls": o.calls, "errors": o.errors}));
if let Some(err) = first_err {
app.status(format!("{}: {err}", tl!("Zotero")));
} else {
app.status(if o.completed { tl!("Zotero: done") } else { tl!("Zotero: cancelled") });
}
app.status(if o.completed { tl!("Zotero: done") } else { tl!("Zotero: cancelled") });
}
Err(e) => {
app.zotero.last = Some(json!({"command": name, "error": e}));
@@ -391,26 +386,4 @@ mod tests {
let last = status["last"].clone();
assert!(last["error"].as_str().is_some_and(|e| !e.is_empty()), "{last}");
}
#[test]
fn failed_bridge_call_surfaces_error_in_status() {
let (addr, server) = fake_zotero(vec![
json!(["Application_getActiveDocument", [3]]),
json!(["Field_setText", [1, 999, "text", false]]),
json!(["Document_complete", [1]]),
]);
let mut app = WordApp::new(Session::new(Document::from_text("Hello")), Services::default());
app.zotero.options.addr = addr;
let ctx = egui::Context::default();
app.run("ui.zotero.addEditBibliography", json!({})).unwrap();
pump(&mut app, &ctx, |a| a.zotero.busy.is_none());
server.join().unwrap();
let last = app.run("ui.zotero.status", json!({})).unwrap()["last"].clone();
assert_eq!(last["errors"].as_array().map(Vec::len), Some(1));
assert!(
app.status.as_ref().is_some_and(|s| s.text.contains("no field with id 999")),
"status was {:?}",
app.status.as_ref().map(|s| &s.text)
);
}
}
-32
View File
@@ -630,35 +630,3 @@ fn citation_at_document_end_stays_closed() {
let back = wordcraft_engine::io::open_bytes("probe.docx", &bytes).unwrap();
assert_eq!(back.field_ranges(StoryRef::Body).len(), 1);
}
#[test]
fn note_style_bibliography_populates_after_switching_citations_to_footnotes() {
let mut z = Z::new("Claim one.\n\nBibliography:\n", 9);
z.begin();
let cite = z.cite(0, "(Doe 2020)");
z.ok("Document_complete", json!([1]));
// Switch to a notes-and-bibliography style (e.g. Chicago 18th): citation moves to a footnote.
z.begin();
z.ok("Document_convert", json!([1, [cite], ["ReferenceMark"], [1], 1]));
z.ok("Document_complete", json!([1]));
assert_eq!(note_count(&z.s.doc, wordcraft_doc::PartKind::Footnote), 1);
// Place the caret at the end of the body and insert the bibliography.
let last_path = z.s.doc.para_paths(StoryRef::Body).pop().unwrap();
z.s.sel = Selection::caret(Pos::new(StoryRef::Body, last_path, 0));
z.begin();
let r = z.ok("Document_insertField", json!([1, "ReferenceMark", 0]));
let bib_id = r[0].as_u64().unwrap();
z.ok("Field_setCode", json!([1, bib_id, "TEMP"]));
assert!(!z.ok("Field_getText", json!([1, bib_id])).as_str().unwrap().is_empty());
z.ok("Field_setCode", json!([1, bib_id, BIBL]));
z.ok("Document_setBibliographyStyle", json!([1, -720, 720, 240, 240, [], 0]));
z.ok("Field_setText", json!([1, bib_id, r"{\rtf Doe, John. {\i Title}. 2020.\par}", true]));
z.ok("Document_complete", json!([1]));
assert!(z.text().contains("Doe, John. Title. 2020."), "body was {:?}", z.text());
let f = z.ok("Document_getFields", json!([1, "ReferenceMark"]));
assert_eq!(f[0], json!([cite, bib_id]));
assert_eq!(f[2], json!([1, 0]));
}
+1
View File
@@ -231,6 +231,7 @@ Page Setup's margin, paper-size and document-grid number boxes scroll long text
| 2026-10-31 | trivial | dialogs are dialogs to screen readers, their tabs are tabs, the one shown selected, and colour fields and swatches say their colour |
| 2026-11-01 | trivial | formatting shortcuts say what they did to screen readers |
| 2026-10-30 | trivial | the Paste button is named "Paste" for screen readers, without macOS's key on other platforms; the status bar's Go To hint shows the platform's key |
| 2026-11-17 | trivial | Right-to-left tables (`w:bidiVisual`): a cell's `w:left` and `w:right` margins (or `w:start` and `w:end`, the cell's or the table's) stay on the sides they name, as measured in Word for Windows; only the left and right borders are drawn mirrored; no ranked gap changed |
| 2026-10-30 | trivial | #5: a list item deleted whole under Track Changes shows its number as deleted text, in the deletion's colour and mark, and hides it where deletions are hidden (#4828); estimate unchanged |
| 2026-11-03 | trivial | A picture inserted or pasted in a table cell fits the cell (a nested cell too), in text columns the column, in another section that section, instead of the first section's text width (#5428); a fix, so no ranked gap changed; readiness estimates unchanged |
| 2026-10-26 | trivial | Dialog sections improve readability across 13 dialogs; conditional scrolling keeps tall dialogs usable. Ranked gaps and estimates unchanged (#4035, #4038) |
+2 -1
View File
@@ -95,7 +95,7 @@ Exact line spacing keeps the run font baseline around tall equations; automatic
| Document grid (`w:docGrid`, lines per page, characters per line) | 🟡 | #391, #401: line grid snaps line heights to whole pitches (text centred in them; `w:snapToGrid` off opts a paragraph out); character grid puts East Asian characters on the character pitch (`linesAndChars`) or all text (`snapToChars`), Latin text proportional; View › Gridlines draws it. Not yet: run-level `w:snapToGrid`, grid in headers/footers, paragraph spacing in grid lines, Word's exact glyph placement in a cell | 1–2 |
| Ruby / phonetic guide, enclose characters, combined characters | 🟡 | ruby (Phonetic Guide) landed (#288): ruby text over its base by alignment, line grows to fit, in PDF; enclose and combined characters missing; ruby not yet compared with Word page by page | 2–4 |
| Automatic space between Asian text and Latin text or digits (`w:autoSpaceDE`, `w:autoSpaceDN`) | 🟡 | #2358: a quarter of the Asian character's font size after the first of two touching characters, across runs (measured on Word's PDF of a Chinese document at 16 pt, as JIS X 4051 asks); not beside East Asian punctuation, Hangul, Latin punctuation or an existing space; a field is classed by the text it shows; none at a line's end, none on a character grid the paragraph snaps to (`layout::tests::autospace`). Not yet: justification widening the space as Word does, `autoSpaceLikeWord95` | 1–2 |
| Bidirectional paragraphs, mixed-direction lines; RTL tables and sections | 🟡 | #207; RTL tables (#362): grid columns from the right edge, start alignment and indent from the right margin, cell margins and left/right borders mirrored, merged and turned cells and nested tables included; RTL sections (#362): newspaper columns right to left with the line between mirrored. Latin text keeps its digits, spaces and punctuation in order inside right-to-left text (#2150). Right-hand page gutter (`w:rtlGutter`) missing | 1 |
| Bidirectional paragraphs, mixed-direction lines; RTL tables and sections | 🟡 | #207; RTL tables (#362): grid columns from the right edge, start alignment and indent from the right margin, left/right borders mirrored while cell margins stay on the sides they name (measured in Word for Windows), merged and turned cells and nested tables included; RTL sections (#362): newspaper columns right to left with the line between mirrored. Latin text keeps its digits, spaces and punctuation in order inside right-to-left text (#2150). Right-hand page gutter (`w:rtlGutter`) missing | 1 |
| Equations: display layout, numbering, wrapping long display equations | ✅ | #191; long display equations break at top-level operators (`m:brkBin`, `m:brkBinSub`), manual breaks and `m:alnAt`, continuation lines indented by `m:wrapIndent` or set right (`m:wrapRight`) (#326); an n-ary operator, delimiter, accent or group character the math font lacks is drawn from a fallback font instead of a missing-glyph box (#1273); an equation-array row without `&` is centred among aligned rows, as in Word (#2617) | — |
| Hidden text excluded from breaking and hyphenation | ✅ | #173 | — |
| Empty paragraph with a hidden mark (`w:pPr/w:rPr/w:vanish`) | ✅ | Synthetic DOCX observed in Word for Windows 16.0.20527: no room, no list number, and the number is still counted (`1.`, hidden item, `3.`), in the body and in table cells. `layout::tests::empty_list_paragraph_with_a_hidden_mark_counts_but_shows_nothing`, #3982. Not observed in Word: when such a paragraph closes a section before a continuous one and holds only an in-line picture (or a note reference, or a legacy check box), the picture keeps its room and the next section starts below it instead of over it (`a_hidden_mark_with_an_inline_picture_keeps_its_room`, #5288). A paragraph with text and a hidden mark shown together with the next one (Word) is #3986 | - |
@@ -329,6 +329,7 @@ The front-of-text opt-out is retained from the earlier implementation; this patc
| Date | Change | Summary |
|---|---|---|
| 2026-11-15 | trivial | A paragraph that starts a table cell's part of a page, in a row split across pages (the row continues from the page before, or starts the page, also under repeated header rows and in a nested table), can split even when only one line fits: a lone first line stays, a three-line paragraph with room for two splits two and one, and a lone continuation line stays, instead of keeping nothing so that the row ran off the bottom of the page. A non-exact row marked Can't Split that is taller than a page goes to a new page first when it starts below text, then splits where the page ends, instead of running off it (#6823; measured with synthetic documents in Word for Windows 16.0, compatibility mode 15, widow control on; `layout::tests::table_first_line`). A paragraph below other content of its cell, or in a row that starts below other content of the page, keeps the widow/orphan rule, which matched Word there. Not matched: Word leaves the repeated header off some pages of such a row (observed, no rule found), WordCraft repeats it on every page |
| 2026-11-17 | trivial | Right-to-left tables (`w:bidiVisual`): a cell's `w:left` and `w:right` margins (or `w:start` and `w:end`, the cell's or the table's) stay on the sides they name, as measured in Word for Windows; only the left and right borders are drawn mirrored |
| 2026-10-29 | trivial | A list item deleted whole under Track Changes shows its number in the deletion's colour and with its mark (struck through by default) with markup, and not at all without (#4828) |
| 2026-11-11 | trivial | The line a paragraph shares with the one before, whose mark is hidden, shows that one's shading and borders: the next paragraph's shading and borders no longer cover the text before it and start on its own next line, and what follows the shared line starts below the first one's bottom border. The joined copy keeps the paragraph's revision, so the word being typed in it gets no squiggle and its layouts are reused between passes (#3986) |
| 2026-10-29 | trivial | A paragraph whose mark is hidden is shown on one line with the next one, as in Word: the next paragraph's first line goes on beside its text, on its baseline, without a space before or a list number (still counted), in the body and in table cells, headers and text boxes; clicks on the joined text land in the paragraph it belongs to; a first word that doesn't fit goes on the next line at the paragraph's left indent, and a paragraph moved on to the next column or page is laid out on its own there; the shared line has one line number and stays one block for justified vertical alignment (#3986) |
+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