mirror of
https://github.com/storytold/wordcraft.git
synced 2026-12-02 22:30:10 +00:00
Compare commits
73
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b741bbac9a | ||
|
|
fd948e2015 | ||
|
|
612e92e6c5 | ||
|
|
5ae937d8e3 | ||
|
|
c07395d712 | ||
|
|
2f16864552 | ||
|
|
1b9b8b1bf3 | ||
|
|
ea5d48b18c | ||
|
|
03b54b043f | ||
|
|
48e07fbcd1 | ||
|
|
28d2dac6fd | ||
|
|
481eb1e79b | ||
|
|
4b5ad59b01 | ||
|
|
f22123dbaf | ||
|
|
df475fac83 | ||
|
|
72e54545d8 | ||
|
|
209db57e2c | ||
|
|
e862c6ad51 | ||
|
|
c2f7c65e9c | ||
|
|
678e813ec4 | ||
|
|
1f682738fd | ||
|
|
647e726179 | ||
|
|
6b8f63e207 | ||
|
|
2b30b235d8 | ||
|
|
423c58523d | ||
|
|
e076e47529 | ||
|
|
f87e9cd6ba | ||
|
|
3035dda6d4 | ||
|
|
8d9eb6fc0f | ||
|
|
6b0c47d2a8 | ||
|
|
93abd12f9f | ||
|
|
3820b9b206 | ||
|
|
e874c67147 | ||
|
|
605df8c165 | ||
|
|
8d7ed624ec | ||
|
|
fd81fadba7 | ||
|
|
17ae08d4b8 | ||
|
|
8edbfcdeef | ||
|
|
0f30f776bb | ||
|
|
19947b9170 | ||
|
|
3de53ecf4e | ||
|
|
faec3ecbde | ||
|
|
5945ca3cae | ||
|
|
14111658d1 | ||
|
|
eeac0d3322 | ||
|
|
e129211603 | ||
|
|
91a52f278c | ||
|
|
80c5151ab3 | ||
|
|
b4b41e038d | ||
|
|
6637fb7bbf | ||
|
|
5e8c7cb7cb | ||
|
|
2c08518c6f | ||
|
|
4a4b37c255 | ||
|
|
6078524793 | ||
|
|
d729387c8c | ||
|
|
c7b21e5d02 | ||
|
|
273d2ed225 | ||
|
|
bdf3c54189 | ||
|
|
6a445b341a | ||
|
|
958dd78ceb | ||
|
|
0b7bdee856 | ||
|
|
8be58e3a21 | ||
|
|
488f75b6e0 | ||
|
|
dd3d3040ac | ||
|
|
03da178335 | ||
|
|
8ee16cc876 | ||
|
|
b1958ac483 | ||
|
|
741d74b3fa | ||
|
|
b92b7a40ad | ||
|
|
5c9c343e46 | ||
|
|
37caf16978 | ||
|
|
6e783bdc6e | ||
|
|
aea58b38b8 |
@@ -36,9 +36,11 @@ USAGE:
|
||||
page can't be drawn or a picture is missing or undecodable
|
||||
(report on stderr, as for convert --strict)
|
||||
wordcraft-cli run [--file F | --template T] [--script FILE|-] [--cmd 'id={json}' …]
|
||||
[--save OUT] [--page N] [--scale S] [--print] [--author NAME]
|
||||
[--save OUT …] [--page N] [--scale S] [--print] [--author NAME]
|
||||
run commands headlessly, then save (--author names
|
||||
who tracked changes and comments are by).
|
||||
Repeat --save OUT to write multiple outputs in order,
|
||||
after any outputs from --script.
|
||||
PNG saves use --page (1-based, default 1) and --scale (default 2).
|
||||
--script runs a JSON file (- is stdin) first:
|
||||
{\"file\"?, \"template\"?, \"commands\": [{\"command\": id,
|
||||
@@ -632,6 +634,13 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
}
|
||||
}
|
||||
validate_options("run", &rest, RUN_OPTIONS)?;
|
||||
let mut cli_outputs = Vec::new();
|
||||
for (i, arg) in rest.iter().enumerate() {
|
||||
if arg == "--save" {
|
||||
let path = rest.get(i + 1).filter(|value| !value.is_empty() && !value.starts_with("--")).ok_or("run: --save requires a path")?;
|
||||
cli_outputs.push(path.clone());
|
||||
}
|
||||
}
|
||||
let page = parse_page_arg("run", &rest)?;
|
||||
let scale = parse_scale_arg("run", &rest)?;
|
||||
let password = password_from(&rest)?;
|
||||
@@ -680,7 +689,7 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
let outputs: Vec<String> = script.iter().flat_map(|c| c.save.iter().cloned()).chain(arg_value(&rest, "--save")).collect();
|
||||
let outputs: Vec<String> = script.iter().flat_map(|c| c.save.iter().cloned()).chain(cli_outputs).collect();
|
||||
// Check every output can be made before writing any, so a bad one leaves no half-done job.
|
||||
for out in &outputs {
|
||||
let parent = Path::new(out).parent().filter(|p| !p.as_os_str().is_empty());
|
||||
|
||||
@@ -564,6 +564,64 @@ fn script_builds_a_document_and_saves_docx_and_pdf_relative_to_the_script() {
|
||||
assert!(json.contains("Hello script") && json.contains("\"bold\":true"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_saves_each_cli_output_and_still_accepts_a_single_save() {
|
||||
let dir = script_dir("cli-saves");
|
||||
let input = dir.join("in.docx");
|
||||
let docx = dir.join("out.docx");
|
||||
let pdf = dir.join("out.pdf");
|
||||
run(&args(&["run", "--template", "sample", "--save", &input.to_string_lossy()])).unwrap();
|
||||
run(&args(&["run", "--file", &input.to_string_lossy(), "--save", &docx.to_string_lossy(), "--save", &pdf.to_string_lossy()])).unwrap();
|
||||
assert_eq!(listed_text(&open(&docx, None).unwrap().doc).unwrap(), listed_text(&open(&input, None).unwrap().doc).unwrap());
|
||||
assert!(std::fs::read(pdf).unwrap().starts_with(b"%PDF"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_saves_script_and_cli_outputs() {
|
||||
let dir = script_dir("mixed-saves");
|
||||
let script = write_script(&dir, r#"{"commands":["caret.docEnd"],"save":["script.txt","script.docx"]}"#);
|
||||
let first = dir.join("cli.txt");
|
||||
let second = dir.join("cli.docx");
|
||||
run(&args(&["run", "--save", &first.to_string_lossy(), "--script", &script, "--save", &second.to_string_lossy()])).unwrap();
|
||||
for path in [dir.join("script.txt"), dir.join("script.docx"), first, second] {
|
||||
assert!(path.is_file(), "{} was not written", path.display());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_rejects_a_missing_second_save_path_before_writing() {
|
||||
let dir = script_dir("missing-save");
|
||||
let first = dir.join("first.docx");
|
||||
let first_path = first.to_string_lossy();
|
||||
for tail in [vec!["--save"], vec!["--save", "--print"], vec!["--save", ""]] {
|
||||
let mut argv: Vec<&str> = vec!["run", "--save", &first_path];
|
||||
argv.extend(tail);
|
||||
assert_eq!(run(&args(&argv)), Err("run: --save requires a path".into()));
|
||||
assert!(!first.exists());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_preflights_script_and_cli_outputs_in_order_before_writing() {
|
||||
let dir = script_dir("preflight-saves");
|
||||
let first = dir.join("first.docx");
|
||||
let invalid = dir.join("missing/later.docx");
|
||||
let last = dir.join("missing-too/last.docx");
|
||||
let mut script = write_script(&dir, r#"{"commands":["caret.docEnd"],"save":["missing-script/script.docx"]}"#);
|
||||
let first_path = first.to_string_lossy();
|
||||
let invalid_path = invalid.to_string_lossy();
|
||||
let last_path = last.to_string_lossy();
|
||||
let argv = |script: &str| args(&["run", "--save", &first_path, "--save", &invalid_path, "--script", script, "--save", &last_path]);
|
||||
let err = run(&argv(&script)).unwrap_err().to_string();
|
||||
assert!(err.contains("script.docx"), "{err}");
|
||||
assert!(!first.exists());
|
||||
|
||||
script = write_script(&dir, r#"{"commands":["caret.docEnd"],"save":["script.docx"]}"#);
|
||||
let err = run(&argv(&script)).unwrap_err().to_string();
|
||||
assert!(err.contains("later.docx"), "{err}");
|
||||
assert!(!first.exists() && !dir.join("script.docx").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_with_a_bad_output_writes_no_output() {
|
||||
let dir = script_dir("badout");
|
||||
|
||||
@@ -745,6 +745,15 @@ 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")) {
|
||||
|
||||
@@ -21,26 +21,32 @@ 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> {
|
||||
if let Some(path) = CHOSEN.get() {
|
||||
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 {
|
||||
return Some(path.clone());
|
||||
}
|
||||
if let Some(path) = std::env::var_os("WORDCRAFT_PROFILE_DIR").filter(|p| !p.is_empty()) {
|
||||
if let Some(path) = env("WORDCRAFT_PROFILE_DIR").filter(|p| !p.is_empty()) {
|
||||
return Some(PathBuf::from(path));
|
||||
}
|
||||
platform_settings_dir()
|
||||
platform_settings_dir_for(env)
|
||||
}
|
||||
|
||||
/// 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") {
|
||||
std::env::var_os("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/WordCraft"))
|
||||
env("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/WordCraft"))
|
||||
} else if cfg!(windows) {
|
||||
std::env::var_os("APPDATA").map(|a| PathBuf::from(a).join("WordCraft"))
|
||||
env("APPDATA").map(|a| PathBuf::from(a).join("WordCraft"))
|
||||
} else {
|
||||
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"))
|
||||
env("XDG_CONFIG_HOME").map(PathBuf::from).or_else(|| env("HOME").map(|h| PathBuf::from(h).join(".config"))).map(|c| c.join("wordcraft"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,4 +115,26 @@ 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));
|
||||
}
|
||||
}
|
||||
|
||||
+52
-3
@@ -230,10 +230,26 @@ impl ChartAxis {
|
||||
pub const MAX_FMT: usize = 128;
|
||||
|
||||
/// A number format code: control characters as spaces, ends trimmed, at most [`MAX_FMT`]
|
||||
/// characters.
|
||||
/// characters. A trailing space stays when it is part of the code: the character after `_`,
|
||||
/// `*` or `\`, or text inside quotes.
|
||||
pub fn clean_fmt(s: &str) -> String {
|
||||
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()
|
||||
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()
|
||||
}
|
||||
|
||||
/// A chart WordCraft can edit.
|
||||
@@ -512,4 +528,37 @@ 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_ "));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -300,7 +300,11 @@ fn page(s: &mut Session, v: &Value, dir: i32) -> CmdResult {
|
||||
}
|
||||
let Some(c) = l.caret_on(&from, s.page_hint) else { return sel_result(s) };
|
||||
let np = if dir < 0 { c.page.saturating_sub(1) } else { (c.page + 1).min(l.pages.len().saturating_sub(1)) };
|
||||
let to = l.hit(np, c.x, c.top + 1.0, from.story).unwrap_or(from);
|
||||
let to = if np == c.page {
|
||||
if dir < 0 { s.doc.start_of(from.story) } else { s.doc.end_of(from.story) }
|
||||
} else {
|
||||
l.hit(np, c.x, c.top + 1.0, from.story).unwrap_or(from)
|
||||
};
|
||||
s.page_hint = np;
|
||||
apply(s, to, ext);
|
||||
sel_result(s)
|
||||
|
||||
@@ -279,6 +279,22 @@ 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
|
||||
|
||||
@@ -327,14 +343,8 @@ 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 (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) },
|
||||
};
|
||||
// Text typed in place of the placeholder takes the control's own run properties, as in Word.
|
||||
let props = replacement_props(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;
|
||||
@@ -666,7 +676,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 = content_base(s, &r);
|
||||
let mut props = replacement_props(s, &r);
|
||||
if !font.is_empty() {
|
||||
props.font = Some(font.clone());
|
||||
}
|
||||
@@ -696,7 +706,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 = content_base(s, &r);
|
||||
let props = replacement_props(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 {
|
||||
@@ -716,7 +726,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 = content_base(s, &r);
|
||||
let props = replacement_props(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 {
|
||||
|
||||
@@ -351,16 +351,6 @@ fn resolved(s: &Session) -> Vec<ResolvedChar> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether a toggle without a `value` turns its format on. A selection follows its first character
|
||||
/// in document order, as Word does: one that starts formatted loses the format, all of it (#6516).
|
||||
fn turns_on(s: &Session, has: impl Fn(&ResolvedChar) -> bool) -> bool {
|
||||
let chars = resolved(s);
|
||||
if !s.sel.is_collapsed() || selected_text_box(s).is_some() || column_rows(s).is_some() {
|
||||
return !chars.first().is_some_and(has);
|
||||
}
|
||||
!chars.iter().all(has)
|
||||
}
|
||||
|
||||
/// Bold as drawn: a run marked complex script (`w:cs`) or right to left (`w:rtl`) shows its
|
||||
/// complex-script bold.
|
||||
fn shown_bold(r: &ResolvedChar) -> bool {
|
||||
@@ -376,7 +366,7 @@ fn shown_italic(r: &ResolvedChar) -> bool {
|
||||
fn toggle(s: &mut Session, v: &Value, get: fn(&ResolvedChar) -> bool, set: fn(&mut CharProps, bool)) -> CmdResult {
|
||||
let on = match p::bool(v, "value") {
|
||||
Some(b) => b,
|
||||
None => turns_on(s, get),
|
||||
None => !resolved(s).iter().all(get),
|
||||
};
|
||||
apply(s, &|c| set(c, on))
|
||||
}
|
||||
@@ -386,7 +376,7 @@ fn underline(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let on = match (p::bool(v, "value"), style) {
|
||||
(Some(b), _) => b,
|
||||
(None, Some(_)) => true,
|
||||
(None, None) => turns_on(s, |r| r.underline != Underline::None),
|
||||
(None, None) => !resolved(s).iter().all(|r| r.underline != Underline::None),
|
||||
};
|
||||
let u = if on { style.unwrap_or(Underline::Single) } else { Underline::None };
|
||||
apply(s, &|c| c.underline = Some(u))
|
||||
|
||||
@@ -80,8 +80,12 @@ 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)), newest];
|
||||
[Some((rev, width, height, mode, spacing, l.clone(), self.view.proofing, outline, deleted, self.view.numeral, typing, shown)), prev];
|
||||
l
|
||||
}
|
||||
|
||||
@@ -275,3 +279,31 @@ 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
-66
@@ -1043,72 +1043,6 @@ fn bold_toggles_selection_and_caret_word() {
|
||||
assert_eq!(p.props_of_char(9).italic, None);
|
||||
}
|
||||
|
||||
/// A partly formatted selection toggles by its first character, as Word does (#6516).
|
||||
#[test]
|
||||
fn toggles_on_mixed_selection_follow_first_character() {
|
||||
// `Abc abc` with `fmt` set by `cmd`, then `cmd` with `v` on the selection `from` → `to`.
|
||||
let toggled = |cmd: &str, fmt: (usize, usize), from: usize, to: usize, v: serde_json::Value| -> String {
|
||||
let mut s = s();
|
||||
run(&mut s, "text.insert", json!({"text": "Abc abc"}));
|
||||
let sel = |s: &mut Session, a: usize, b: usize| {
|
||||
run(s, "select.range", json!({"anchor": {"block": 0, "off": a}, "focus": {"block": 0, "off": b}}));
|
||||
};
|
||||
sel(&mut s, fmt.0, fmt.1);
|
||||
run(&mut s, cmd, json!({"value": true}));
|
||||
sel(&mut s, from, to);
|
||||
run(&mut s, cmd, v);
|
||||
let p = s.doc.para_at(&Pos::body(0, 0)).unwrap();
|
||||
(0..7)
|
||||
.map(|i| {
|
||||
let c = p.props_of_char(i);
|
||||
match cmd {
|
||||
"format.italic" => c.italic == Some(true),
|
||||
"format.underline" => c.underline.is_some_and(|u| u != wordcraft_doc::props::Underline::None),
|
||||
_ => c.bold == Some(true),
|
||||
}
|
||||
})
|
||||
.map(|on| if on { 'F' } else { '.' })
|
||||
.collect()
|
||||
};
|
||||
let t = || json!({});
|
||||
for cmd in ["format.bold", "format.italic", "format.underline"] {
|
||||
// `FFF....`: a selection starting on formatted text removes the format from all of it.
|
||||
assert_eq!(toggled(cmd, (0, 3), 2, 5, t()), "FF.....", "{cmd}");
|
||||
assert_eq!(toggled(cmd, (0, 3), 0, 7, t()), ".......", "{cmd}");
|
||||
assert_eq!(toggled(cmd, (0, 3), 1, 7, t()), "F......", "{cmd}");
|
||||
// Made right to left: still the first character in document order.
|
||||
assert_eq!(toggled(cmd, (0, 3), 5, 2, t()), "FF.....", "{cmd}");
|
||||
assert_eq!(toggled(cmd, (0, 3), 7, 0, t()), ".......", "{cmd}");
|
||||
// `....FFF`: a selection starting on plain text applies it to all of it.
|
||||
assert_eq!(toggled(cmd, (4, 7), 0, 7, t()), "FFFFFFF", "{cmd}");
|
||||
// An explicit value still sets.
|
||||
assert_eq!(toggled(cmd, (0, 3), 0, 7, json!({"value": true})), "FFFFFFF", "{cmd}");
|
||||
assert_eq!(toggled(cmd, (4, 7), 0, 7, json!({"value": false})), ".......", "{cmd}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A selection that starts in an empty paragraph: Word decides from the first text character, not
|
||||
/// from the empty paragraph's mark (observed in Word for Windows, #6516 review).
|
||||
#[test]
|
||||
fn toggle_on_a_selection_from_an_empty_paragraph_follows_the_first_text() {
|
||||
let toggled = |mark_bold: bool, text_bold: bool| -> Option<bool> {
|
||||
let mut s = s();
|
||||
run(&mut s, "text.newParagraph", json!({}));
|
||||
run(&mut s, "text.insert", json!({"text": "abc"}));
|
||||
let first = Pos::body(0, 0);
|
||||
s.doc.para_mut(first.story, &first.path).unwrap().mark.bold = Some(mark_bold);
|
||||
run(&mut s, "select.range", json!({"anchor": {"block": 1, "off": 0}, "focus": {"block": 1, "off": 3}}));
|
||||
run(&mut s, "format.bold", json!({"value": text_bold}));
|
||||
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 0}, "focus": {"block": 1, "off": 3}}));
|
||||
run(&mut s, "format.bold", json!({}));
|
||||
s.doc.para_at(&Pos::body(1, 0)).unwrap().props_of_char(0).bold
|
||||
};
|
||||
// A bold empty paragraph before plain text: Bold goes on.
|
||||
assert_eq!(toggled(true, false), Some(true));
|
||||
// A plain empty paragraph before bold text: Bold comes off.
|
||||
assert_eq!(toggled(false, true), Some(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn border_toggles_and_saves() {
|
||||
use wordcraft_doc::props::Border;
|
||||
@@ -9800,6 +9734,77 @@ fn change_case_keeps_each_runs_formatting_when_lengths_change() {
|
||||
assert_eq!(text(&s), "Q");
|
||||
}
|
||||
|
||||
/// #3479: Change Case follows language-aware mapping for Turkish, Azerbaijani, and Crimean Tatar (i↔İ, ı↔I).
|
||||
#[test]
|
||||
fn change_case_follows_turkic_language_mapping() {
|
||||
// 1. Turkish (tr-TR): all 5 modes
|
||||
// Capitalize Each Word (title)
|
||||
let mut s = s();
|
||||
run(&mut s, "review.language", json!({"lang": "tr-TR", "default": true}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul ışık", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "title"}));
|
||||
assert_eq!(text(&s), "İstanbul Işık");
|
||||
|
||||
// UPPERCASE
|
||||
run(&mut s, "format.changeCase", json!({"mode": "upper"}));
|
||||
assert_eq!(text(&s), "İSTANBUL IŞIK");
|
||||
|
||||
// lowercase
|
||||
run(&mut s, "format.changeCase", json!({"mode": "lower"}));
|
||||
assert_eq!(text(&s), "istanbul ışık");
|
||||
|
||||
// sentence case
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "tr-TR", "default": true}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul. ışık.", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "sentence"}));
|
||||
assert_eq!(text(&s), "İstanbul. Işık.");
|
||||
|
||||
// toggle case
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "tr-TR", "default": true}));
|
||||
run(&mut s, "text.insert", json!({"text": "İstanbul Işık", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "toggle"}));
|
||||
assert_eq!(text(&s), "iSTANBUL ıŞIK");
|
||||
|
||||
// 2. Azerbaijani (az-AZ)
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "az-AZ", "default": true}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "title"}));
|
||||
assert_eq!(text(&s), "İstanbul");
|
||||
|
||||
// 3. Crimean Tatar (crh)
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "crh", "default": true}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "title"}));
|
||||
assert_eq!(text(&s), "İstanbul");
|
||||
|
||||
// 4. English control (en-US): unchanged Unicode default
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "en-US", "default": true}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "title"}));
|
||||
assert_eq!(text(&s), "Istanbul");
|
||||
|
||||
// 5. Mixed-language selection: Turkish run followed by English run
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "tr-TR"}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul ", "raw": true}));
|
||||
run(&mut s, "review.language", json!({"lang": "en-US"}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "title"}));
|
||||
assert_eq!(text(&s), "İstanbul Istanbul");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn change_case_sentence_ignores_decimal_points() {
|
||||
// #3485: Sentence case should not capitalize after decimal points.
|
||||
@@ -9872,6 +9877,9 @@ 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();
|
||||
@@ -15407,6 +15415,32 @@ fn page_down_extends_a_selection_that_ends_in_collapsed_outline_text() {
|
||||
assert!(s.layout().caret(&s.sel.focus).is_some(), "to a place the outline shows");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_down_and_up_reach_the_ends_on_first_and_last_page() {
|
||||
let mut s = s();
|
||||
for i in 0..80 {
|
||||
if i > 0 {
|
||||
run(&mut s, "text.newParagraph", json!({}));
|
||||
}
|
||||
run(&mut s, "text.insert", json!({"text": format!("Paragraph {i}")}));
|
||||
}
|
||||
let pages = s.layout().pages.len();
|
||||
assert!(pages >= 2, "expected a multi-page document, got {pages}");
|
||||
run(&mut s, "caret.docStart", json!({}));
|
||||
let start = s.sel.focus.clone();
|
||||
// Advance page by page until the last page, then one more PageDown must reach the end.
|
||||
for _ in 0..pages {
|
||||
run(&mut s, "caret.pageDown", json!({}));
|
||||
}
|
||||
let end = s.doc.end_of(wordcraft_doc::StoryRef::Body);
|
||||
assert_eq!(s.sel.focus, end, "PageDown on the last page reaches the end of the document");
|
||||
// Step back page by page until page 0, then one more PageUp must reach the start.
|
||||
for _ in 0..pages {
|
||||
run(&mut s, "caret.pageUp", json!({}));
|
||||
}
|
||||
assert_eq!(s.sel.focus, start, "PageUp on the first page reaches the start of the document");
|
||||
}
|
||||
|
||||
/// #5428: an inserted or pasted picture fits where it goes, as in Word: a table cell's width
|
||||
/// (a nested cell's too), a column's, not the whole page's text width.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
|
||||
@@ -41,6 +41,41 @@ fn assert_fixture_font(s: &mut Session) {
|
||||
assert!(runs > 0, "the font check must inspect laid-out body text");
|
||||
}
|
||||
|
||||
/// A document that just spills onto a second page: the most lines `make` can put on one page,
|
||||
/// then space before the last paragraph until it moves to page 2 ([`spill_last_paragraph`]).
|
||||
/// The fixtures are set in the bundled [`FIXTURE_FONT`], but a fixed line count still depends on
|
||||
/// that font's exact metrics and the page setup, so the tests find the spill point instead.
|
||||
fn just_spilling(make: impl Fn(usize) -> Session) -> Session {
|
||||
let mut lines = 10;
|
||||
while make(lines + 1).layout().pages.len() < 2 {
|
||||
lines += 1;
|
||||
assert!(lines < 120, "{lines} lines still fit on one page");
|
||||
}
|
||||
let mut s = make(lines);
|
||||
assert_eq!(s.layout().pages.len(), 1, "{lines} lines must fit on one page");
|
||||
spill_last_paragraph(&mut s);
|
||||
s
|
||||
}
|
||||
|
||||
/// Adds space before the last paragraph, half a point at a time, until it moves to page 2. The
|
||||
/// document then overflows by less than half a point, which any font reduction it is fitted with
|
||||
/// brings back.
|
||||
fn spill_last_paragraph(s: &mut Session) {
|
||||
let mut before = match s.doc.body.last().map(|b| &**b) {
|
||||
Some(wordcraft_doc::Block::Para(p)) => p.props.space_before.unwrap_or(0.0),
|
||||
_ => 0.0,
|
||||
};
|
||||
while s.layout().pages.len() < 2 {
|
||||
before += 0.5;
|
||||
assert!(before <= 200.0, "space before the last paragraph never moved it to page 2");
|
||||
if let Some(wordcraft_doc::Block::Para(p)) = s.doc.body.last_mut().map(std::sync::Arc::make_mut) {
|
||||
p.props.space_before = Some(before);
|
||||
}
|
||||
s.touch();
|
||||
s.relayout();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_fails_on_single_page() {
|
||||
let mut s = create_multiline_doc(5);
|
||||
@@ -144,15 +179,20 @@ fn fit_one_page_respects_max_delta() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_respects_step_pt() {
|
||||
let mut s = create_multiline_doc(27);
|
||||
for b in &mut s.doc.body {
|
||||
if let wordcraft_doc::Block::Para(p) = std::sync::Arc::make_mut(b) {
|
||||
p.mark.size = Some(11.4);
|
||||
for r in &mut p.runs {
|
||||
r.props.size = Some(11.4);
|
||||
let at_11_4 = |lines: usize| {
|
||||
let mut s = create_multiline_doc(lines);
|
||||
for b in &mut s.doc.body {
|
||||
if let wordcraft_doc::Block::Para(p) = std::sync::Arc::make_mut(b) {
|
||||
p.mark.size = Some(11.4);
|
||||
for r in &mut p.runs {
|
||||
r.props.size = Some(11.4);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
s.touch();
|
||||
s
|
||||
};
|
||||
let mut s = just_spilling(at_11_4);
|
||||
assert_eq!(s.layout().pages.len(), 2, "must start as 2-page document at 11.4 pt");
|
||||
assert_fixture_font(&mut s);
|
||||
|
||||
@@ -162,7 +202,7 @@ fn fit_one_page_respects_step_pt() {
|
||||
let default_res = s.run("layout.fitOnePage", &json!({"maxDeltaPt": 0.4, "adjustSpacing": false}));
|
||||
assert!(default_res.is_err(), "default step 0.5 must skip all candidates when maxDelta is 0.4");
|
||||
|
||||
// With stepPt = 0.1 under the same maxDeltaPt = 0.4, fine-grained steps (0.1..0.4) succeed (11.4 -> 11.0 pt).
|
||||
// With stepPt = 0.1 under the same maxDeltaPt = 0.4, a fine-grained step (0.1 to 0.4 pt) succeeds.
|
||||
s.doc = doc_backup;
|
||||
let res = s.run("layout.fitOnePage", &json!({"maxDeltaPt": 0.4, "stepPt": 0.1, "adjustSpacing": false}));
|
||||
assert!(res.is_ok(), "stepPt=0.1 must generate fine-grained candidates under maxDelta 0.4: {res:?}");
|
||||
@@ -877,7 +917,7 @@ fn fit_one_page_tracks_reduced_complex_script_font_sizes() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_preserves_budget_across_document_serialization() {
|
||||
let mut s = create_multiline_doc(26);
|
||||
let mut s = just_spilling(create_multiline_doc);
|
||||
assert_eq!(s.layout().pages.len(), 2);
|
||||
assert_fixture_font(&mut s);
|
||||
|
||||
@@ -894,12 +934,10 @@ fn fit_one_page_preserves_budget_across_document_serialization() {
|
||||
assert_eq!(reopened_doc.fit_state.as_ref().map(|f| f.cum_delta), Some(0.5));
|
||||
assert!(reopened_doc.custom_props.is_empty(), "custom_props must remain empty");
|
||||
|
||||
// Reopen into a new session with additional spill
|
||||
// Reopen into a new session with additional spill: the last paragraph moves to page 2 again
|
||||
let mut s2 = Session::new(reopened_doc);
|
||||
let extra_p = wordcraft_doc::Paragraph::with_text("Extra overflow paragraph.", CharProps::default());
|
||||
s2.doc.body.push(wordcraft_doc::para_block(extra_p));
|
||||
s2.touch();
|
||||
s2.relayout();
|
||||
assert_eq!(s2.layout().pages.len(), 1);
|
||||
spill_last_paragraph(&mut s2);
|
||||
|
||||
// Second fit on reopened document preserves previous 0.5 delta, allowing only remaining 0.5 pt up to 1.0 cap
|
||||
let res2 = s2.run("layout.fitOnePage", &json!({"maxDeltaPt": 0.5, "adjustSpacing": false}));
|
||||
|
||||
@@ -3416,13 +3416,22 @@ fn autocorrect_capitalisation_follows_turkic_case_mapping() {
|
||||
run(&mut s, "review.language", json!({"lang": "en-US", "default": true}));
|
||||
typ(&mut s, "İNgilizce ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "İngilizce ", "no combining dot in any language");
|
||||
// #3503: two initial capitals and caps-lock with a stray İ in English.
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "en-US", "default": true}));
|
||||
typ(&mut s, "Wİrd ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "Wird ", "two initial capitals lowercases İ to i in English");
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "en-US", "default": true}));
|
||||
typ(&mut s, "wİRD ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "Wird ", "caps-lock slip fixes wİRD to Wird in English");
|
||||
}
|
||||
|
||||
/// #3479: Format > Change Case follows the same Turkic case mapping as AutoCorrect, using
|
||||
/// each run's own language; other languages keep the Unicode default.
|
||||
#[test]
|
||||
fn change_case_follows_turkic_case_mapping() {
|
||||
for tag in ["tr-TR", "az-AZ"] {
|
||||
for tag in ["tr-TR", "az-AZ", "crh"] {
|
||||
for (mode, input, want) in [
|
||||
("upper", "istanbul", "İSTANBUL"),
|
||||
("lower", "IŞIK", "ışık"),
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
//! 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,4 +1,5 @@
|
||||
mod comment_ids;
|
||||
mod content_controls;
|
||||
mod date_fields;
|
||||
mod macro_packages;
|
||||
mod odt_charts;
|
||||
|
||||
@@ -909,29 +909,19 @@ impl Scan {
|
||||
}
|
||||
self.x += w;
|
||||
}
|
||||
_ => {
|
||||
// Its room grows from nothing with its text (a tab moved on from the line before
|
||||
// may still hold the width it had there).
|
||||
if let Some(c) = pl.clusters.get_mut(j) {
|
||||
c.adv = 0.0;
|
||||
}
|
||||
self.pending_tab = Some((j, stop, self.x));
|
||||
}
|
||||
_ => self.pending_tab = Some((j, stop, self.x)),
|
||||
}
|
||||
if stop.leader != TabLeader::None {
|
||||
self.leaders.push((j, stop.leader));
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether text after a right/centre tab grows leftwards into the tab's space first. Up to a
|
||||
/// right or decimal stop it fits even past the right indent (Word: a TOC entry whose text ends
|
||||
/// less than a digit short of the indent keeps its page number on its line when the stop is
|
||||
/// at the margin); unshifted, the text after the tab ends at `x - room`.
|
||||
/// Whether text after a right/centre tab grows leftwards into the tab's space first.
|
||||
fn absorbs(&self, pl: &ParaLayout, advance: f32) -> bool {
|
||||
self.pending_tab.is_some_and(|(tj, stop, _)| {
|
||||
let room = pl.clusters.get(tj).map(|t| t.adv).unwrap_or(0.0);
|
||||
match stop.align {
|
||||
TabAlign::Right | TabAlign::Decimal => room >= advance || self.x - room + advance <= stop.pos + 0.01,
|
||||
TabAlign::Right | TabAlign::Decimal => room >= advance,
|
||||
TabAlign::Center => room >= advance / 2.0 && self.x + advance / 2.0 <= self.right_edge + 0.01,
|
||||
_ => false,
|
||||
}
|
||||
@@ -1007,9 +997,7 @@ impl Scan {
|
||||
/// Text after a decimal/centre/right tab shifts as it grows.
|
||||
fn shift_pending_tab(&mut self, pl: &mut ParaLayout) {
|
||||
let Some((tj, stop, tx)) = self.pending_tab else { return };
|
||||
// `x` includes the room the tab has so far.
|
||||
let old = pl.clusters.get(tj).map(|c| c.adv).unwrap_or(0.0);
|
||||
let seg_w = self.x - tx - old;
|
||||
let seg_w = self.x - tx;
|
||||
let shift = match stop.align {
|
||||
TabAlign::Right => stop.pos - tx - seg_w,
|
||||
TabAlign::Center => stop.pos - tx - seg_w / 2.0,
|
||||
@@ -1018,6 +1006,7 @@ impl Scan {
|
||||
_ => 0.0,
|
||||
};
|
||||
let shift = shift.max(0.0);
|
||||
let old = pl.clusters.get(tj).map(|c| c.adv).unwrap_or(0.0);
|
||||
if (shift - old).abs() > 0.001 {
|
||||
let delta = shift - old;
|
||||
if let Some(c) = pl.clusters.get_mut(tj) {
|
||||
|
||||
@@ -521,12 +521,18 @@ fn fill_headers_footers(
|
||||
None
|
||||
}
|
||||
|
||||
/// Evict paragraph layouts that weren't used this pass if the cache grew large.
|
||||
/// Evict paragraph layouts that weren't used this pass if the cache accumulated too many stale entries.
|
||||
fn evict_unused(cache: &mut LayoutCache) {
|
||||
if cache.paras.len() + cache.measures.len() > 4 * cache.used.len().max(1024) {
|
||||
if cache.paras.len() + cache.measures.len() > cache.used.len() + cache.used.len().clamp(512, 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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -589,7 +589,8 @@ 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).
|
||||
let room = (avail - start_offset.max(0.0)).max(1.0);
|
||||
// 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);
|
||||
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);
|
||||
|
||||
+60
-49
@@ -685,6 +685,43 @@ 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();
|
||||
@@ -1970,54 +2007,6 @@ fn leader_dots_are_spaced_and_placed_as_in_word() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A TOC entry with a right indent and its right tab at the margin, past the indent (Word's TOC
|
||||
/// styles): the page number may end past the indent, up to the stop. Like Word, the number stays
|
||||
/// on the text's line whenever it fits between the text and the stop, also when the text ends
|
||||
/// less than a digit short of the indent; when it doesn't fit there, the tab and the number go
|
||||
/// to the next line as before.
|
||||
#[test]
|
||||
fn right_tab_past_the_right_indent_takes_its_number_up_to_the_stop() {
|
||||
use wordcraft_doc::props::{TabAlign, TabLeader, TabStop};
|
||||
let stop = 72.0 + 468.0;
|
||||
let mut close = 0;
|
||||
for indent in [28.35f32, 6.0] {
|
||||
let edge = stop - indent;
|
||||
for m in 20..40 {
|
||||
for r in 2..7 {
|
||||
let text = format!("{}{}\t104", "abc ".repeat(m), "y".repeat(r));
|
||||
let n = text.chars().count();
|
||||
let tab = n - 4;
|
||||
let mut d = Document::from_text(&text);
|
||||
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| {
|
||||
p.indent_right = Some(indent);
|
||||
p.tabs = Some(vec![TabStop { pos: 468.0, align: TabAlign::Right, leader: TabLeader::Dot }]);
|
||||
})
|
||||
.unwrap();
|
||||
let l = lay(&d);
|
||||
let Some(para) = l.pages[0].items.iter().find_map(|i| if let Placed::Lines { para, .. } = i { Some(para.clone()) } else { None })
|
||||
else {
|
||||
panic!("no lines")
|
||||
};
|
||||
let line_of = |k: usize| para.lines.iter().position(|l| l.c0 <= k && k < l.c1).unwrap();
|
||||
// Where the text ends and how wide the number is (the text's last letter and the number
|
||||
// are each on one line; the last two letters are both a "y").
|
||||
let last = l.caret(&Pos::body(0, tab - 1)).unwrap().x;
|
||||
let text_end = last + (last - l.caret(&Pos::body(0, tab - 2)).unwrap().x);
|
||||
let end = l.caret(&Pos::body(0, n)).unwrap().x;
|
||||
let number = end - l.caret(&Pos::body(0, n - 3)).unwrap().x;
|
||||
assert!((end - stop).abs() < 0.5, "indent {indent}, {m} words + {r}: number ends at {end}");
|
||||
assert_eq!(line_of(tab), line_of(n - 1), "indent {indent}, {m} words + {r}: the tab and its number are on different lines");
|
||||
let same = line_of(tab) == line_of(tab - 1);
|
||||
assert_eq!(same, text_end + number <= stop + 0.01, "indent {indent}, {m} words + {r}: text ends at {text_end}, number {number} wide");
|
||||
if same && text_end > edge - number / 3.0 {
|
||||
close += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(close > 0, "no entry whose text ends within a digit of the indent");
|
||||
}
|
||||
|
||||
/// A left tab whose only stop is past the right indent wraps; on the next line it still can't
|
||||
/// reach that stop, so it takes no room there and its text starts at the indent instead of
|
||||
/// going to a line of its own.
|
||||
@@ -3983,7 +3972,13 @@ fn kept_headings_measure_the_next_paragraph_through_the_cache() {
|
||||
let mut c = LayoutCache::new();
|
||||
let proofed = layout(&d, &mut c, &LayoutOptions { proofing: true, ..Default::default() });
|
||||
assert_eq!(c.misses, d.body.len() as u64, "each paragraph laid out once with proofing on");
|
||||
assert!(c.hits >= 40, "each kept heading should reuse its following paragraph layout with proofing on; got {} cache hits", c.hits);
|
||||
// A kept heading that falls to the next page skips the pre-measure, once per page break at most.
|
||||
let pre_measured = 40u64.saturating_sub(l.pages.len() as u64).max(1);
|
||||
assert!(
|
||||
c.hits >= pre_measured,
|
||||
"kept headings should reuse their following paragraph layout with proofing on; got {} cache hits of at least {pre_measured}",
|
||||
c.hits
|
||||
);
|
||||
let starts = |l: &DocLayout| (0..d.body.len()).map(|i| l.caret(&Pos::body(i, 0)).map(|c| (c.page, c.top.to_bits()))).collect::<Vec<_>>();
|
||||
assert_eq!(starts(&l), starts(&proofed));
|
||||
}
|
||||
@@ -18292,3 +18287,19 @@ 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,16 +6,74 @@
|
||||
//! Renders now [`take`](ContextPool::take) the kept context, reset to their size, and
|
||||
//! [`give_back`](ContextPool::give_back) it when done.
|
||||
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::ops::{Deref, DerefMut};
|
||||
use std::sync::{Mutex, PoisonError};
|
||||
|
||||
use vello_cpu::{RenderContext, RenderSettings};
|
||||
|
||||
/// A render context kept between renders.
|
||||
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.
|
||||
pub(crate) struct ContextPool {
|
||||
slot: Mutex<Option<RenderContext>>,
|
||||
/// How many contexts (so thread pools) were built: one, unless renders overlap.
|
||||
built: AtomicUsize,
|
||||
state: Mutex<State>,
|
||||
}
|
||||
|
||||
/// The context page, area and icon renders share.
|
||||
@@ -23,39 +81,96 @@ pub(crate) static CONTEXTS: ContextPool = ContextPool::new();
|
||||
|
||||
impl ContextPool {
|
||||
pub(crate) const fn new() -> Self {
|
||||
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() })
|
||||
}
|
||||
ContextPool {
|
||||
state: Mutex::new(State {
|
||||
primary: None,
|
||||
primary_out: false,
|
||||
primary_peak_pixels: 0,
|
||||
primary_small_streak: 0,
|
||||
spares: Vec::new(),
|
||||
built: 0,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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);
|
||||
/// 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,
|
||||
}
|
||||
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.built.load(Ordering::Relaxed)
|
||||
self.state.lock().unwrap_or_else(PoisonError::into_inner).built
|
||||
}
|
||||
}
|
||||
|
||||
@@ -270,4 +385,55 @@ mod tests {
|
||||
// down here; that it built any shows page renders go through it.
|
||||
assert!(CONTEXTS.built() >= 1, "page and icon renders take the shared context");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concurrent_spares_are_reused_without_spawning_more_contexts() {
|
||||
let pool = ContextPool::new();
|
||||
for _ in 0..4 {
|
||||
let a = pool.take(240, 160);
|
||||
let b = pool.take(240, 160);
|
||||
pool.give_back(a);
|
||||
pool.give_back(b);
|
||||
}
|
||||
assert_eq!(pool.built(), 2, "primary + spare should be reused across overlapping rounds");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_contexts_are_dropped_after_returning_to_small_renders() {
|
||||
let pool = ContextPool::new();
|
||||
let big_p = pool.take(2500, 2500);
|
||||
let big_s = pool.take(2500, 2500);
|
||||
pool.give_back(big_p);
|
||||
pool.give_back(big_s);
|
||||
assert_eq!(pool.built(), 2);
|
||||
|
||||
for _ in 0..OVERSIZED_SHRINK_STREAK {
|
||||
pooled(&pool, 400, 400);
|
||||
}
|
||||
// Oversized primary dropped at streak == OVERSIZED_SHRINK_STREAK; next take rebuilds a fresh one.
|
||||
pooled(&pool, 400, 400);
|
||||
assert_eq!(pool.built(), 3, "oversized primary should be replaced once back at normal sizes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spare_pool_caps_retained_contexts_at_max_spares() {
|
||||
let pool = ContextPool::new();
|
||||
let retained = MAX_SPARES + usize::from(crate::default_threads() > 0);
|
||||
let total = retained + 1;
|
||||
let held: Vec<_> = (0..total).map(|_| pool.take(240, 160)).collect();
|
||||
assert_eq!(pool.built(), total);
|
||||
for ctx in held {
|
||||
pool.give_back(ctx);
|
||||
}
|
||||
|
||||
// Primary (when default_threads() > 0) + MAX_SPARES spares are retained; checking that many out builds nothing new.
|
||||
let reused: Vec<_> = (0..retained).map(|_| pool.take(240, 160)).collect();
|
||||
assert_eq!(pool.built(), total, "retained contexts should be reused");
|
||||
let extra = pool.take(240, 160);
|
||||
assert_eq!(pool.built(), total + 1, "excess spare beyond MAX_SPARES should have been dropped");
|
||||
pool.give_back(extra);
|
||||
for ctx in reused {
|
||||
pool.give_back(ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
//! 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.
|
||||
//! 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.
|
||||
//!
|
||||
//! `cargo run --release -p wordcraft-ui-egui --example perf_probe -- doc.docx [block]`
|
||||
//! `cargo run --release -p wordcraft-ui-egui --example perf_probe -- [--synthetic | 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
|
||||
@@ -14,6 +15,9 @@ 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};
|
||||
|
||||
@@ -21,6 +25,118 @@ 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);
|
||||
@@ -46,22 +162,34 @@ 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": (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})
|
||||
json!({"n": s.len(), "med": round1(at(0.5)), "p95": round1(at(0.95)), "max": round1(at(1.0))})
|
||||
}
|
||||
|
||||
/// Opens the document named on the command line and prints JSON timings for start-up, typing,
|
||||
/// scrolling, zooming, ribbon tabs and window resizes.
|
||||
/// 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.
|
||||
fn main() {
|
||||
let path = std::env::args().nth(1).expect("usage: perf_probe doc.docx [block]");
|
||||
let path = std::env::args().nth(1).expect("usage: perf_probe [--synthetic | 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 mut session = Session::new(wordcraft_doc::Document::new());
|
||||
session.run("file.open", &json!({"path": path})).expect("open");
|
||||
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 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().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()
|
||||
.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(
|
||||
|ui, app: &mut WordApp| {
|
||||
if !READY.load(std::sync::atomic::Ordering::Relaxed) {
|
||||
return;
|
||||
@@ -82,8 +210,18 @@ fn main() {
|
||||
}
|
||||
READY.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
let first: Vec<f64> = (0..6).map(|_| step(&mut h)).collect();
|
||||
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<_>>()});
|
||||
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),
|
||||
});
|
||||
|
||||
// Typing: the caret in the middle of `block` (default: the longest paragraph), 40 characters.
|
||||
let doc_block = block.unwrap_or_else(|| {
|
||||
@@ -126,6 +264,24 @@ 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 {
|
||||
@@ -142,6 +298,7 @@ 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();
|
||||
@@ -149,26 +306,49 @@ 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": (a * 10.0).round() / 10.0, "next_ms": (b * 10.0).round() / 10.0}));
|
||||
zoom.push(json!({"zoom": z, "frame_ms": round1(a), "next_ms": round1(b)}));
|
||||
}
|
||||
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": (f * 10.0).round() / 10.0});
|
||||
out["accept_all"] = json!({"frame_ms": round1(f)});
|
||||
}
|
||||
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}");
|
||||
}
|
||||
|
||||
@@ -120,6 +120,7 @@ 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,
|
||||
@@ -214,11 +215,18 @@ impl WordApp {
|
||||
.wheel_speed(WheelSpeed::new(line, point))
|
||||
.alt_code_pages(AltCodePages::new(ansi, oem))
|
||||
.set(ComponentSet::Productivity);
|
||||
env.motion = self.ui.animations.motion();
|
||||
env.motion = self.ui.animations.motion_drawn(self.software_drawing);
|
||||
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 {
|
||||
|
||||
@@ -887,8 +887,9 @@ impl WordApp {
|
||||
let Some(path) = p.get("path").and_then(Value::as_str) else {
|
||||
return Some(Err("`path` must name a document on the recent list".into()));
|
||||
};
|
||||
let resolved = crate::prefs::expand_recent_path(path);
|
||||
let before = self.ui.recent.len();
|
||||
self.ui.recent.retain(|r| r != path);
|
||||
self.ui.recent.retain(|r| r != path && r != &resolved);
|
||||
if self.ui.recent.len() == before {
|
||||
return Some(Err(format!("`{path}` is not on the recent list")));
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ impl WordApp {
|
||||
ui.keyboard = Shortcuts(self.session.keymap().clone());
|
||||
ui.ribbon = self.session.ribbon.clone();
|
||||
ui.ink_pens = self.session.view.draw.pens.clone();
|
||||
ui.recent = ui.recent.iter().map(|p| crate::prefs::contract_recent_path(p)).collect();
|
||||
ui
|
||||
}
|
||||
|
||||
@@ -35,6 +36,8 @@ impl WordApp {
|
||||
self.ui.tab = DEFAULT_TAB.into();
|
||||
let recent_fonts = recent_fonts_from(self.ui.font_picker.recent.iter().map(String::as_str));
|
||||
self.ui.font_picker.recent = recent_fonts;
|
||||
let mut seen_recent = std::collections::HashSet::with_capacity(self.ui.recent.len());
|
||||
self.ui.recent = self.ui.recent.iter().map(|p| crate::prefs::expand_recent_path(p)).filter(|p| seen_recent.insert(p.clone())).collect();
|
||||
// Settings from before the theme setting: their dark-mode switch picks Dark or Light.
|
||||
if let Some(dark) = self.ui.legacy_dark.take() {
|
||||
self.ui.theme = if dark { theme::Appearance::Dark } else { theme::Appearance::Light };
|
||||
|
||||
@@ -143,6 +143,8 @@ 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)>,
|
||||
@@ -262,6 +264,19 @@ 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
|
||||
@@ -405,6 +420,7 @@ 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,
|
||||
@@ -798,7 +814,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: Vec<(f64, f64)> = layout.pages.iter().map(|p| (f64::from(p.body.y), f64::from(p.body.bottom()))).collect();
|
||||
let bodies = app.canvas.cached_page_bodies(layout);
|
||||
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;
|
||||
|
||||
@@ -65,11 +65,12 @@ 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(app.canvas.table_resize.as_ref().and_then(|d| d.ruler_line_x(mods, line)).unwrap_or(x)))
|
||||
.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)))
|
||||
.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);
|
||||
@@ -101,6 +102,18 @@ 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);
|
||||
}
|
||||
|
||||
@@ -36,6 +36,23 @@ 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]
|
||||
@@ -2605,3 +2622,115 @@ 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");
|
||||
}
|
||||
|
||||
@@ -118,7 +118,8 @@ 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.
|
||||
/// 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.
|
||||
#[derive(craft::ui::contract::Component, craft::ui::contract::Props)]
|
||||
#[component(canvas_control)]
|
||||
struct ContentControls<'a> {
|
||||
@@ -188,14 +189,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(Sense::CLICK | Sense::KEEP_FOCUS)
|
||||
.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(Sense::CLICK | Sense::KEEP_FOCUS)
|
||||
.priority(handle)
|
||||
.cursor(CursorIcon::PointingHand)
|
||||
.pointer_only("Developer > Choose Item and Set Date run the same commands");
|
||||
@@ -392,6 +393,14 @@ 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| {
|
||||
@@ -404,11 +413,35 @@ 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]
|
||||
@@ -452,4 +485,46 @@ 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");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -269,12 +269,21 @@ impl WordForm for MergeRecordsForm {
|
||||
})
|
||||
});
|
||||
self.choice = choice;
|
||||
// Typing a number picks the range.
|
||||
if let Some(v) = NumberField::new(tl!("From:"), Bind::given(self.from)).show(ui).value().copied() {
|
||||
// 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 {
|
||||
self.from = v;
|
||||
self.choice = 2;
|
||||
}
|
||||
if let Some(v) = NumberField::new(tl!("To:"), Bind::given(self.to)).show(ui).value().copied() {
|
||||
if let Some(v) = to {
|
||||
self.to = v;
|
||||
self.choice = 2;
|
||||
}
|
||||
|
||||
@@ -73,8 +73,15 @@ 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)),
|
||||
_ => {}
|
||||
@@ -341,6 +348,34 @@ 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]
|
||||
@@ -743,6 +778,7 @@ 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)),
|
||||
_ => {}
|
||||
|
||||
@@ -527,7 +527,14 @@ 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 enabled = app.ui.keytips_enabled && app.canvas.object_gesture().is_none();
|
||||
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;
|
||||
}
|
||||
|
||||
// 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).
|
||||
@@ -579,6 +586,7 @@ 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 }));
|
||||
}
|
||||
|
||||
@@ -582,3 +582,32 @@ 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");
|
||||
}
|
||||
|
||||
@@ -458,6 +458,11 @@ 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
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! formatting controls. The framework's selection task bar places it (above the selection, flipped
|
||||
//! and clamped inside the document area); this module decides when it shows and what it holds.
|
||||
|
||||
use craft::behavior::{EditEvent, Preview};
|
||||
use craft::behavior::{EditEvent, EditPolicy, Preview};
|
||||
use craft::keymap::CommandRef;
|
||||
use craft::pages::ui::PageBody;
|
||||
use craft::ui::buttons::{Button, ControlPlace, GroupLevel, ToggleButton};
|
||||
@@ -198,13 +198,14 @@ pub(crate) fn members(app: &mut WordApp, ui: &mut Ui, preview: bool) {
|
||||
.map(|s| Entry::new(number_text(f64::from(*s)), number_text(f64::from(*s))))
|
||||
.collect();
|
||||
let mut text = size.clone();
|
||||
let combo = ComboBox::new(tl!("Font Size").to_string(), Bind::bound(&mut text), &sizes).show(ui);
|
||||
// `text` is rebuilt from the selection on every pass: the box keeps what is typed until Enter.
|
||||
let combo = ComboBox::new(tl!("Font Size").to_string(), Bind::bound(&mut text).policy(EditPolicy::OnCommit), &sizes).show(ui);
|
||||
follow_list(app, preview, &combo.preview, |v| {
|
||||
v.trim().parse::<f64>().ok().map(|x| ("format.size".to_string(), json!({"size": x})))
|
||||
});
|
||||
// Only a pick or Enter applies the size: typing alone is an edit of the box's draft.
|
||||
let committed =
|
||||
combo.edit.submitted || combo.edit.events.iter().any(|e| matches!(e, EditEvent::Set { .. } | EditEvent::Commit { .. }));
|
||||
// Only a pick or Enter applies the size: typing alone is an edit of the box's draft, and leaving the box
|
||||
// without either drops it.
|
||||
let committed = combo.edit.submitted || combo.edit.events.iter().any(|e| matches!(e, EditEvent::Set { .. }));
|
||||
if committed
|
||||
&& text != size
|
||||
&& let Ok(x) = text.trim().parse::<f64>()
|
||||
|
||||
@@ -980,3 +980,25 @@ fn automatic_and_no_color_preview_on_hover() {
|
||||
assert_eq!(h.state().canvas.command_previewed, None, "{button} {item_label}: Escape clears the preview");
|
||||
}
|
||||
}
|
||||
|
||||
/// A size typed into the bar's size box applies when Enter is pressed. The box's
|
||||
/// text was rebuilt from the selection on every pass, so what was typed was gone by then.
|
||||
#[test]
|
||||
fn a_size_typed_into_the_bar_size_box_applies_on_enter() {
|
||||
let mut h = bar_over("brown fox");
|
||||
for typed in ["20", "16.5"] {
|
||||
h.state_mut().run("select.text", json!({"text": "brown fox"})).unwrap();
|
||||
steps(&mut h);
|
||||
let selection = h.state().session.sel.clone();
|
||||
let before = format_state(&mut h).get("size").and_then(Value::as_f64);
|
||||
let at = size_box(&h).center();
|
||||
click_at(&mut h, at);
|
||||
press_key(&mut h, egui::Key::A, egui::Modifiers { ctrl: true, command: true, ..Default::default() });
|
||||
h.event(egui::Event::Text(typed.into()));
|
||||
steps(&mut h);
|
||||
assert_eq!(format_state(&mut h).get("size").and_then(Value::as_f64), before, "typing {typed} alone changes nothing");
|
||||
press_key(&mut h, egui::Key::Enter, egui::Modifiers::NONE);
|
||||
assert_eq!(format_state(&mut h).get("size").and_then(Value::as_f64), typed.parse::<f64>().ok(), "Enter applies the typed size {typed}");
|
||||
assert_eq!(h.state().session.sel, selection, "the selection stays");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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("select.addObject", json!({"pos": object.pos()}));
|
||||
let _ = app.run_keep_view("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,7 +582,8 @@ impl ObjectGesture {
|
||||
}
|
||||
let pos = object.pos();
|
||||
let end = Pos { off: pos.off + OBJ.len_utf8(), ..pos.clone() };
|
||||
let _ = app.run("select.range", json!({"anchor": pos, "focus": end}));
|
||||
// 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}));
|
||||
// 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() {
|
||||
@@ -604,7 +605,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("select.range", json!({"anchor": pos, "focus": end}));
|
||||
let _ = app.run_keep_view("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;
|
||||
@@ -758,8 +759,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("select.range", json!({"anchor": pos, "focus": end}));
|
||||
if app.run("select.member", json!({"index": index})).is_err() {
|
||||
let _ = app.run_keep_view("select.range", json!({"anchor": pos, "focus": end}));
|
||||
if app.run_keep_view("select.member", json!({"index": index})).is_err() {
|
||||
return Some(ObjectGesture::inert());
|
||||
}
|
||||
ObjectGesture::start(body, object, at)
|
||||
@@ -911,7 +912,10 @@ 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() };
|
||||
let _ = app.run("select.range", json!({"anchor": pos, "focus": end}));
|
||||
// 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}));
|
||||
}
|
||||
// A header/footer picture repeats on every page: its frame belongs on the page clicked, not
|
||||
// the one last edited.
|
||||
|
||||
@@ -347,7 +347,9 @@ impl PreferencesModel for OptionsModel<'_> {
|
||||
tl!("Tell me when a document's missing fonts can be downloaded"),
|
||||
app.ui.font_download_notice,
|
||||
),
|
||||
custom("general.defaultApp", tl!("Make WordCraft the default for Word documents…")).visible(can_default),
|
||||
RowSpec::new("general.defaultApp", "", RowKind::CustomRows)
|
||||
.keywords(tl!("Make WordCraft the default for Word documents…"))
|
||||
.visible(can_default),
|
||||
],
|
||||
),
|
||||
GroupSpec::new(
|
||||
|
||||
@@ -221,6 +221,20 @@ 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() {
|
||||
|
||||
@@ -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};
|
||||
use craft::ui::contract::{Bind, Props, Show, ShowContainer, Sizing};
|
||||
use craft::ui::display::Text;
|
||||
use craft::ui::layout_components::{Row, Stack};
|
||||
use craft::ui::primitives::IconSpec;
|
||||
@@ -128,6 +128,12 @@ 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.
|
||||
@@ -140,8 +146,9 @@ 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(1)
|
||||
.lines(FIELD_LINES)
|
||||
.max_lines(COMMENT_ROWS)
|
||||
.sizing(Sizing::FillWidth)
|
||||
.placeholder(tl!("Add a comment").to_owned())
|
||||
.enabled(editable)
|
||||
.show(ui);
|
||||
@@ -198,8 +205,9 @@ 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(1)
|
||||
.lines(FIELD_LINES)
|
||||
.max_lines(COMMENT_ROWS)
|
||||
.sizing(Sizing::FillWidth)
|
||||
.placeholder(tl!("Write a reply").to_owned())
|
||||
.enabled(editable)
|
||||
.show(ui);
|
||||
|
||||
@@ -273,6 +273,143 @@ 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]
|
||||
|
||||
@@ -461,3 +461,105 @@ pub fn import_legacy_window(bytes: &[u8], store: &mut craft::window::restore::St
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
/// Returns the user's home directory from `HOME` or `USERPROFILE`, if set and non-empty.
|
||||
fn home_dir() -> Option<std::path::PathBuf> {
|
||||
std::env::var_os("HOME")
|
||||
.filter(|h| !h.is_empty())
|
||||
.or_else(|| std::env::var_os("USERPROFILE").filter(|h| !h.is_empty()))
|
||||
.map(std::path::PathBuf::from)
|
||||
}
|
||||
|
||||
fn strip_tilde_prefix(path: &str) -> Option<&str> {
|
||||
if cfg!(windows) { path.strip_prefix("~/").or_else(|| path.strip_prefix("~\\")) } else { path.strip_prefix("~/") }
|
||||
}
|
||||
|
||||
fn split_tilde_rest(rest: &str) -> impl Iterator<Item = &str> {
|
||||
let is_sep = |c: char| c == '/' || (cfg!(windows) && c == '\\');
|
||||
rest.split(is_sep).filter(|s| !s.is_empty())
|
||||
}
|
||||
|
||||
fn strip_home_prefix<'a>(path: &'a std::path::Path, home: &std::path::Path) -> Option<Vec<std::path::Component<'a>>> {
|
||||
if cfg!(not(windows)) {
|
||||
return path.strip_prefix(home).ok().map(|rel| rel.components().collect());
|
||||
}
|
||||
let mut path_comps = path.components();
|
||||
for h in home.components() {
|
||||
let p = path_comps.next()?;
|
||||
let matches = match (h, p) {
|
||||
(std::path::Component::Prefix(a), std::path::Component::Prefix(b)) => {
|
||||
a.as_os_str().to_string_lossy().eq_ignore_ascii_case(&b.as_os_str().to_string_lossy())
|
||||
}
|
||||
(std::path::Component::RootDir, std::path::Component::RootDir) | (std::path::Component::CurDir, std::path::Component::CurDir) => true,
|
||||
(std::path::Component::ParentDir, std::path::Component::ParentDir) => true,
|
||||
(std::path::Component::Normal(a), std::path::Component::Normal(b)) => {
|
||||
a.to_string_lossy().to_lowercase() == b.to_string_lossy().to_lowercase()
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
if !matches {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(path_comps.collect())
|
||||
}
|
||||
|
||||
/// Contracts a path inside `home` to `~/...` with `/` separators for cross-OS profile sync (#8189).
|
||||
/// Paths outside `home`, containing `..`, or (on Unix) literal backslashes are returned unchanged.
|
||||
pub(crate) fn contract_recent_path_with(path: &str, home: Option<&std::path::Path>) -> String {
|
||||
if let Some(rest) = strip_tilde_prefix(path) {
|
||||
let parts: Vec<_> = split_tilde_rest(rest).collect();
|
||||
return if parts.is_empty() { path.to_string() } else { format!("~/{}", parts.join("/")) };
|
||||
}
|
||||
let Some(home) = home else {
|
||||
return path.to_string();
|
||||
};
|
||||
let Some(rel) = strip_home_prefix(std::path::Path::new(path), home) else {
|
||||
return path.to_string();
|
||||
};
|
||||
let mut parts = Vec::new();
|
||||
for c in rel {
|
||||
match c {
|
||||
std::path::Component::Normal(s) => {
|
||||
let s = s.to_string_lossy();
|
||||
if s.contains('\\') {
|
||||
return path.to_string();
|
||||
}
|
||||
parts.push(s);
|
||||
}
|
||||
std::path::Component::CurDir => {}
|
||||
std::path::Component::ParentDir | std::path::Component::RootDir | std::path::Component::Prefix(_) => {
|
||||
return path.to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
if parts.is_empty() { path.to_string() } else { format!("~/{}", parts.join("/")) }
|
||||
}
|
||||
|
||||
/// Expands a `~/...` recent-file path against `home`; other paths (or entries whose components
|
||||
/// would replace `home`, such as `..` or a Windows drive prefix) are returned unchanged (#8189).
|
||||
pub(crate) fn expand_recent_path_with(path: &str, home: Option<&std::path::Path>) -> String {
|
||||
let Some(rest) = strip_tilde_prefix(path) else {
|
||||
return path.to_string();
|
||||
};
|
||||
let Some(home) = home else {
|
||||
return path.to_string();
|
||||
};
|
||||
let mut out = home.to_path_buf();
|
||||
for part in split_tilde_rest(rest) {
|
||||
let mut comps = std::path::Path::new(part).components();
|
||||
if !matches!((comps.next(), comps.next()), (Some(std::path::Component::Normal(_)), None)) {
|
||||
return path.to_string();
|
||||
}
|
||||
out.push(part);
|
||||
}
|
||||
out.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
pub(crate) fn contract_recent_path(path: &str) -> String {
|
||||
contract_recent_path_with(path, home_dir().as_deref())
|
||||
}
|
||||
|
||||
pub(crate) fn expand_recent_path(path: &str) -> String {
|
||||
expand_recent_path_with(path, home_dir().as_deref())
|
||||
}
|
||||
|
||||
@@ -219,3 +219,55 @@ fn recent_list_edits_are_final_and_persist() {
|
||||
assert!(c.ui.recent.is_empty());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// #8189: recent paths inside the user's home directory are stored as `~/...` and resolved on load.
|
||||
#[test]
|
||||
fn recent_paths_inside_home_contract_and_expand() {
|
||||
use std::path::Path;
|
||||
|
||||
let home = Path::new("/home/alice");
|
||||
let inside = home.join("Docs").join("test.docx");
|
||||
let contracted = super::contract_recent_path_with(&inside.to_string_lossy(), Some(home));
|
||||
assert_eq!(contracted, "~/Docs/test.docx");
|
||||
assert_eq!(super::expand_recent_path_with(&contracted, Some(home)), inside.to_string_lossy());
|
||||
|
||||
// Paths outside home, with `..`, and the home directory itself stay unchanged.
|
||||
assert_eq!(super::contract_recent_path_with("/tmp/outside.docx", Some(home)), "/tmp/outside.docx");
|
||||
assert_eq!(super::contract_recent_path_with("/home/alice/../etc/passwd", Some(home)), "/home/alice/../etc/passwd");
|
||||
assert_eq!(super::contract_recent_path_with(&home.to_string_lossy(), Some(home)), home.to_string_lossy());
|
||||
if cfg!(not(windows)) {
|
||||
let literal_backslash = "/home/alice/Docs/a\\b.docx";
|
||||
assert_eq!(super::contract_recent_path_with(literal_backslash, Some(home)), literal_backslash);
|
||||
assert_eq!(super::expand_recent_path_with("~/Docs/a\\b.docx", Some(home)), literal_backslash);
|
||||
// Case-sensitive on Unix.
|
||||
assert_eq!(super::contract_recent_path_with("/home/Alice/Docs/test.docx", Some(home)), "/home/Alice/Docs/test.docx");
|
||||
} else {
|
||||
let win_home = Path::new(r"C:\Users\Alice");
|
||||
assert_eq!(super::contract_recent_path_with(r"c:\users\alice\Docs\test.docx", Some(win_home)), "~/Docs/test.docx");
|
||||
assert_eq!(super::expand_recent_path_with("~/Docs/C:notes.docx", Some(win_home)), "~/Docs/C:notes.docx");
|
||||
}
|
||||
assert_eq!(super::expand_recent_path_with("~/Docs/../outside.docx", Some(home)), "~/Docs/../outside.docx");
|
||||
assert_eq!(super::expand_recent_path_with("/tmp/outside.docx", Some(home)), "/tmp/outside.docx");
|
||||
assert_eq!(super::expand_recent_path_with("~/Docs/test.docx", None), "~/Docs/test.docx");
|
||||
|
||||
// Round-trip through WordApp::prefs / apply_prefs using the process home directory.
|
||||
let real_home = std::env::var_os("HOME")
|
||||
.filter(|h| !h.is_empty())
|
||||
.or_else(|| std::env::var_os("USERPROFILE").filter(|h| !h.is_empty()))
|
||||
.map(std::path::PathBuf::from);
|
||||
if let Some(real_home) = real_home {
|
||||
let doc = real_home.join("WordCraftSyncTest").join("notes.docx");
|
||||
let doc_str = doc.to_string_lossy().into_owned();
|
||||
let mut a = app();
|
||||
a.ui.recent = vec![doc_str.clone(), "/tmp/outside.docx".into()];
|
||||
let saved = a.prefs();
|
||||
assert_eq!(saved.recent, vec!["~/WordCraftSyncTest/notes.docx".to_string(), "/tmp/outside.docx".to_string()]);
|
||||
|
||||
let mut loaded = saved;
|
||||
loaded.recent.push(doc_str.clone());
|
||||
a.apply_prefs(loaded);
|
||||
assert_eq!(a.ui.recent, vec![doc_str, "/tmp/outside.docx".to_string()]);
|
||||
assert!(a.run("ui.recentRemove", json!({"path": "~/WordCraftSyncTest/notes.docx"})).is_ok());
|
||||
assert_eq!(a.ui.recent, vec!["/tmp/outside.docx".to_string()]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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..5u64 {
|
||||
for lv in 0..9u64 {
|
||||
MenuItem::command(CommandRef::with_params("para.listLevel", json!({"level": lv})))
|
||||
.label(format!("Change to Level {}", lv + 1))
|
||||
.show(ui);
|
||||
|
||||
@@ -81,12 +81,13 @@ 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, line: usize) -> Option<f32> {
|
||||
if !self.ruler || !matches!(self.target.edge, Edge::Column(_)) {
|
||||
pub(crate) fn ruler_line_x(&self, mods: Mods, row: Option<usize>, line: usize) -> Option<f32> {
|
||||
if !matches!(self.target.edge, Edge::Column(_)) {
|
||||
return None;
|
||||
}
|
||||
let plan = self.plan(mods);
|
||||
Some(self.target.planned_x(&plan, plan.cells.first().map(|(r, _)| *r), line))
|
||||
let row = row.or_else(|| plan.cells.first().map(|(r, _)| *r));
|
||||
Some(self.target.planned_x(&plan, row, line))
|
||||
}
|
||||
|
||||
/// Whether the pointer has moved from where it went down.
|
||||
@@ -95,6 +96,51 @@ 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> {
|
||||
|
||||
@@ -380,3 +380,79 @@ 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");
|
||||
}
|
||||
|
||||
@@ -391,6 +391,34 @@ fn find_shortcut_focuses_find_what() {
|
||||
assert!(fields["find"].as_str().unwrap_or_default().ends_with("abc"), "typing went into Find what: {fields:?}");
|
||||
}
|
||||
|
||||
/// #1610: opening a hyperlink must direct typing and paste into its address.
|
||||
#[test]
|
||||
fn hyperlink_shortcut_focuses_address_and_preserves_document() {
|
||||
let mut a = app();
|
||||
a.run("text.insert", json!({"text": "Keep this text"})).unwrap();
|
||||
a.run("select.text", json!({"text": "Keep this text"})).unwrap();
|
||||
let mut h = harness(a);
|
||||
h.run_steps(2);
|
||||
|
||||
for (event, expected) in [
|
||||
(egui::Event::Paste("https://example.com".into()), "https://example.com"),
|
||||
(egui::Event::Text("https://example.org".into()), "https://example.org"),
|
||||
] {
|
||||
press(&mut h, egui::Key::K, egui::Modifiers::COMMAND);
|
||||
assert!(h.state().dialog_host.open_dialogs().iter().any(|d| d.key.as_deref() == Some("link")), "Link dialog open");
|
||||
h.event(event);
|
||||
h.run_steps(2);
|
||||
let address = h.get_by_label("Address:").value().unwrap_or_default();
|
||||
assert_eq!(address, expected, "input replaces the initial address");
|
||||
let display = h.get_by_label("Text to display:").value().unwrap_or_default();
|
||||
assert_eq!(display, "Keep this text");
|
||||
assert_eq!(body_text(h.state()), "Keep this text");
|
||||
press(&mut h, egui::Key::Escape, egui::Modifiers::NONE);
|
||||
assert!(h.state().dialog_host.open_dialogs().is_empty(), "Cancel closes the dialog");
|
||||
assert_eq!(h.state().session.selected_text(), "Keep this text", "Cancel preserves selection");
|
||||
}
|
||||
}
|
||||
|
||||
/// The key of the dialog a command opened, read off its reply.
|
||||
fn pending_of(reply: &Value) -> Option<&str> {
|
||||
reply.get("pending").and_then(Value::as_str)
|
||||
@@ -2209,11 +2237,8 @@ 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");
|
||||
// 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");
|
||||
assert_eq!(h.query_all_by_label_contains(LABEL).count(), hook as usize, "hook {hook}: one caption on 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");
|
||||
|
||||
@@ -231,6 +231,12 @@ 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 {
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft::font_manager::Catalog;
|
||||
use craft::font_manager::craft_font_catalog::{Limits, Source};
|
||||
use craft::font_manager::craft_font_catalog::{FontEnv, Limits, Os, Source};
|
||||
use craft::font_manager::picker::FontPickerSettings;
|
||||
use craft::ui::buttons::IconButton;
|
||||
use craft::ui::contract::{Props as _, Show as _};
|
||||
use egui::Key;
|
||||
use craft::ui::contract::{Bind, Props as _, Show as _};
|
||||
use egui::accesskit::Role;
|
||||
use egui_kittest::kittest::{NodeT, Queryable};
|
||||
use egui::{Key, vec2};
|
||||
use egui_kittest::kittest::{By, NodeT, Queryable};
|
||||
use serde_json::{Value, json};
|
||||
use wordcraft_engine::Session;
|
||||
|
||||
@@ -222,3 +226,78 @@ 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:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -168,6 +168,7 @@ impl WordApp {
|
||||
ime_origin: _,
|
||||
user_origin: _,
|
||||
native_scale: _,
|
||||
software_drawing: _,
|
||||
auto_scale_limit: _,
|
||||
legacy_interface_size: _,
|
||||
applied_editing: _,
|
||||
|
||||
@@ -211,8 +211,13 @@ 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}));
|
||||
app.status(if o.completed { tl!("Zotero: done") } else { tl!("Zotero: cancelled") });
|
||||
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") });
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
app.zotero.last = Some(json!({"command": name, "error": e}));
|
||||
@@ -386,4 +391,26 @@ 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)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -630,3 +630,35 @@ 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]));
|
||||
}
|
||||
|
||||
@@ -413,7 +413,6 @@ The front-of-text opt-out is retained from the earlier implementation; this patc
|
||||
| 2026-10-27 | trivial | A kept-together paragraph in a continuous section is measured against the next page's body, so a tall different first-page header no longer splits one that fits on page 2 (#3907 CodeRabbit) |
|
||||
| 2026-10-27 | trivial | 2026-10-27 · #4533 review: numeric REF updates lazily index body bookmarks once per update, retaining the first body bookmark for duplicate names. Unsupported switches and ordinary REF/PAGEREF behavior are unchanged; a synthetic 64-reference regression covers repeated updates and duplicate names. Estimates unchanged. |
|
||||
| 2026-10-27 | trivial | 2026-10-27 · #4533: numeric REF fields use paragraph list numbers for no/full/relative context, reusing bounded numbering. Shared context already embedded in a level label is removed; merged-away cells do not count. Unsupported separator/text/position switches and ambiguous contexts or delimiter-free joins retain cached results. Synthetic OOXML regressions; no native Word or real-document validation, estimates unchanged. |
|
||||
| 2026-10-27 | trivial | A right or decimal tab past the right indent (a TOC entry's page number at the margin) keeps its text on the line while it ends before the stop, also when the text before the tab ends less than a digit short of the indent; measured in Word for Mac 16.93. `layout::tests::right_tab_past_the_right_indent_takes_its_number_up_to_the_stop` |
|
||||
| 2026-10-20 | trivial | A click below a floating table, outside its cells, goes to the paragraph beside or after it instead of a cell of its last row, as checked in Word (#2038) |
|
||||
| 2026-10-19 | trivial | A right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, starts the next line with its text instead of ending the line (a TOC entry's page number keeps its leader); a left tab still past the right indent there takes no room (#1840) |
|
||||
| 2026-10-19 | trivial | Justified lines (compatibility mode 15) shrink their spaces to fit one more word by at most a quarter of the spaces' width (was a fifth) and by at most 0.355 of that word's own width with the space before it. Measured in Word for Mac with synthetic justified paragraphs: words of 2.7 to 80 pt, spaces of 3.3 and 6.7 pt, only justified text, last lines included, never in modes 12 and 14. A real paper's justified abstract now breaks like Word on all 23 lines (3 before); on 180 real-world papers, page counts matching Word went from 139 to 142, none further |
|
||||
|
||||
+3
-2
@@ -73,8 +73,9 @@ PDF in one run without a window:
|
||||
`file` (a document to open) and `template` are optional, and `--file` / `--template` on the command
|
||||
line win. A command is `{"command": id, "params": {…}}` or just the id. `save` is a path or a list;
|
||||
each output's format follows its extension. Relative `file` and `save` paths resolve against the
|
||||
script's folder (the working folder for stdin). `--cmd` flags run after the script's commands and
|
||||
`--save` after its outputs. The run starts with one open document. `file.new` and `file.open`
|
||||
script's folder (the working folder for stdin). `--cmd` flags run after the script's commands.
|
||||
Repeat `--save OUT` to write additional outputs in command-line order, after the script's outputs.
|
||||
Each `--save` requires a path. The run starts with one open document. `file.new` and `file.open`
|
||||
open another one and make it active; later commands and the saves work on the active document.
|
||||
`view.switchWindows` lists the open documents (with `--print` their ids show), and
|
||||
`view.switchWindows={"id": n}` makes one active. A failing command stops the run with `command N (id): …` and exit
|
||||
|
||||
+1
-12
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user