Merge main (cbea96e5) into the pull request

The only conflict was in crates/layout/src/tests.rs, where both sides ha

The only conflict was in crates/layout/src/tests.rs, where both sides had added tests at the end of the file. I kept all of them: the pull request's `a_decimal_tab_by_the_margin_still_wraps_its_number`, and main's `a_body_text_frame_respects_its_anchors`, `env_hash_memoizes_styles_and_invalidates_on_change` and `evict_unused_caps_stale_entries_across_repeated_edits`. I gave the decimal-tab test its own closing brace and removed the markers. No markers are left in crates, and `cargo fmt --check` is clean for the layout crate. The file is byte-identical to my earlier resolution (same sha256), which built and passed those four tests. I did not re-run the tests in this session. I did not run the full layout suite either. The earlier session saw 4 unrelated failures, which I think come from the sandbox; I did not confirm that.
This commit is contained in:
autocraft-bot[bot]
2026-12-03 14:04:54 +00:00
161 changed files with 6556 additions and 746 deletions
+12 -2
View File
@@ -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());
@@ -1048,6 +1057,7 @@ fn launcher_profile_flag(args: &[OsString]) -> bool {
}
fn main() -> ExitCode {
wordcraft_engine::malloc_tuning::apply();
let args: Vec<OsString> = std::env::args_os().skip(1).collect();
if launcher_profile_flag(&args) {
eprintln!("wordcraft-cli: --launch-profile and --profile-root are the desktop app's Nightly bootstrap, not a CLI option");
+58
View File
@@ -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");
+2
View File
@@ -3,6 +3,8 @@ mod closed_stdout;
mod convert_fields;
mod convert_region;
mod help;
#[cfg(all(target_os = "linux", target_env = "gnu"))]
mod malloc_tuning;
mod mcp_roots;
#[cfg(all(unix, not(target_os = "macos")))]
mod non_utf8_args;
@@ -0,0 +1,78 @@
//! The CLI binary re-executes itself on Linux glibc with `MALLOC_TRIM_THRESHOLD_` fixed so freed
//! page/render buffers are returned to the OS while respecting caller-supplied values.
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicUsize, Ordering};
use wordcraft_engine::malloc_tuning::{TRIM_THRESHOLD, TRIM_THRESHOLD_VAR};
struct TempDirs(PathBuf);
impl TempDirs {
fn new(tag: &str) -> Self {
static NEXT: AtomicUsize = AtomicUsize::new(0);
let root = loop {
let n = NEXT.fetch_add(1, Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!("wc-cli-malloc-{tag}-{}-{n}", std::process::id()));
match std::fs::create_dir(&dir) {
Ok(()) => break dir,
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
Err(e) => panic!("temp dir {}: {e}", dir.display()),
}
};
std::fs::create_dir_all(root.join("in")).unwrap();
std::fs::create_dir_all(root.join("out")).unwrap();
Self(root)
}
}
impl Drop for TempDirs {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn s(p: &Path) -> String {
p.to_string_lossy().into_owned()
}
fn mcp_environ(tag: &str, set: Option<&str>) -> Vec<String> {
let dirs = TempDirs::new(tag);
let mut cmd = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"));
for var in [TRIM_THRESHOLD_VAR, "MALLOC_MMAP_THRESHOLD_", "MALLOC_TOP_PAD_", "MALLOC_MMAP_MAX_", "MALLOC_ARENA_MAX", "GLIBC_TUNABLES"] {
cmd.env_remove(var);
}
if let Some(v) = set {
cmd.env(TRIM_THRESHOLD_VAR, v);
}
let mut child = cmd
.args(["mcp", "--automation-read-root", &s(&dirs.0.join("in")), "--automation-write-root", &s(&dirs.0.join("out"))])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.unwrap();
let mut stdin = child.stdin.take().unwrap();
writeln!(stdin, r#"{{"jsonrpc":"2.0","id":1,"method":"ping"}}"#).unwrap();
let mut reply = String::new();
BufReader::new(child.stdout.take().unwrap()).read_line(&mut reply).unwrap();
assert!(reply.contains(r#""id":1"#), "mcp answered after re-exec: {reply}");
let environ = std::fs::read(format!("/proc/{}/environ", child.id())).unwrap();
drop(stdin);
assert!(child.wait().unwrap().success());
environ.split(|&b| b == 0).map(|e| String::from_utf8_lossy(e).into_owned()).collect()
}
#[test]
fn sets_the_trim_threshold() {
let env = mcp_environ("default", None);
assert!(env.contains(&format!("{TRIM_THRESHOLD_VAR}={TRIM_THRESHOLD}")), "{env:?}");
}
#[test]
fn keeps_a_value_the_user_set() {
let env = mcp_environ("explicit", Some("999999"));
assert!(env.contains(&format!("{TRIM_THRESHOLD_VAR}=999999")), "{env:?}");
}
+12
View File
@@ -492,6 +492,9 @@ fn main() -> eframe::Result {
let updates_unsafe = start_over_failed.is_some();
#[cfg(not(target_os = "linux"))]
let updates_unsafe = false;
// Before any thread or logger starts: re-exec on Linux glibc with MALLOC_TRIM_THRESHOLD_
// fixed so large freed document/render buffers return to the OS.
wordcraft_engine::malloc_tuning::apply();
// First, so the panic hook (set once, by this call; the later one only gives it the crash-log
// folder) and every start-up warning are recorded.
let logger = logs::install(LogNames::new("wordcraft"));
@@ -745,6 +748,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")) {
+37 -9
View File
@@ -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
View File
@@ -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_ "));
}
}
+17 -1
View File
@@ -619,7 +619,8 @@ impl Paragraph {
/// The word around `off` (double-click): (start, end) without trailing space.
pub fn word_at(&self, off: usize) -> (usize, usize) {
let off = self.clamp(off);
let is_w = |c: char| crate::bidi::is_word_char(c);
// Word's word unit takes a typographic apostrophe (’) like `'`, at either end too (#6517).
let is_w = |c: char| crate::bidi::is_word_char(c) || c == '’';
let mut a = off;
for (i, c) in self.text.get(..off).unwrap_or("").char_indices().rev() {
if !is_w(c) {
@@ -852,6 +853,21 @@ mod tests {
assert_eq!(p.prev_boundary(0), 0);
}
#[test]
fn word_at_takes_a_typographic_apostrophe_like_a_straight_one() {
// Byte offsets: `’` is three bytes. Word: `don’t ` (#6517).
let p = Paragraph::with_text("don’t stop", CharProps::default());
assert_eq!(p.word_at(1), (0, 8));
assert_eq!(p.word_at(2), (0, 8));
let p = Paragraph::with_text("the dogs’ bone", CharProps::default());
assert_eq!(p.word_at(5), (4, 12));
let p = Paragraph::with_text("’tis here", CharProps::default());
assert_eq!(p.word_at(3), (0, 7));
assert_eq!(p.word_at(4), (0, 7));
let p = Paragraph::with_text("well-known", CharProps::default());
assert_eq!(p.word_at(1), (0, 4));
}
proptest::proptest! {
#[test]
fn edits_keep_runs_consistent(ops in proptest::collection::vec((0u8..4, 0usize..40, 0usize..40, "[a-zé ]{0,5}"), 0..40)) {
+4 -4
View File
@@ -362,10 +362,10 @@ fn copy_member(s: &mut Session, pos: &Pos, index: usize) -> CmdResult {
if !copied {
return Err(CmdError::Failed("the member vanished".into()));
}
s.clipboard_text = f.clipboard_text();
s.clip_history.push(&f, &s.clipboard_text);
s.clipboard = Some(f);
Ok(super::edit::copy_result(s))
let text = f.clipboard_text();
let r = super::edit::copy_result(s, &f, &text)?;
s.clip_history.push(&f, &text);
Ok(r)
}
/// Take member `index` out of the canvas at `pos`; the canvas stays selected.
+5 -1
View File
@@ -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)
+3 -3
View File
@@ -244,10 +244,10 @@ fn copy(s: &mut Session, segs: &[(Pos, Pos)]) -> CmdResult {
rows.push(row_text(s, &a, &b));
blocks.push(Block::Para(para));
}
s.clipboard_text = rows.join("\n");
let text = rows.join("\n");
let media = s.doc.media_of_blocks(&blocks);
s.clipboard = Some(Fragment { blocks, parts, media });
Ok(super::edit::copy_result(s))
let f = Fragment { blocks, parts, media };
super::edit::copy_result(s, &f, &text)
}
/// Delete each row's piece (bottom up, so earlier positions stay valid) and leave the caret at
+21 -11
View File
@@ -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 {
+25 -20
View File
@@ -208,29 +208,28 @@ fn copy_with(s: &mut Session, whole: Option<&Path>) -> CmdResult {
None if a == b => return Ok(json!({"text": ""})),
None => s.doc.copy_range(&a, &b),
};
s.clipboard_text = f.clipboard_text();
s.clip_history.push(&f, &s.clipboard_text);
s.clipboard = Some(f);
Ok(copy_result(s))
let text = f.clipboard_text();
let r = copy_result(s, &f, &text)?;
s.clip_history.push(&f, &text);
Ok(r)
}
/// What Copy and Cut return: the clipboard's text, and the copy as HTML (equations as MathML,
/// #816) and as RTF for the host to put on the system clipboard too, so other programs keep the
/// formatting; and for a copy of one equation alone, its MathML (#1297).
pub(crate) fn copy_result(s: &mut Session) -> Value {
(s.clipboard_html, s.clipboard_rtf) = match &s.clipboard {
Some(f) => {
let mut d = f.to_document();
d.styles = s.doc.styles.clone();
if d.media.is_empty() {
d.media = s.doc.media.clone();
}
(wordcraft_formats::html::export_fragment(&d), wordcraft_formats::rtf::export(&d))
}
None => (String::new(), String::new()),
};
let mut r = json!({"text": s.clipboard_text});
for (k, v) in [("html", &s.clipboard_html), ("rtf", &s.clipboard_rtf)] {
///
/// The copy goes on the clipboard whole or not at all: a copy whose HTML or RTF cannot be made
/// is refused, and the clipboard keeps what it held.
pub(crate) fn copy_result(s: &mut Session, f: &Fragment, text: &str) -> CmdResult {
let mut d = f.to_document();
d.styles = s.doc.styles.clone();
if d.media.is_empty() {
d.media = s.doc.media.clone();
}
let html = wordcraft_formats::html::export_fragment(&d).map_err(|e| CmdError::Failed(format!("the copy cannot be exported as HTML: {e}")))?;
let rtf = wordcraft_formats::rtf::export(&d).map_err(|e| CmdError::Failed(format!("the copy cannot be exported as RTF: {e}")))?;
let mut r = json!({"text": text});
for (k, v) in [("html", &html), ("rtf", &rtf)] {
if !v.is_empty() {
r[k] = json!(v);
}
@@ -239,10 +238,16 @@ pub(crate) fn copy_result(s: &mut Session) -> Value {
// ("MathML" on Windows, `public.mathml.presentation` on macOS; #1297). Word looks for them
// before anything else when it pastes; a copy with text around the equation doesn't offer
// them, so pasting it keeps the text.
if let Some((linear, display)) = s.clipboard.as_ref().and_then(|f| f.sole_equation()) {
if let Some((linear, display)) = f.sole_equation() {
r["mathml"] = json!(wordcraft_formats::mathml::linear_to_mathml(linear, display));
}
r
// The copy is on the clipboard now: its text, its fragment and its HTML and RTF flavours,
// all at once.
s.clipboard_text = text.to_string();
s.clipboard = Some(f.clone());
s.clipboard_html = html;
s.clipboard_rtf = rtf;
Ok(r)
}
/// Cut the selection, selected object, or whole table cells to the clipboard and remove it from the document.
+21
View File
@@ -703,3 +703,24 @@ fn a_math_name_is_corrected_by_any_character_that_cannot_continue_it() {
s.run("equation.type", &json!({"text": r"\alpha+"})).unwrap();
assert_eq!(linear(&s), r"\alpha+");
}
/// Paste Formatting keeps an open equation open (matching other formatting commands and
/// `cmd::column`), whereas content-pasting commands leave the equation first.
#[test]
fn paste_formatting_keeps_an_open_equation_open() {
let mut s = session();
s.run("text.insert", &json!({"text": "source "})).unwrap();
s.run("select.text", &json!({"text": "source"})).unwrap();
s.run("format.bold", &json!({})).unwrap();
s.run("edit.copyFormat", &json!({})).unwrap();
s.run("caret.docEnd", &json!({})).unwrap();
s.run("insert.equation", &json!({"linear": "x"})).unwrap();
let before = s.math.clone();
assert!(before.is_some());
s.run("edit.pasteFormat", &json!({})).unwrap();
assert_eq!(s.math, before, "edit.pasteFormat keeps the open equation open");
s.run("edit.pasteText", &json!({"text": "y"})).unwrap();
assert!(s.math.is_none(), "edit.pasteText closes the open equation");
}
+20 -6
View File
@@ -94,9 +94,9 @@ pub fn specs() -> Vec<CommandSpec> {
.pure(),
CommandSpec::new("file.save", "Save", "File", save)
.key("Mod+S / Shift+F12 / Alt+Shift+F2")
.params(r#"{"path"?: string, "password"?: string (encrypt this and later saves with it, as file.encrypt does), "markup"?: bool (Print Markup for a PDF, PNG, HTML, Markdown or text copy: comments shown; default file.printMarkup), "format"?: "wordml2003" (an .xml file as a Word 2003 XML Document) | "flatopc" (as a Word XML Document, the default; saving over a Word 2003 XML file keeps that format), "strict"?: bool (a .pdf or .png only: refuse, writing nothing, if a character can't be drawn or a picture is missing; see file.strictReport)}"#)
.params(r#"{"path"?: string (required with `copy`), "password"?: string (encrypt this and later saves with it, as file.encrypt does), "markup"?: bool (Print Markup for a PDF, PNG, HTML, Markdown or text copy: comments shown; default file.printMarkup), "format"?: "wordml2003" (an .xml file as a Word 2003 XML Document) | "flatopc" (as a Word XML Document, the default; saving over a Word 2003 XML file keeps that format), "strict"?: bool (a .pdf or .png only: refuse, writing nothing, if a character can't be drawn or a picture is missing; see file.strictReport), "copy"?: bool (write a copy at `path`, as File › Export does: the document keeps its own file, unsaved changes and save stamps; not with `password`)}"#)
.pure(),
CommandSpec::new("file.saveAs", "Save As", "File", save_as).key(super::mac_or("F12 / Mod+Shift+S", "F12 / Alt+F2")).params(r#"{"path": string, "password"?: string, "markup"?: bool, "format"?: string (as file.save), "strict"?: bool (as file.save)}"#).pure(),
CommandSpec::new("file.saveAs", "Save As", "File", save_as).key(super::mac_or("F12 / Mod+Shift+S", "F12 / Alt+F2")).params(r#"{"path": string, "password"?: string, "markup"?: bool, "format"?: string (as file.save), "strict"?: bool (as file.save), "copy"?: bool (as file.save)}"#).pure(),
// Pure: the password must not land in Repeat or a recorded macro, and it isn't an edit
// to undo; it marks the document as changed itself.
CommandSpec::new("file.encrypt", "Encrypt with Password", "File › Info › Protect Document", encrypt)
@@ -393,6 +393,14 @@ fn encrypt(s: &mut Session, v: &Value) -> CmdResult {
/// Executes `file.save`: writes the document or text to disk, preserving exact file text for
/// unedited Markdown files, and updating session path and dirty state.
fn save(s: &mut Session, v: &Value) -> CmdResult {
// A copy (File › Export, #6131) is written and nothing else: the document keeps its own file,
// its unsaved changes and its save stamps, so the next Save still goes to the original.
// It never falls back to the document's own file or opens the Save As picker (whose answer is
// an ordinary save that adopts the file).
let as_copy = p::bool(v, "copy") == Some(true);
if as_copy && p::str(v, "path").is_none() {
return Err(CmdError::Params("`copy` needs a `path`: the copy has to go somewhere".into()));
}
let path = match p::str(v, "path").map(std::path::PathBuf::from).or_else(|| s.path.clone()) {
Some(p) => p,
None => {
@@ -401,6 +409,9 @@ fn save(s: &mut Session, v: &Value) -> CmdResult {
}
};
check_strict_output(p::bool(v, "strict").unwrap_or(false), &path.to_string_lossy())?;
if as_copy && v.get("password").is_some_and(|pw| !pw.is_null()) {
return Err(CmdError::Params("`password` changes the document's own saves, so it can't come with `copy` (use file.encrypt)".into()));
}
if let Some(pw) = v.get("password").filter(|pw| !pw.is_null()) {
let Some(pw) = pw.as_str().filter(|pw| !pw.is_empty()) else {
return Err(CmdError::Params("`password` must be a non-empty string (file.encrypt removes a password)".into()));
@@ -443,11 +454,14 @@ fn save(s: &mut Session, v: &Value) -> CmdResult {
Some(text) => crate::io::save_text_path(&path, text),
None => crate::io::save_path_with(&path, copy.as_ref().unwrap_or(&s.doc), password, &opts),
};
if let Err(e) = written {
(s.doc.settings.zoom, s.doc.core.last_modified_by, s.doc.core.created, s.doc.core.modified, s.doc.core.revision) = before_stamp;
return Err(CmdError::Failed(e));
}
let encrypted = password.is_some() && crate::io::can_encrypt(&path.to_string_lossy());
if written.is_err() || as_copy {
(s.doc.settings.zoom, s.doc.core.last_modified_by, s.doc.core.created, s.doc.core.modified, s.doc.core.revision) = before_stamp;
}
written.map_err(CmdError::Failed)?;
if as_copy {
return Ok(json!({"saved": true, "path": path.to_string_lossy(), "encrypted": encrypted, "copy": true}));
}
// A save in a format that doesn't keep everything (plain text, Markdown, a page image) is a
// copy, except over the document's own file: a note.txt opened and saved is saved (#2376).
// A Markdown file saved as another one loses nothing its own save wouldn't: it moves there.
+2 -1
View File
@@ -209,7 +209,8 @@ fn target(s: &Session) -> Option<(Pos, Pos)> {
return Some((a, b));
}
let p = s.doc.para_at(&a)?;
let is_w = |c: char| c.is_alphanumeric() || c == '\'' || c == '_';
// Word takes a typographic apostrophe (’) like `'` here (#6517).
let is_w = |c: char| c.is_alphanumeric() || matches!(c, '\'' | '’' | '_');
let before = p.text.get(..a.off)?.chars().next_back();
let after = p.text.get(a.off..)?.chars().next();
if before.is_some_and(is_w) && after.is_some_and(is_w) {
+27 -10
View File
@@ -188,10 +188,14 @@ fn range_index_after_text(s: &Session) -> bool {
fn insert_index(s: &mut Session, v: &Value) -> CmdResult {
let instr = index_instr(v);
check_index_reachable(s)?;
// An index Word wrote as a range field is rebuilt by Update Index; Insert Index would add a
// second one beside it (#8034).
// An index Word wrote as a range field is first made a plain field in its own paragraph, as
// Update Index makes it, so it takes the new settings rather than a second index being added
// beside it (#8034).
if index_field(s).is_none() && has_index(s, true) {
return Err(CmdError::Failed("the document already has an index; use Update Index to rebuild it".into()));
super::citations::update_generated(s)?;
if index_field(s).is_none() {
return Err(CmdError::Failed("the document already has an index; use Update Index to rebuild it".into()));
}
}
match index_field(s) {
Some((i, _)) => {
@@ -640,10 +644,10 @@ End.",
assert!(!body_has_index(&s));
}
/// An index Word wrote as a range field in the main text is rebuilt by Update Index; Insert
/// Index says so instead of adding a second one (#8034).
/// An index Word wrote as a range field in the main text takes Insert Index's settings and is
/// rebuilt, rather than a second index being added at the caret (#8034).
#[test]
fn insert_index_leaves_a_range_field_index_in_the_main_text_to_update_index() {
fn insert_index_gives_a_range_field_index_in_the_main_text_its_settings() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Kilns are hot."));
s.run("select.text", &json!({"text": "Kilns"})).unwrap();
s.run("references.markEntry", &json!({})).unwrap();
@@ -654,10 +658,23 @@ End.",
para.insert_object(0, InlineObject::FieldStart { instr: r#"INDEX \h "A""#.into(), locked: false, dirty: false }, &CharProps::default())
.unwrap();
s.doc.insert_block(StoryRef::Body, &Path::top(at), wordcraft_doc::Block::Para(para)).unwrap();
let before = s.doc.body.len();
assert!(s.run("references.index", &json!({})).is_err());
assert_eq!(s.doc.body.len(), before, "no second index was added");
s.run("references.updateIndex", &json!({})).unwrap();
s.run("caret.docEnd", &json!({})).unwrap();
s.run("references.index", &json!({"columns": 2})).unwrap();
let instrs: Vec<String> = s
.doc
.body
.iter()
.filter_map(|b| b.as_para())
.flat_map(|p| p.objects.iter())
.filter_map(|o| match o {
InlineObject::Field { instr, .. } | InlineObject::FieldStart { instr, .. } if FieldCode::parse(instr).name == "INDEX" => {
Some(instr.clone())
}
_ => None,
})
.collect();
assert_eq!(instrs.len(), 1, "one index, not a second beside it: {instrs:?}");
assert!(FieldCode::parse(&instrs[0]).arg('c').is_some(), "the index took the new columns setting: {instrs:?}");
let text: String =
s.doc.body.iter().filter_map(|b| b.as_para()).map(|p| p.text.replace(wordcraft_doc::para::OBJ, "")).collect::<Vec<_>>().join(
"
+1 -1
View File
@@ -21,7 +21,7 @@ pub use items::{
};
use items::{cover_page, date_time, drop_cap, drop_cap_off, field, page_number, symbol};
use links::{bookmark, delete_bookmark, link, link_targets};
pub use links::{bookmark_name_ok, bookmark_range, bookmark_span};
pub use links::{bookmark_name_ok, bookmark_range, bookmark_span, selection_is_one_line};
pub use objects::{MAX_TABLE_ROWS, base64_decode, base64_encode};
use objects::{icon, shape, table, text_box};
pub(crate) use objects::{image_ext, picture};
+88 -11
View File
@@ -205,21 +205,26 @@ pub fn format_date_at_in(fmt: &str, lang: Option<&str>, unix: u64, offset_secs:
format_date_parts_in(fmt, lang, y, m as usize, d, hms, days)
}
/// Month and weekday names of a language, as Word writes them in date fields: full names, the
/// three-letter forms (`MMM`, `ddd`) being their first three letters, without a full stop.
/// Weekdays start on Thursday (1970-01-01).
/// Month and weekday names of a language, as Word writes them in date fields: full names and the
/// abbreviations used by `MMM` and `ddd`. Weekdays start on Thursday (1970-01-01).
struct DateNames {
/// Full month names (January through December).
months: [&'static str; 12],
/// Abbreviated month names for `MMM` (January through December).
months_short: [&'static str; 12],
/// Weekday names starting on Thursday (1970-01-01).
days: [&'static str; 7],
/// Abbreviated weekday names for `ddd`, starting on Thursday (1970-01-01).
days_short: [&'static str; 7],
/// The picture of a `DATE` field without `\@`.
default: &'static str,
}
const ENGLISH: DateNames = DateNames {
months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
months_short: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
days: ["Thursday", "Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday"],
days_short: ["Thu", "Fri", "Sat", "Sun", "Mon", "Tue", "Wed"],
default: "M/d/yyyy",
};
@@ -227,14 +232,46 @@ const ENGLISH: DateNames = DateNames {
/// `ddd` = `qui`, and `dd/MM/yyyy` for a field without a picture.
const PORTUGUESE: DateNames = DateNames {
months: ["janeiro", "fevereiro", "março", "abril", "maio", "junho", "julho", "agosto", "setembro", "outubro", "novembro", "dezembro"],
months_short: ["jan", "fev", "mar", "abr", "mai", "jun", "jul", "ago", "set", "out", "nov", "dez"],
days: ["quinta-feira", "sexta-feira", "sábado", "domingo", "segunda-feira", "terça-feira", "quarta-feira"],
days_short: ["qui", "sex", "sáb", "dom", "seg", "ter", "qua"],
default: "dd/MM/yyyy",
};
/// Choose month and weekday names according to the primary language subtag.
/// German (Word's Windows NLS forms): `MMMM` = `März`, `MMM` = `Mrz`, `ddd` = `Fr` (two
/// letters), and `dd.MM.yyyy` for a field without a picture. Covers de-DE, de-CH and bare `de`.
const GERMAN: DateNames = DateNames {
months: ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
months_short: ["Jan", "Feb", "Mrz", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"],
days: ["Donnerstag", "Freitag", "Samstag", "Sonntag", "Montag", "Dienstag", "Mittwoch"],
days_short: ["Do", "Fr", "Sa", "So", "Mo", "Di", "Mi"],
default: "dd.MM.yyyy",
};
/// Austrian Standard German: January is `Jänner`, abbreviated `Jän` (Österreichisches
/// Wörterbuch; Windows NLS `de-AT`). Every other month and weekday matches [`GERMAN`].
const GERMAN_AUSTRIA: DateNames = DateNames {
months: ["Jänner", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
months_short: ["Jän", "Feb", "Mrz", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"],
days: ["Donnerstag", "Freitag", "Samstag", "Sonntag", "Montag", "Dienstag", "Mittwoch"],
days_short: ["Do", "Fr", "Sa", "So", "Mo", "Di", "Mi"],
default: "dd.MM.yyyy",
};
/// Choose month and weekday names from the language tag: the primary subtag picks the language,
/// and a region subtag refines it (`de-AT` writes `Jänner`). Tags compare case-insensitively, as
/// `w:lang` values do.
fn date_names(lang: Option<&str>) -> &'static DateNames {
let primary = lang.and_then(|l| l.trim().split(['-', '_']).next()).unwrap_or("");
if primary.eq_ignore_ascii_case("pt") { &PORTUGUESE } else { &ENGLISH }
let mut subtags = lang.unwrap_or("").trim().split(['-', '_']);
let primary = subtags.next().unwrap_or("");
if primary.eq_ignore_ascii_case("pt") {
&PORTUGUESE
} else if primary.eq_ignore_ascii_case("de") {
// Austria keeps `Jänner` / `Jän`; Germany and Switzerland keep `Januar` / `Jan`.
if subtags.any(|region| region.eq_ignore_ascii_case("AT")) { &GERMAN_AUSTRIA } else { &GERMAN }
} else {
&ENGLISH
}
}
/// The picture Word gives a `DATE` field that has no `\@` switch, in the field's language.
@@ -252,9 +289,12 @@ pub fn format_date_parts(fmt: &str, y: i64, m: usize, d: u32, hms: (u32, u32, u3
#[allow(clippy::too_many_arguments)]
pub fn format_date_parts_in(fmt: &str, lang: Option<&str>, y: i64, m: usize, d: u32, (hh, mm, ss): (u32, u32, u32), days_since: i64) -> String {
let names = date_names(lang);
let month = names.months.get(m.saturating_sub(1)).copied().unwrap_or(names.months[0]);
let day = names.days.get(days_since.rem_euclid(7) as usize).copied().unwrap_or(names.days[0]);
let three = |s: &str| -> String { s.chars().take(3).collect() };
let mi = m.saturating_sub(1);
let di = days_since.rem_euclid(7) as usize;
let month = names.months.get(mi).copied().unwrap_or(names.months[0]);
let month_short = names.months_short.get(mi).copied().unwrap_or(names.months_short[0]);
let day = names.days.get(di).copied().unwrap_or(names.days[0]);
let day_short = names.days_short.get(di).copied().unwrap_or(names.days_short[0]);
let mut out = String::new();
let chars: Vec<char> = fmt.chars().collect();
let mut i = 0;
@@ -296,11 +336,11 @@ pub fn format_date_parts_in(fmt: &str, lang: Option<&str>, y: i64, m: usize, d:
('y' | 'Y', 4..) => out.push_str(&format!("{y:04}")),
('y' | 'Y', _) => out.push_str(&format!("{:02}", y % 100)),
('M', 4..) => out.push_str(month),
('M', 3) => out.push_str(&three(month)),
('M', 3) => out.push_str(month_short),
('M', 2) => out.push_str(&format!("{m:02}")),
('M', 1) => out.push_str(&m.to_string()),
('d' | 'D', 4..) => out.push_str(day),
('d' | 'D', 3) => out.push_str(&three(day)),
('d' | 'D', 3) => out.push_str(day_short),
('d' | 'D', 2) => out.push_str(&format!("{d:02}")),
('d' | 'D', 1) => out.push_str(&d.to_string()),
('H', 2..) => out.push_str(&format!("{hh:02}")),
@@ -574,6 +614,43 @@ mod date_time_locale_tests {
assert_eq!(format("MMMM", 20), "outubro");
}
/// German month and weekday names, and the default picture, are chosen by the language tag
/// (de-DE, de-AT, de-CH), as in Word (#7146).
#[test]
fn german_date_names_render_for_de() {
assert_eq!(format_date_parts_in("dddd, d. MMMM yyyy", Some("de-DE"), 2026, 11, 21, (12, 0, 0), 2), "Samstag, 21. November 2026");
assert_eq!(default_date_picture(Some("de-CH")), "dd.MM.yyyy");
}
/// Windows NLS short forms: two-letter weekdays (`Mo`, `Di`…) and `Mrz` for March, with no
/// trailing full stop (#7146).
#[test]
fn german_short_names_match_windows_nls() {
let format = |pic| format_date_parts_in(pic, Some("de-DE"), 2026, 3, 15, (12, 0, 0), 3);
assert_eq!(format("ddd, d. MMM yyyy"), "So, 15. Mrz 2026");
assert_eq!(format("dddd"), "Sonntag");
assert_eq!(format("MMM"), "Mrz");
}
/// Austrian Standard German writes January as `Jänner` (`Jän`), while Germany, Switzerland
/// and bare `de` keep `Januar` (`Jan`); every other name is shared (#7146).
#[test]
fn austrian_german_january_is_jaenner() {
let january = |lang, pic| format_date_parts_in(pic, Some(lang), 2026, 1, 15, (12, 0, 0), 0);
assert_eq!(january("de-AT", "MMMM"), "Jänner");
assert_eq!(january("de-AT", "MMM"), "Jän");
assert_eq!(january("de_at", "MMMM"), "Jänner", "region subtags compare case-insensitively");
for lang in ["de-DE", "de-CH", "de"] {
assert_eq!(january(lang, "MMMM"), "Januar", "{lang}");
assert_eq!(january(lang, "MMM"), "Jan", "{lang}");
}
// Only January differs: February and March read the same in Austria and Germany.
for month in [2, 3] {
let names = |lang| format_date_parts_in("MMMM MMM", Some(lang), 2026, month, 1, (12, 0, 0), 0);
assert_eq!(names("de-AT"), names("de-DE"));
}
}
/// A pt-BR dynamic field keeps its result after DOCX round-trip and refresh.
#[test]
fn pt_br_date_time_dialog_inserts_dynamic_field() {
+27 -12
View File
@@ -84,25 +84,40 @@ pub(super) fn link(s: &mut Session, v: &Value) -> CmdResult {
sel_result(s)
}
/// The `text` to retype a selection with before linking it: only when it differs from the selected
/// text and both fit in one line of one paragraph without pictures or fields, outside any field's
/// result. Otherwise (as Word shows `<<Selection in Document>>`) the selection keeps its text.
fn retyped_text(s: &Session, v: &Value) -> Option<String> {
/// What can't stand in one line of text: breaks, and pictures or fields.
const NOT_ONE_LINE: [char; 7] = {
use wordcraft_doc::para::{COLUMN_BREAK, LINE_BREAK, OBJ, PAGE_BREAK};
/// What can't stand in one line of text: breaks, and pictures or fields.
const NOT_ONE_LINE: [char; 7] = [LINE_BREAK, '\r', '\u{2029}', '\u{b}', PAGE_BREAK, COLUMN_BREAK, OBJ];
let text = p::str(v, "text").filter(|t| !t.is_empty() && t.len() <= 4096)?;
if text.contains(NOT_ONE_LINE) {
return None;
}
[LINE_BREAK, '\r', '\u{2029}', '\u{b}', PAGE_BREAK, COLUMN_BREAK, OBJ]
};
/// The raw text of the selection when it is one run of one paragraph without breaks, pictures or fields.
fn one_line_selection(s: &Session) -> Option<&str> {
let (a, b) = s.sel.ordered();
if a.story != b.story || a.path != b.path {
return None;
}
let shown = s.doc.para(a.story, &a.path)?.text.get(a.off..b.off)?;
if shown.contains(NOT_ONE_LINE) || shown == text {
s.doc.para(a.story, &a.path)?.text.get(a.off..b.off).filter(|t| !t.contains(NOT_ONE_LINE))
}
/// Whether the selection is plain text in one line of one paragraph: otherwise (as Word shows
/// `<<Selection in Document>>`) Text to display can't show it and linking keeps its content (#8286).
pub fn selection_is_one_line(s: &Session) -> bool {
one_line_selection(s).is_some()
}
/// The `text` to retype a selection with before linking it: only when it differs from the selected
/// text and both fit in one line of one paragraph without pictures or fields, outside any field's
/// result. Otherwise (as Word shows `<<Selection in Document>>`) the selection keeps its text.
fn retyped_text(s: &Session, v: &Value) -> Option<String> {
let text = p::str(v, "text").filter(|t| !t.is_empty() && t.len() <= 4096)?;
if text.contains(NOT_ONE_LINE) {
return None;
}
let shown = one_line_selection(s)?;
if shown == text {
return None;
}
let (a, b) = s.sel.ordered();
// A selection in a field's result (between its markers, which it doesn't hold) is retyped by
// the next update of the field, not here.
if s.doc.field_ranges(a.story).iter().any(|r| r.start < b && a <= r.end) {
+24 -10
View File
@@ -103,7 +103,7 @@ fn exact_text(s: &Session) -> Option<String> {
return res.clone();
}
let kept = [s.md_file.latest.as_deref(), s.md_file.saved.as_deref()];
let res = kept.into_iter().flatten().find(|text| parse(&s.doc, text).same_content(&s.doc)).map(str::to_string);
let res = kept.into_iter().flatten().find(|text| parse(&s.doc, text).is_ok_and(|d| d.same_content(&s.doc))).map(str::to_string);
*s.md_file.cached_exact.borrow_mut() = Some((s.rev(), res.clone()));
res
}
@@ -216,15 +216,16 @@ fn enter(s: &mut Session) -> Result<(), CmdError> {
// The file's own text when it still says what the document holds, so nothing is lost.
let (text, loses_content, block_lines) = match exact_text(s) {
Some(text) => {
let (_, lines) = parse_with_lines(&s.doc, &text);
let (_, lines) = parse_with_lines(&s.doc, &text)?;
(text, false, lines)
}
None => {
let text = wordcraft_formats::markdown::export(&s.doc);
let text = wordcraft_formats::markdown::export(&s.doc)
.map_err(|e| CmdError::Failed(format!("the document cannot be written as Markdown: {e}")))?;
if text.len() > MAX_SOURCE_BYTES {
return Err(CmdError::Failed(too_long()));
}
let (doc, lines) = parse_with_lines(&s.doc, &text);
let (doc, lines) = parse_with_lines(&s.doc, &text)?;
let loses_content = !doc.same_content(&s.doc);
(text, loses_content, lines)
}
@@ -289,7 +290,19 @@ pub fn apply(s: &mut Session) {
}
(src.text.clone(), src.entry_text.clone(), src.entry_doc.clone(), src.has_step, src.entry_lines.clone())
};
let (doc, lines) = if text == *entry_text { ((*entry_doc).clone(), entry_lines) } else { parse_with_lines(&s.doc, &text) };
let (doc, lines) = if text == *entry_text {
((*entry_doc).clone(), entry_lines)
} else {
// The text cannot be read as Markdown: the document stays as it is, rather than
// becoming an empty one.
match parse_with_lines(&s.doc, &text) {
Ok(v) => v,
Err(e) => {
s.status = e.to_string();
return;
}
}
};
let step = if !has_step {
s.checkpoint(LABEL);
Some(s.undo_mark())
@@ -313,19 +326,20 @@ pub fn apply(s: &mut Session) {
/// `text` as a document and block lines, with what isn't in Markdown from `current`: its page, settings,
/// properties and language, as opening the file gave it.
fn parse_with_lines(current: &Document, text: &str) -> (Document, Vec<usize>) {
let (mut doc, lines) = wordcraft_formats::markdown::import_on_with_lines(text, &current.last_section);
fn parse_with_lines(current: &Document, text: &str) -> Result<(Document, Vec<usize>), CmdError> {
let (mut doc, lines) = wordcraft_formats::markdown::import_on_with_lines(text, &current.last_section)
.map_err(|e| CmdError::Failed(format!("the Markdown cannot be read: {e}")))?;
doc.ensure_nonempty();
doc.settings = current.settings.clone();
doc.core = current.core.clone();
Arc::make_mut(&mut doc.styles).default_chr.lang = current.styles.default_chr.lang.clone();
(doc, lines)
Ok((doc, lines))
}
/// `text` as a document, with what isn't in Markdown from `current`: its page, settings,
/// properties and language, as opening the file gave it.
fn parse(current: &Document, text: &str) -> Document {
parse_with_lines(current, text).0
fn parse(current: &Document, text: &str) -> Result<Document, CmdError> {
parse_with_lines(current, text).map(|(doc, _)| doc)
}
/// The byte offset where `line` starts, or the end of a text with fewer lines.
+19
View File
@@ -278,4 +278,23 @@ mod tests {
assert_eq!(texts(&s), ["First one.", "Second one.", "Third one."]);
assert!(kinds(&mut s).is_empty());
}
/// A command that fails between a tracked cut and its paste changed nothing, so the move
/// the cut recorded is still there: the paste is a move, as it was before the command.
#[test]
fn a_failed_command_between_a_tracked_cut_and_its_paste_leaves_the_move() {
let mut s = Session::new(Document::new());
s.run("document.setText", &json!({"text": "First one.\nSecond one.\nThird one."})).unwrap();
s.run("file.setAuthor", &json!({"name": "Ana"})).unwrap();
s.run("review.trackChanges", &json!({"value": true})).unwrap();
s.run("select.range", &json!({"anchor": {"block": 1, "off": 0}, "focus": {"block": 2, "off": 0}})).unwrap();
s.run("edit.cut", &json!({})).unwrap();
// A command that fails: there is no such character style.
assert!(s.run("format.charStyle", &json!({"style": "NoSuchStyle"})).is_err());
s.run("caret.set", &json!({"pos": {"block": 0, "off": 0}})).unwrap();
s.run("edit.paste", &json!({})).unwrap();
let k = kinds(&mut s);
assert!(k.iter().any(|(k, m)| k == "moveTo" && m == "move1"), "{k:?}");
assert!(k.iter().any(|(k, m)| k == "moveFrom" && m == "move1"), "{k:?}");
}
}
+42 -13
View File
@@ -187,7 +187,7 @@ fn paste_special(s: &mut Session, v: &Value) -> CmdResult {
return Ok(r);
}
"formatted" => s.clipboard.clone().ok_or_else(|| CmdError::Failed("the clipboard is empty".into()))?,
"html" => adopt(s, import_html(&src)),
"html" => adopt(s, import_html(&src).map_err(|e| CmdError::Failed(format!("bad HTML: {e}")))?),
_ => adopt(s, wordcraft_formats::rtf::import(src.as_bytes()).map_err(|e| CmdError::Failed(format!("bad RTF: {e}")))?),
};
insert(s, frag)?;
@@ -204,8 +204,8 @@ const BLOCKQUOTE_INDENT: f32 = 36.0;
/// (#1270): it pastes as a Normal paragraph indented by the page's `blockquote` margins, else half
/// an inch each side, rather than in the (centred, italic) Quote style. Opening an .html file keeps
/// `<blockquote>` as Quote, so HTML round-trips.
fn import_html(html: &str) -> Document {
let mut doc = wordcraft_formats::html::import(html_fragment(html));
fn import_html(html: &str) -> Result<Document, String> {
let mut doc = wordcraft_formats::html::import(html_fragment(html))?;
let (left, right) = blockquote_margins(html);
for b in &mut doc.body {
each_para(Arc::make_mut(b), 0, &mut |p| {
@@ -217,7 +217,7 @@ fn import_html(html: &str) -> Document {
}
});
}
doc
Ok(doc)
}
/// The left and right margins (points) the payload's `<style>` sheets give `blockquote` — LibreOffice
@@ -294,7 +294,7 @@ fn has_content(d: &Document) -> bool {
/// [`MAX_PASTE_BYTES`], or it holds nothing to paste (the caller pastes the text then).
pub fn rich_fragment(s: &mut Session, v: &Value) -> Option<Fragment> {
let fits = |k: &str| p::str(v, k).filter(|t| !t.trim().is_empty() && t.len() <= MAX_PASTE_BYTES);
let doc = fits("html").map(import_html);
let doc = fits("html").and_then(|html| import_html(html).ok());
let doc = match doc.filter(has_content) {
Some(d) => d,
None => {
@@ -373,21 +373,22 @@ pub fn merge_formatting(s: &Session, frag: &mut Fragment) {
p.props = para.clone();
for run in &mut p.runs {
let src = std::mem::replace(&mut run.props, base.clone());
// Emphasis in either script is kept for both, as the Bold and Italic buttons set
// it: text pasted into a run marked `w:cs` (Thai from a WPS or Word file) is drawn
// with the complex-script bold and italic.
if src.bold == Some(true) || src.bold_cs == Some(true) {
let e = emphasis_of(s, &src);
// Emphasis the source shows in either script is kept for both, as the Bold and
// Italic buttons set it: text pasted into a run marked `w:cs` (Thai from a WPS or
// Word file) is drawn with the complex-script bold and italic.
if shown(e.bold, e.bold_cs, &e) {
run.props.bold = Some(true);
run.props.bold_cs = Some(true);
}
if src.italic == Some(true) || src.italic_cs == Some(true) {
if shown(e.italic, e.italic_cs, &e) {
run.props.italic = Some(true);
run.props.italic_cs = Some(true);
}
if src.underline.is_some_and(|u| u != wordcraft_doc::props::Underline::None) {
run.props.underline = src.underline;
if e.underline.is_some_and(|u| u != wordcraft_doc::props::Underline::None) {
run.props.underline = e.underline;
}
if src.strike == Some(true) {
if e.strike == Some(true) {
run.props.strike = Some(true);
}
run.props.link = src.link;
@@ -400,6 +401,34 @@ pub fn merge_formatting(s: &Session, frag: &mut Fragment) {
}
}
/// The formatting a pasted run's emphasis is judged by: its own, over its character style
/// chain's. Word keeps the bold, italic, underline and strikethrough a character style gives the
/// source, as direct formatting, but not a paragraph style's (measured in Word for Windows), so
/// the paragraph style isn't consulted.
fn emphasis_of(s: &Session, src: &wordcraft_doc::CharProps) -> wordcraft_doc::CharProps {
use wordcraft_doc::styles::StyleKind;
let mut e = wordcraft_doc::CharProps::default();
if let Some(id) = src.style.as_deref() {
for st in s.doc.styles.chain(id) {
if st.kind == StyleKind::Character || st.kind == StyleKind::Paragraph {
e.overlay(&st.chr);
}
}
}
e.overlay(&wordcraft_doc::CharProps { style: None, ..src.clone() });
e
}
/// Whether a run with these Latin and complex-script values of a toggle (bold or italic) shows
/// it anywhere, as the resolved formatting draws it: a run marked `w:cs` or `w:rtl` draws all
/// its text with the complex-script value, which borrows the Latin one unless the run is marked
/// `w:cs`; other runs draw their Latin text with the Latin value.
fn shown(latin: Option<bool>, complex: Option<bool>, run: &wordcraft_doc::CharProps) -> bool {
let complex_shown = complex.or(latin.filter(|_| run.cs != Some(true))) == Some(true);
let all_complex = run.cs == Some(true) || run.rtl == Some(true);
complex_shown || (!all_complex && latin == Some(true))
}
/// Paste `frag` at the selection. A copied table pasted with the caret in a table cell goes the way
/// Word's Paste does it (rows inserted or cells overwritten, #6739; see [`super::paste_cells`]);
/// anything else is [`insert_as_is`].
+10 -1
View File
@@ -305,7 +305,16 @@ pub(crate) fn greyed_out(s: &Session, id: &str, facts: impl FnOnce() -> Facts) -
}
}
let comment_ok = id.starts_with("review.") && (id.contains("Comment") || id == "review.reply");
let tracked = matches!(id, "review.accept" | "review.reject" | "review.acceptAll" | "review.rejectAll" | "review.trackChanges");
let tracked = matches!(
id,
"review.accept"
| "review.reject"
| "review.acceptAndNext"
| "review.rejectAndNext"
| "review.acceptAll"
| "review.rejectAll"
| "review.trackChanges"
);
match mode {
"readOnly" => (!facts().exceptions).then_some("the document is protected (read only)"),
"forms" => (facts().fillable == 0).then_some("the document is protected (read only)"),
+9 -1
View File
@@ -213,7 +213,15 @@ fn tracked_changes_protection_keeps_revisions() {
select(&mut s, "text");
s.run("text.insert", &json!({"text": "words"})).unwrap();
let before = s.doc.clone();
for id in ["review.acceptAll", "review.rejectAll", "review.accept", "review.reject", "review.trackChanges"] {
for id in [
"review.acceptAll",
"review.rejectAll",
"review.accept",
"review.reject",
"review.acceptAndNext",
"review.rejectAndNext",
"review.trackChanges",
] {
assert!(s.run(id, &json!({})).is_err(), "{id}");
}
assert_eq!(s.doc, before);
+7
View File
@@ -12,6 +12,7 @@ use crate::{CmdError, CmdResult, CommandSpec, Selection, Session, p};
mod changes;
mod comments;
mod proofing;
pub use proofing::thesaurus_word;
pub(crate) use changes::StyleTarget;
pub use changes::{
@@ -61,6 +62,12 @@ pub fn specs() -> Vec<CommandSpec> {
.params(r#"{"next"?: bool (then select the next change)}"#),
CommandSpec::new("review.reject", "Reject", "Review › Changes", |s, v| resolve_sel_then(s, v, false))
.params(r#"{"next"?: bool (then select the next change)}"#),
CommandSpec::new("review.acceptAndNext", "Accept and Move to Next", "Review › Changes", |s, _| {
resolve_sel_then(s, &json!({"next": true}), true)
}),
CommandSpec::new("review.rejectAndNext", "Reject and Move to Next", "Review › Changes", |s, _| {
resolve_sel_then(s, &json!({"next": true}), false)
}),
CommandSpec::new("review.nextChange", "Next Change", "Review › Changes", |s, _| nav_change(s, 1)).pure(),
CommandSpec::new("review.previousChange", "Previous Change", "Review › Changes", |s, _| nav_change(s, -1)).pure(),
CommandSpec::new("review.markup", "Display for Review", "Review › Tracking", |s, v| {
+30 -4
View File
@@ -53,10 +53,11 @@ fn resolve_para(
}
// An inserted paragraph mark that is rejected, or a deleted one that is accepted, goes away:
// the next paragraph joins this one (the split is undone). A paragraph left empty goes away
// whole, so the next one keeps its own style and numbering, as in Word. The mark at the end
// of a story or cell can't go, so it just stops being a revision. An empty paragraph whose
// mark carries a section break goes whole too: its section joins the following one, as when
// the break is deleted (#5667). Joining instead gave the next paragraph its properties.
// whole, so the next one keeps its own style and numbering, as in Word. The end mark of a
// story or cell has no follower to join here; `resolve_all` removes the whole paragraph
// instead when one is left over (see `remove_trailing_para`). An empty paragraph whose mark
// carries a section break goes whole too: its section joins the following one, as when the
// break is deleted (#5667). Joining instead gave the next paragraph its properties.
if (del.is_some() && accept) || (ins.is_some() && !accept) {
let sectioned = story == StoryRef::Body
&& path.0.len() == 1
@@ -76,6 +77,23 @@ fn resolve_para(
Ok(())
}
/// Remove the whole paragraph at `path` when a whole-paragraph revision on its mark resolved to
/// removal and it is the last paragraph in its container and carries no section break: it goes
/// away, as long as the container keeps another paragraph (a story or cell must never end up
/// with none). `false`, changing nothing, otherwise.
fn remove_trailing_para(s: &mut Session, story: StoryRef, path: &wordcraft_doc::Path) -> Result<bool, CmdError> {
let Some(p) = s.doc.para(story, path) else { return Ok(false) };
if !p.is_empty() || p.section.is_some() {
return Ok(false);
}
let Some(container) = s.doc.container(story, path) else { return Ok(false) };
if container.iter().filter(|b| b.as_para().is_some()).count() <= 1 {
return Ok(false);
}
s.doc.remove_block(story, path)?;
Ok(true)
}
/// Accept or reject the changes of the table cell `path` is in: the table's, its row's and the
/// cell's own. Returns whether there were any.
fn resolve_cell(s: &mut Session, story: StoryRef, path: &wordcraft_doc::Path, accept: bool) -> Result<bool, CmdError> {
@@ -245,8 +263,16 @@ fn resolve_all(s: &mut Session, accept: bool) -> CmdResult {
let stories: Vec<StoryRef> = std::iter::once(StoryRef::Body).chain(s.doc.parts.keys().map(|k| StoryRef::Part(*k))).collect();
for st in stories {
for path in s.doc.para_paths(st).into_iter().rev() {
// A whole-paragraph mark that resolves to removal at the end of its container takes
// the paragraph with it (there is no follower for `resolve_para` to join). A paragraph
// followed by a table is not the end: removing it could make two tables adjacent.
let is_last = s.doc.block(st, &path.with_last(path.last().saturating_add(1))).is_none();
let trailing = is_last && s.doc.para(st, &path).is_some_and(|p| (p.mark.del.is_some() && accept) || (p.mark.ins.is_some() && !accept));
let len = s.doc.para(st, &path).map(|p| p.len()).unwrap_or(0);
resolve_para(s, st, &path, (0, len), (true, true), accept)?;
if trailing {
remove_trailing_para(s, st, &path)?;
}
}
}
// Tables, rows, cells, sections and style definitions.
+16 -4
View File
@@ -128,6 +128,20 @@ pub(super) fn suggestions(s: &mut Session, v: &Value) -> CmdResult {
}
}
/// The word at the caret that the thesaurus looks up and a chosen synonym replaces: the word unit
/// without the spaces after it or the quotes around it, so `‘good’` is `good` and its quotes stay
/// when it is replaced; an apostrophe inside a word (`don’t`) is kept (#6517).
pub fn thesaurus_word(s: &Session) -> Option<(Pos, Pos)> {
let f = &s.sel.focus;
let p = s.doc.para_at(f)?;
let (a, b) = p.word_at(f.off);
let w = p.text.get(a..b)?;
let edge = |c: char| c.is_whitespace() || matches!(c, '’' | '‘' | '\'');
let start = a + (w.len() - w.trim_start_matches(edge).len());
let end = (a + w.trim_end_matches(edge).len()).max(start);
Some((Pos { off: start, ..f.clone() }, Pos { off: end, ..f.clone() }))
}
/// A tiny built-in thesaurus of common words (our own list).
pub(super) fn thesaurus(s: &mut Session, v: &Value) -> CmdResult {
const T: &[(&str, &[&str])] = &[
@@ -164,10 +178,8 @@ pub(super) fn thesaurus(s: &mut Session, v: &Value) -> CmdResult {
let word = match p::str(v, "word") {
Some(w) => w.to_lowercase(),
None => {
let f = s.sel.focus.clone();
let p = s.doc.para_at(&f).ok_or_else(|| CmdError::Failed("no word".into()))?;
let (a, b) = p.word_at(f.off);
p.text.get(a..b).unwrap_or("").trim().to_lowercase()
let (a, b) = thesaurus_word(s).ok_or_else(|| CmdError::Failed("no word".into()))?;
s.doc.para_at(&a).and_then(|p| p.text.get(a.off..b.off)).unwrap_or("").to_lowercase()
}
};
let syn = T.iter().find(|(w, _)| *w == word).map(|(_, l)| l.to_vec()).unwrap_or_default();
+15 -1
View File
@@ -703,6 +703,20 @@ fn accept_and_reject_can_move_to_the_next_change() {
}
}
#[test]
fn review_shortcut_commands_resolve_and_select_the_next_change_without_parameters() {
for (command, accept) in [("review.acceptAndNext", true), ("review.rejectAndNext", false)] {
let mut s = three_changes();
s.run("caret.docStart", &json!({})).unwrap();
s.run(command, &serde_json::Value::Null).unwrap();
let remaining = change_spans(&mut s);
assert_eq!(remaining.iter().map(|change| change.0.as_str()).collect::<Vec<_>>(), ["delete", "insert"], "{command}");
let (_, start, end) = remaining[0];
assert_eq!(selected(&s), (start as usize, end as usize), "{command}: the deletion is selected next");
assert_eq!(s.doc.plain_text(wordcraft_doc::StoryRef::Body).starts_with("new "), accept, "{command}");
}
}
/// With the caret on no change, Accept and Move to Next selects the next change without
/// resolving it, as Accept and Next Change do.
#[test]
@@ -1248,7 +1262,7 @@ fn rtf_tracked_changes_accept_and_reject_after_opening_and_round_trip() {
let rtf: &[u8] = br"{\rtf1\ansi\deff0{\fonttbl{\f0 Arial;}}{\*\revtbl {Unknown;}{Alice;}{Bob;}}
\pard Keep {\revised\revauth1\revdttm-1480361314 added }text{\deleted\revauthdel2\revdttmdel-2016341499 gone} end{\revised\revauth1\revdttm-1480361314\deleted\revauthdel2\revdttmdel-2016341499 both}.\par}";
let opened = wordcraft_formats::rtf::import(rtf).unwrap();
let again = wordcraft_formats::rtf::import(wordcraft_formats::rtf::export(&opened).as_bytes()).unwrap();
let again = wordcraft_formats::rtf::import(wordcraft_formats::rtf::export(&opened).unwrap().as_bytes()).unwrap();
for doc in [opened, again] {
for (cmd, want) in [("review.acceptAll", "Keep added text end."), ("review.rejectAll", "Keep text gone end.")] {
let mut s = Session::new(doc.clone());
+5 -6
View File
@@ -1622,12 +1622,11 @@ fn block_text(b: &Block, depth: usize) -> String {
/// the paragraph is empty (`format` returns early for a length-0 range). Walks nested tables
/// iteratively, without recursion or depth truncation.
///
/// Known limitation: resolving a revision needs a following paragraph, so a paragraph inserted at
/// the very end (rejected) or deleted from the very end (accepted) still leaves one empty
/// paragraph. That is a separate follow-up, not handled here. A section-carrying inserted
/// paragraph is not such a case: `resolve_para` removes the section break first (#5734, issue
/// #5667), so rejecting it takes the paragraph out whole and the following paragraph keeps its
/// own properties.
/// A whole-paragraph revision on the last paragraph of a story or cell is removed together with
/// the paragraph on Accept/Reject All (see `remove_trailing_para` in `review::changes`), except
/// where the paragraph carries a section break or is the container's only paragraph. A
/// non-terminal section-carrying paragraph is removed whole too: `resolve_para` removes the
/// section break first (#5734, issue #5667), so the following paragraph keeps its own properties.
fn mark_block(b: &Block, f: &dyn Fn(&mut CharProps)) -> Block {
let mut out = b.clone();
let mut todo = vec![&mut out];
+77 -14
View File
@@ -105,31 +105,49 @@ fn compare_keeps_another_authors_deletion_stamp() {
}
#[test]
fn compare_pins_the_terminal_inserted_paragraph_limitation() {
// Characterizes the limitation documented on `mark_block` (compare.rs): resolving a revision
// needs a following paragraph, so a paragraph inserted at the very end is rejected but leaves
// one empty paragraph behind. Flip this test when the follow-up fix lands.
fn compare_terminal_inserted_paragraph_resolves_fully() {
// A paragraph inserted at the very end is removed whole when rejected, leaving no empty
// paragraph behind.
let mut s = Session::new(Document::from_text("A\nB"));
s.run("review.compare", &json!({"text": "A\nB\nC"})).unwrap();
assert_eq!(s.doc.body.len(), 3);
s.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB\n", "the rejected terminal paragraph still leaves a line");
assert_eq!(s.doc.body.len(), 3);
assert_eq!(empty_paras(&s), 1, "the rejected terminal paragraph is left as one empty paragraph");
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
assert_eq!(s.doc.body.len(), 2);
assert_eq!(empty_paras(&s), 0, "rejecting a terminal inserted paragraph left an empty paragraph behind");
}
#[test]
fn compare_pins_the_terminal_deleted_paragraph_limitation() {
// The mirror of `compare_pins_the_terminal_inserted_paragraph_limitation`: a paragraph deleted
// from the very end is accepted but still leaves one empty paragraph. Characterizes the
// limitation documented on `mark_block` (compare.rs); flip when the follow-up fix lands.
fn compare_terminal_deleted_paragraph_resolves_fully() {
// The mirror of `compare_terminal_inserted_paragraph_resolves_fully`: a paragraph deleted
// from the very end is removed whole when accepted, leaving no empty paragraph behind.
let mut s = Session::new(Document::from_text("A\nB\nC"));
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
assert_eq!(s.doc.body.len(), 3);
s.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB\n", "the accepted terminal deletion still leaves a line");
assert_eq!(s.doc.body.len(), 3);
assert_eq!(empty_paras(&s), 1, "the accepted terminal deletion is left as one empty paragraph");
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
assert_eq!(s.doc.body.len(), 2);
assert_eq!(empty_paras(&s), 0, "accepting a terminal deleted paragraph left an empty paragraph behind");
}
#[test]
fn reject_all_keeps_an_empty_inserted_paragraph_between_tables() {
// An empty paragraph between two tables is not the container's last block: removing it
// would make the tables adjacent, and they would join into one on reopen. Reject All only
// clears its mark.
use wordcraft_doc::{Block, Paragraph, para_block};
let mut doc = Document::from_text("");
doc.revisions.push(wordcraft_doc::Revision::new(RevisionKind::Insert, "Alice", ""));
let table = || std::sync::Arc::new(Block::Table(wordcraft_doc::table::Table::new(1, 1, 100.0)));
let mut between = Paragraph::default();
between.mark.ins = Some(0);
doc.body = vec![table(), para_block(between), table(), para_block(Paragraph::with_text("end", Default::default()))];
let mut s = Session::new(doc);
s.run("review.rejectAll", &json!({})).unwrap();
let kinds: Vec<bool> = s.doc.body.iter().map(|b| matches!(**b, Block::Table(_))).collect();
assert_eq!(kinds, [true, false, true, false]);
let kept = s.doc.para(StoryRef::Body, &wordcraft_doc::Path::top(1)).unwrap();
assert!(kept.is_empty() && kept.mark.ins.is_none(), "{kept:?}");
}
#[test]
@@ -201,6 +219,51 @@ fn compare_pins_accepting_a_deleted_section_keeps_the_next_paragraphs_style() {
assert_eq!(body.props.style.as_deref(), Some("Heading1"), "the following paragraph keeps its own properties (fixed on main by #5734)");
}
#[test]
fn compare_marks_the_last_paragraphs_mark() {
// Inserted last paragraph: rejecting removes it whole.
let mut s = Session::new(Document::from_text("A\nB"));
s.run("review.compare", &json!({"text": "A\nB\nNEW"})).unwrap();
assert_eq!(s.doc.body.len(), 3);
assert!(s.doc.body[2].as_para().unwrap().mark.ins.is_some());
s.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
assert_eq!(s.doc.body.len(), 2);
assert_eq!(empty_paras(&s), 0);
let mut s = Session::new(Document::from_text("A\nB"));
s.run("review.compare", &json!({"text": "A\nB\nNEW"})).unwrap();
s.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB\nNEW");
assert_eq!(s.doc.body.len(), 3);
assert_eq!(empty_paras(&s), 0);
// Deleted last paragraph: accepting removes it whole.
let mut s = Session::new(Document::from_text("A\nB\nOLD"));
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
assert_eq!(s.doc.body.len(), 3);
assert!(s.doc.body[2].as_para().unwrap().mark.del.is_some());
s.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
assert_eq!(s.doc.body.len(), 2);
assert_eq!(empty_paras(&s), 0);
let mut s = Session::new(Document::from_text("A\nB\nOLD"));
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
s.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB\nOLD");
assert_eq!(s.doc.body.len(), 3);
assert_eq!(empty_paras(&s), 0);
}
#[test]
fn compare_keeps_the_only_paragraphs_mark() {
let mut s = Session::new(Document::from_text(""));
s.doc.revisions.push(wordcraft_doc::Revision::new(RevisionKind::Insert, s.author.clone(), ""));
s.doc.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap().mark.ins = Some(0);
s.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s.doc.body.len(), 1);
assert!(s.doc.body[0].as_para().unwrap().mark.ins.is_none());
}
#[test]
fn compare_options_ignore_case_and_white_space() {
let original = "The Cat sat.\nTwo spaces here.";
+6 -3
View File
@@ -284,14 +284,17 @@ fn import_chunk(c: &wordcraft_docx::AltChunk) -> Option<Document> {
|| matches!(ext.as_str(), "mht" | "mhtml")
|| mht::is_mht(b)
{
mht::import(b)
mht::import(b).map_err(|e| log::warn!("altChunk {}: the MHT cannot be read: {e}", c.part)).ok()?
} else if ct.contains("rtf") || ext == "rtf" || b.starts_with(b"{\\rtf") {
rtf::import(b).ok()?
rtf::import(b).map_err(|e| log::warn!("altChunk {}: the RTF cannot be read: {e}", c.part)).ok()?
} else if ct.contains("html") || matches!(ext.as_str(), "html" | "htm" | "xhtml") {
html::import_page(&html::decode_as(b, charset), &|_| None)
.map_err(|e| log::warn!("altChunk {}: the HTML cannot be read: {e}", c.part))
.ok()?
} else if ct == "text/plain" || ext == "txt" {
txt::import(b)
} else {
log::warn!("altChunk {}: its type ({ct}) is not one WordCraft reads", c.part);
return None;
};
// shortcut: pictures fit the chunk's default page, not the section it lands in; fit them there if wide pictures in chunks overflow narrow sections.
@@ -496,7 +499,7 @@ pub fn open_path_in(path: &std::path::Path, password: Option<&str>, region: &wor
// Pictures referenced by a relative path load from beside the HTML file.
let images = LocalImages::new(path.parent().unwrap_or(std::path::Path::new("")));
let html = wordcraft_formats::html::decode(&bytes);
let mut doc = wordcraft_formats::html::import_on(&html, &|src| images.load(src), &region_page(region));
let mut doc = wordcraft_formats::html::import_on(&html, &|src| images.load(src), &region_page(region))?;
fit_pictures(&mut doc);
opened(&mut doc);
return Ok((doc, false));
+1
View File
@@ -16,6 +16,7 @@ pub mod io;
mod io_ext;
pub mod keymap;
pub(crate) mod locale;
pub mod malloc_tuning;
pub mod math_gallery;
pub mod packs;
pub(crate) mod prefs;
+80
View File
@@ -0,0 +1,80 @@
//! glibc malloc tuning for native binaries (adapted from Storytold's `photocraft` #8743).
//!
//! With glibc's defaults, transient large buffers (page render targets, autofit tables, decoded
//! images) raise glibc's dynamic `mmap` and `trim` thresholds (up to 32 MiB on 64-bit), so later
//! heap allocations stay in glibc arenas instead of returning freed pages to the OS. Fixing
//! `MALLOC_TRIM_THRESHOLD_` at 128 KiB (`131072`) disables dynamic threshold growth so freed
//! pages above 128 KiB are returned cleanly while preserving multi-arena allocation throughput.
//!
//! Because glibc reads its malloc environment variables once at process start and mutating the
//! process environment in Rust requires `unsafe` (forbidden workspace-wide) and happens after glibc
//! initialization, [`apply`] re-executes the current executable via `exec` when no malloc tuning
//! variable is already set (keeping PID, argv, `argv[0]`, and environment). Setting any `MALLOC_*`
//! variable or `glibc.malloc.*` tunable opts out.
use std::ffi::OsString;
/// The glibc environment variable [`apply`] sets.
pub const TRIM_THRESHOLD_VAR: &str = "MALLOC_TRIM_THRESHOLD_";
/// Fixed trim threshold (128 KiB, glibc's initial default) to disable dynamic threshold escalation.
pub const TRIM_THRESHOLD: &str = "131072";
/// glibc malloc variables that indicate callers or wrappers already configured malloc tuning.
const MALLOC_VARS: [&str; 5] = [TRIM_THRESHOLD_VAR, "MALLOC_MMAP_THRESHOLD_", "MALLOC_TOP_PAD_", "MALLOC_MMAP_MAX_", "MALLOC_ARENA_MAX"];
/// Whether startup should re-execute with [`TRIM_THRESHOLD_VAR`] set, given an environment reader:
/// true only when no malloc variable or `glibc.malloc.*` tunable is present.
pub fn needs_restart(var: impl Fn(&str) -> Option<OsString>) -> bool {
if MALLOC_VARS.iter().any(|v| var(v).is_some()) {
return false;
}
!var("GLIBC_TUNABLES").is_some_and(|t| t.to_string_lossy().contains("glibc.malloc."))
}
/// Re-execute this binary with [`TRIM_THRESHOLD_VAR`] set when [`needs_restart`] is true.
///
/// Must be called early in `main()` before worker threads start or logs/crash hooks initialize.
/// Returns immediately if tuning variables are already present or if `exec` fails.
#[cfg(all(target_os = "linux", target_env = "gnu"))]
pub fn apply() {
use std::io::Write;
use std::os::unix::process::CommandExt;
if !needs_restart(|k| std::env::var_os(k)) {
return;
}
let Ok(exe) = std::env::current_exe() else { return };
let mut args = std::env::args_os();
let mut cmd = std::process::Command::new(exe);
if let Some(argv0) = args.next() {
cmd.arg0(argv0);
}
// `exec` replaces the current process in place and only returns on error.
let err = cmd.args(args).env(TRIM_THRESHOLD_VAR, TRIM_THRESHOLD).exec();
let _ = writeln!(std::io::stderr(), "wordcraft: could not restart with {TRIM_THRESHOLD_VAR} set ({err})");
}
/// No-op on platforms without Linux glibc.
#[cfg(not(all(target_os = "linux", target_env = "gnu")))]
pub fn apply() {}
#[cfg(test)]
mod tests {
use super::*;
fn env<'a>(vars: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<OsString> + 'a {
move |k| vars.iter().find(|(n, _)| *n == k).map(|(_, v)| OsString::from(v))
}
#[test]
fn restarts_only_without_malloc_tuning() {
assert!(needs_restart(env(&[])));
assert!(needs_restart(env(&[("HOME", "/home/a"), ("GLIBC_TUNABLES", "glibc.cpu.hwcaps=-AVX2")])));
assert!(!needs_restart(env(&[(TRIM_THRESHOLD_VAR, TRIM_THRESHOLD)])), "re-executed process stops");
assert!(!needs_restart(env(&[(TRIM_THRESHOLD_VAR, "")])), "any explicit value opts out");
assert!(!needs_restart(env(&[("MALLOC_MMAP_THRESHOLD_", "1048576")])));
assert!(!needs_restart(env(&[("MALLOC_ARENA_MAX", "2")])));
assert!(!needs_restart(env(&[("GLIBC_TUNABLES", "glibc.malloc.trim_threshold=0")])));
}
}
+33 -1
View File
@@ -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);
}
}
+18 -4
View File
@@ -27,13 +27,18 @@ struct ElsewhereContext {
blocks_before: Option<std::collections::BTreeMap<String, Fragment>>,
default_language_before: Option<String>,
pending_application_change_before: bool,
/// The tracked move the command would have dropped, put back when it fails.
move_before: Option<crate::cmd::moves::PendingMove>,
}
impl Session {
fn leave_math_for_command(&mut self, id: &str) {
self.math_left = false;
if self.math.is_some()
&& (id.starts_with("text.") || id.starts_with("caret.") || id.starts_with("select.") || id.starts_with("edit.paste"))
&& (id.starts_with("text.")
|| id.starts_with("caret.")
|| id.starts_with("select.")
|| (id.starts_with("edit.paste") && id != "edit.pasteFormat"))
&& let Some(m) = self.math.take()
{
let off = m.at.off + wordcraft_doc::para::OBJ.len_utf8();
@@ -213,7 +218,9 @@ impl Session {
} else if spec.id.starts_with("caret.") {
self.typing_open = false;
}
// Only the paste right after a tracked cut makes it a move.
// Only the paste right after a tracked cut makes it a move. A command that fails
// changed nothing, so the move it would have dropped is put back (below).
let move_before = self.pending_move.clone();
if (spec.mutates || matches!(id, "edit.undo" | "edit.undoTo" | "edit.redo")) && !matches!(id, "edit.cut" | "edit.paste" | "edit.pasteSpecial")
{
self.pending_move = None;
@@ -239,7 +246,7 @@ impl Session {
};
if self.document_id != home || (result.is_err() && self.order.iter().any(|d| *d >= mark)) {
return self.finish_elsewhere(
ElsewhereContext { home, mark, before_doc, blocks_before, default_language_before, pending_application_change_before },
ElsewhereContext { home, mark, before_doc, blocks_before, default_language_before, pending_application_change_before, move_before },
result,
);
}
@@ -304,6 +311,9 @@ impl Session {
self.join_anchor = false;
}
}
// The command failed, so the tracked move it would have dropped is still there:
// the paste after it is a move, as it was before the command.
self.pending_move = move_before;
if let Some(dirty) = dirty_before {
self.dirty = dirty;
}
@@ -482,7 +492,8 @@ impl Session {
/// as it was (opening a document is no edit to undo there). Failed: the documents the command opened close again and the first document is
/// active and as it was.
fn finish_elsewhere(&mut self, context: ElsewhereContext, result: Result<Value, CmdError>) -> Result<Value, CmdError> {
let ElsewhereContext { home, mark, before_doc, blocks_before, default_language_before, pending_application_change_before } = context;
let ElsewhereContext { home, mark, before_doc, blocks_before, default_language_before, pending_application_change_before, move_before } =
context;
// Another document is a state change the input method has to see, never an IME edit.
self.ime_edit_outcome = ImeEditOutcome::default();
match &result {
@@ -514,6 +525,9 @@ impl Session {
self.undo_evicted = ev;
self.column = c;
}
// The command failed, so the tracked move it would have dropped is still
// there: the paste after it is a move, as it was before the command.
self.pending_move = move_before;
}
if let Some(b) = blocks_before {
self.building_blocks = b;
+305 -1
View File
@@ -293,6 +293,15 @@ fn custom_dictionary_words_persist_through_their_file() {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn confined_sessions_test_is_native_only() {
let source = include_str!("tests.rs");
assert!(source.contains(
"#[cfg(not(target_arch = \"wasm32\"))]\n#[test]\nfn confined_sessions_neither_save_the_dictionary_nor_choose_folders_outside_their_roots()"
));
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn confined_sessions_neither_save_the_dictionary_nor_choose_folders_outside_their_roots() {
let _guard = crate::custom_dict::DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
@@ -1043,6 +1052,62 @@ fn bold_toggles_selection_and_caret_word() {
assert_eq!(p.props_of_char(9).italic, None);
}
#[test]
fn bold_at_a_caret_takes_a_word_with_a_typographic_apostrophe() {
// Word bolds `don’t` and `dogs’` whole: `’` is part of the word like `'` (#6517).
let bold_word = |text: &str, caret: usize| {
let mut s = s();
run(&mut s, "text.insert", json!({"text": text}));
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": caret}}));
run(&mut s, "format.bold", json!({}));
let p = s.doc.para_at(&Pos::body(0, 0)).unwrap().clone();
p.text.char_indices().filter(|&(i, _)| p.props_of_char(i).bold == Some(true)).map(|(_, c)| c).collect::<String>()
};
assert_eq!(bold_word("don’t stop", 1), "don’t");
assert_eq!(bold_word("the dogs’ bone", 5), "dogs’");
assert_eq!(bold_word("’tis here", 3), "’tis");
}
#[test]
fn select_word_takes_a_typographic_apostrophe() {
let mut s = s();
run(&mut s, "text.insert", json!({"text": "don’t stop"}));
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": 1}}));
run(&mut s, "select.word", json!({}));
let (a, b) = s.sel.ordered();
assert_eq!((a.off, b.off), (0, 8), "`don’t ` with its trailing space, as Word selects it (#6517)");
}
#[test]
fn thesaurus_at_a_caret_looks_up_a_quoted_word_without_its_quotes() {
// The word unit now takes `’`, so `‘good’` gives `good’`; the lookup drops enclosing quotes.
let mut s = s();
run(&mut s, "text.insert", json!({"text": "a ‘good’ day"}));
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": 6}}));
let r = run(&mut s, "review.thesaurus", json!({}));
assert_eq!(r["word"], json!("good"));
assert!(r["synonyms"].as_array().is_some_and(|a| !a.is_empty()), "{r}");
}
#[test]
fn a_synonym_replaces_the_word_and_keeps_its_quotes() {
// The range a chosen synonym replaces (the context menu's): the word without its quotes or the
// space after it, while an apostrophe inside a word stays part of it (#6517).
let word = |text: &str, caret: usize| {
let mut s = s();
run(&mut s, "text.insert", json!({"text": text, "raw": true}));
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": caret}}));
let (a, b) = crate::cmd::review::thesaurus_word(&s).unwrap();
s.set_selection(crate::Selection { anchor: a, focus: b });
run(&mut s, "text.insert", json!({"text": "fine", "raw": true}));
s.doc.plain_text(StoryRef::Body)
};
assert_eq!(word("a ‘good’ day", 6), "a ‘fine’ day");
assert_eq!(word("a 'good' day", 4), "a 'fine' day");
assert_eq!(word("a good day", 3), "a fine day");
assert_eq!(word("don’t go", 1), "fine go");
}
#[test]
fn border_toggles_and_saves() {
use wordcraft_doc::props::Border;
@@ -2054,6 +2119,88 @@ fn paste_merge_formatting_keeps_bold_and_italic_in_a_complex_script_run() {
assert!(r.bold_cs, "drawn bold as complex script");
}
#[test]
fn paste_merge_formatting_leaves_plain_what_the_source_draws_plain() {
// #4852 review: a run marked `w:cs` is bold and italic only by `w:bCs` and `w:iCs`, so one
// with `w:b` and `w:i` alone is drawn plain and pastes plain; one with `w:bCs` pastes bold.
let mut s = s();
run(&mut s, "document.setText", json!({"text": "x"}));
run(&mut s, "caret.docEnd", json!({}));
let pasted = |s: &Session, props: wordcraft_doc::CharProps| {
let mut frag = wordcraft_doc::edit::Fragment::from_text("ไทย");
for b in &mut frag.blocks {
crate::cmd::paste::each_para(b, 0, &mut |p| p.runs.iter_mut().for_each(|r| r.props = props.clone()));
}
crate::cmd::paste::merge_formatting(s, &mut frag);
let mut out = Vec::new();
for b in &mut frag.blocks {
crate::cmd::paste::each_para(b, 0, &mut |p| out.extend(p.runs.iter().map(|r| s.doc.styles.resolve_char(None, &r.props))));
}
out
};
let cs = wordcraft_doc::CharProps { cs: Some(true), bold: Some(true), italic: Some(true), ..Default::default() };
for r in pasted(&s, cs.clone()) {
assert!(!r.bold && !r.bold_cs && !r.italic && !r.italic_cs, "{r:?}");
}
for r in pasted(&s, wordcraft_doc::CharProps { bold_cs: Some(true), ..cs }) {
assert!(r.bold && r.bold_cs && !r.italic_cs, "{r:?}");
}
// An unmarked run shows `w:b` in both scripts.
for r in pasted(&s, wordcraft_doc::CharProps { bold: Some(true), ..Default::default() }) {
assert!(r.bold && r.bold_cs, "{r:?}");
}
}
#[test]
fn paste_merge_formatting_keeps_a_character_styles_emphasis_not_a_paragraph_styles() {
// #7177 review, measured in Word for Windows: Merge Formatting keeps the bold, italic,
// underline and strikethrough a character style gives the source, as direct formatting, but
// drops a paragraph style's.
use wordcraft_doc::props::Underline;
use wordcraft_doc::styles::{Style, StyleKind};
let mut s = s();
run(&mut s, "document.setText", json!({"text": "x"}));
run(&mut s, "caret.docEnd", json!({}));
let on = wordcraft_doc::CharProps {
bold: Some(true),
bold_cs: Some(true),
italic: Some(true),
italic_cs: Some(true),
underline: Some(Underline::Single),
strike: Some(true),
..Default::default()
};
let sheet = Arc::make_mut(&mut s.doc.styles);
sheet.upsert(Style { id: "ChEmph".into(), name: "ChEmph".into(), kind: StyleKind::Character, chr: on.clone(), ..Default::default() });
sheet.upsert(Style { id: "PEmph".into(), name: "PEmph".into(), kind: StyleKind::Paragraph, chr: on, ..Default::default() });
let pasted = |s: &Session, para_style: Option<&str>, props: wordcraft_doc::CharProps| {
let mut frag = wordcraft_doc::edit::Fragment::from_text("ไทย Thai");
for b in &mut frag.blocks {
crate::cmd::paste::each_para(b, 0, &mut |p| {
p.props.style = para_style.map(str::to_string);
p.runs.iter_mut().for_each(|r| r.props = props.clone());
});
}
crate::cmd::paste::merge_formatting(s, &mut frag);
let mut out = Vec::new();
for b in &mut frag.blocks {
crate::cmd::paste::each_para(b, 0, &mut |p| {
out.extend(p.runs.iter().map(|r| s.doc.styles.resolve_char(p.props.style.as_deref(), &r.props)));
});
}
out
};
for cs in [None, Some(true)] {
for r in pasted(&s, None, wordcraft_doc::CharProps { style: Some("ChEmph".into()), cs, ..Default::default() }) {
assert!(r.bold && r.bold_cs && r.italic && r.italic_cs && r.strike, "character style, cs {cs:?}: {r:?}");
assert_eq!(r.underline, Underline::Single, "character style, cs {cs:?}");
}
for r in pasted(&s, Some("PEmph"), wordcraft_doc::CharProps { cs, ..Default::default() }) {
assert!(!r.bold && !r.bold_cs && !r.italic && !r.italic_cs && !r.strike, "paragraph style, cs {cs:?}: {r:?}");
assert_eq!(r.underline, Underline::None, "paragraph style, cs {cs:?}");
}
}
}
#[test]
fn pasted_rtf_sections_link_their_headers_to_the_previous() {
// #1378: the RTF's own header part ids mean nothing in this document; a pasted section
@@ -7301,6 +7448,64 @@ fn saving_a_text_file_over_itself_saves_the_document() {
let _ = std::fs::remove_dir_all(&dir);
}
/// #6131: File › Export to DOCX, ODT or RTF writes a copy (`copy: true`). It made the copy the
/// document's file and cleared its unsaved changes, so the next Save went to the copy and the
/// original kept its old text. The copy has the edits; the document keeps its file, its changes
/// and its save stamps.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn exporting_a_copy_keeps_the_documents_file() {
let dir = std::env::temp_dir().join(format!("wordcraft-engine-export-copy-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let body = |p: &std::path::Path| crate::io::open_path(p).unwrap().plain_text(wordcraft_doc::StoryRef::Body);
for ext in ["docx", "odt", "rtf"] {
let original = dir.join(format!("a-{ext}.docx"));
let mut s = Session::new(wordcraft_doc::Document::new());
run(&mut s, "text.insert", json!({"text": "first"}));
run(&mut s, "file.save", json!({"path": original.to_string_lossy()}));
run(&mut s, "text.insert", json!({"text": " edited"}));
let stamps = (s.doc.core.revision, s.doc.core.modified.clone());
let copy = dir.join(format!("copy.{ext}"));
let r = run(&mut s, "file.saveAs", json!({"path": copy.to_string_lossy(), "copy": true}));
assert_eq!(r["saved"], true, "{ext}");
assert_eq!(body(&copy), "first edited", "{ext}: the copy has the edits");
assert_eq!(s.path.as_deref(), Some(original.as_path()), "{ext}: the document keeps its file");
assert!(s.dirty, "{ext}: the document keeps its unsaved changes");
assert_eq!((s.doc.core.revision, s.doc.core.modified.clone()), stamps, "{ext}: the document's save stamps are untouched");
run(&mut s, "file.save", json!({}));
assert_eq!(body(&original), "first edited", "{ext}: Save still writes the original");
assert!(!s.dirty);
}
let _ = std::fs::remove_dir_all(&dir);
}
/// A copy with no path would open the Save As picker on an untitled document (whose answer is an
/// ordinary save that adopts the file) or fall back to the open file's path and overwrite it while
/// leaving the document dirty: refused in both cases (#6131 review).
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_copy_without_a_path_is_refused() {
let mut s = Session::new(wordcraft_doc::Document::new());
run(&mut s, "text.insert", json!({"text": "first"}));
let e = s.run("file.save", &json!({"copy": true})).unwrap_err();
assert!(e.to_string().contains("copy"), "{e}");
assert!(s.ui_requests.is_empty(), "no picker opens");
let dir = std::env::temp_dir().join(format!("wordcraft-engine-copy-no-path-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let original = dir.join("doc.docx");
run(&mut s, "file.save", json!({"path": original.to_string_lossy()}));
run(&mut s, "text.insert", json!({"text": " edited"}));
let e = s.run("file.save", &json!({"copy": true})).unwrap_err();
assert!(e.to_string().contains("copy"), "{e}");
assert!(s.dirty, "the document keeps its unsaved changes");
let on_disk = crate::io::open_path(&original).unwrap().plain_text(wordcraft_doc::StoryRef::Body);
assert_eq!(on_disk, "first", "the original file on disk was not overwritten");
let _ = std::fs::remove_dir_all(&dir);
}
/// A Markdown file saved as another Markdown file is that file from now on: the next save goes
/// there and the first file stays as it was. Other formats keep the #2376 rule.
#[cfg(not(target_arch = "wasm32"))]
@@ -7407,7 +7612,6 @@ fn scratch_dir(name: &str) -> std::path::PathBuf {
dir
}
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn tiny_png() -> Vec<u8> {
wordcraft_geom::picture::encode_format(
&image::DynamicImage::from(image::RgbaImage::from_pixel(2, 2, image::Rgba([200, 30, 30, 255])).clone()),
@@ -9734,6 +9938,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.
@@ -9806,6 +10081,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();
@@ -15341,6 +15619,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"))]
+10 -1
View File
@@ -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");
}
}
+99
View File
@@ -129,6 +129,105 @@ fn a_date_field_in_a_header_is_refreshed_too() {
assert_eq!(found, [today], "the header's field is refreshed as well as the body's");
}
/// A document whose `docDefaults` set `lang`, so a field run that names no language inherits it,
/// as a German Word document does.
fn open_body_in_lang(lang: &str, body: &str) -> wordcraft_doc::Document {
let rels = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
let doc_rels = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rIdStyles" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>"#;
let styles = format!(
r#"<?xml version="1.0" encoding="UTF-8"?><w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:docDefaults><w:rPrDefault><w:rPr><w:lang w:val="{lang}"/></w:rPr></w:rPrDefault></w:docDefaults><w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style></w:styles>"#
);
let doc = format!(
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
);
wordcraft_engine::io::open_bytes(
"d.docx",
&zip(&[("_rels/.rels", rels), ("word/document.xml", &doc), ("word/_rels/document.xml.rels", doc_rels), ("word/styles.xml", &styles)]),
)
.expect("opens")
}
/// German documents carry their language in `docDefaults`, not on each field run. A `DATE` field
/// without `\@` therefore uses `dd.MM.yyyy`, and `MMMM`/`dddd` name the day in German, on open
/// and on an explicit refresh, for `de-DE`, `de-AT` and `de-CH` (#7146).
#[test]
fn german_date_fields_inherit_the_document_default_language() {
const PICTURE: &str = "dddd, d. MMMM yyyy";
for lang in ["de-DE", "de-AT", "de-CH"] {
let d = open_body_in_lang(
lang,
&format!(
"<w:p>{}</w:p><w:p>{}</w:p>",
field(&format!(r#"DATE \@ "{PICTURE}""#), "Wednesday, 1 January 2020", false),
field("DATE", "1/1/2020", false)
),
);
let expected = wordcraft_engine::cmd::insert::format_date_in(PICTURE, Some(lang));
let got = fields(&d);
assert_eq!(got.len(), 2, "{lang}");
assert_eq!(got[0].1, expected, "{lang}: weekday and month names come from docDefaults");
assert_ne!(got[0].1, wordcraft_engine::cmd::insert::format_date_in(PICTURE, None), "{lang}: not the English names");
assert_eq!(
got[1].1,
wordcraft_engine::cmd::insert::format_date_in("dd.MM.yyyy", Some(lang)),
"{lang}: a DATE field without a picture uses the German default"
);
// Saving and reopening keeps the inherited language, and an explicit refresh does not
// fall back to English.
let written = wordcraft_docx::write(&d).unwrap();
let mut reopened = wordcraft_engine::io::open_bytes("reopened.docx", &written).unwrap();
wordcraft_engine::cmd::references::refresh_date_fields(&mut reopened);
let got = fields(&reopened);
assert_eq!(got[0].1, expected, "{lang}: after round-trip");
assert_eq!(got[1].1, wordcraft_engine::cmd::insert::format_date_in("dd.MM.yyyy", Some(lang)), "{lang}: after round-trip");
}
}
/// `MMM` and `ddd` use Word's Windows NLS short forms for German: two-letter weekdays (`So`,
/// `Mo`…) and `Mrz` for March, with no trailing full stop (#7146).
#[test]
fn a_german_short_date_field_uses_windows_nls_abbreviations() {
const PICTURE: &str = "ddd, d. MMM yyyy";
let d = open_body_in_lang("de-DE", &format!("<w:p>{}</w:p>", field(&format!(r#"DATE \@ "{PICTURE}""#), "Wed, 1 Jan 2020", false)));
let got = fields(&d);
assert_eq!(got[0].1, wordcraft_engine::cmd::insert::format_date_in(PICTURE, Some("de-DE")));
// The abbreviations at a fixed date, independent of when the test runs.
assert_eq!(wordcraft_engine::cmd::insert::format_date_parts_in(PICTURE, Some("de-DE"), 2026, 3, 15, (12, 0, 0), 3), "So, 15. Mrz 2026");
}
/// A `TIME` field whose picture carries German name tokens inherits the language too, so the
/// English result cached in the fixture is replaced with German weekday and month names.
#[test]
fn a_german_time_field_uses_german_names() {
const PICTURE: &str = "dddd, d. MMMM yyyy 'um' HH:mm";
let d =
open_body_in_lang("de-DE", &format!("<w:p>{}</w:p>", field(&format!(r#"TIME \@ "{PICTURE}""#), "Wednesday, 1 January 2020 um 00:00", false)));
let got = fields(&d);
assert_eq!(got[0].0, format!(r#"TIME \@ "{PICTURE}""#));
assert_eq!(got[0].1, wordcraft_engine::cmd::insert::format_date_in(PICTURE, Some("de-DE")));
}
/// Austrian Standard German writes January as `Jänner` (`Jän`), while Germany, Switzerland and
/// bare `de` keep `Januar` (`Jan`), as in Windows NLS (#7146). A `de-AT` document reads German
/// through `docDefaults`; the refresh always uses the real clock, so the January names are asked
/// of the same formatter at a fixed January instant.
#[test]
fn austrian_german_documents_use_jaenner() {
const PICTURE: &str = "dddd, d. MMMM yyyy";
let d = open_body_in_lang("de-AT", &format!("<w:p>{}</w:p>", field(&format!(r#"DATE \@ "{PICTURE}""#), "Wednesday, 1 January 2020", false)));
let got = fields(&d);
assert_eq!(got[0].1, wordcraft_engine::cmd::insert::format_date_in(PICTURE, Some("de-AT")), "an Austrian document reads German");
let january = |lang: &str, picture: &str| wordcraft_engine::cmd::insert::format_date_parts_in(picture, Some(lang), 2026, 1, 15, (12, 0, 0), 0);
assert_eq!(january("de-AT", "MMMM"), "Jänner");
assert_eq!(january("de-AT", "MMM"), "Jän");
assert_eq!(january("de-AT", PICTURE), "Donnerstag, 15. Jänner 2026");
for lang in ["de-DE", "de-CH", "de"] {
assert_eq!(january(lang, "MMMM"), "Januar", "{lang}");
assert_eq!(january(lang, "MMM"), "Jan", "{lang}");
}
}
/// A minimal Word 97-2003 file whose only paragraph holds a `DATE` field cached as " 2001":
/// FIB, one compressed text piece, and the Clx that points at it.
fn binary_doc_with_stale_date() -> Vec<u8> {
+1
View File
@@ -1,4 +1,5 @@
mod comment_ids;
mod content_controls;
mod date_fields;
mod macro_packages;
mod odt_charts;
+49 -7
View File
@@ -25,7 +25,7 @@ mod lookup;
mod names;
use face::{BUNDLED, FontBytes};
pub use face::{FALLBACK_FAMILY, FaceRef, FontFace, bundled};
pub use face::{FALLBACK_FAMILY, FaceRef, FontFace, bundled, bundled_inter};
#[cfg(test)]
use fallback_data::{Coverage, RUN_FALLBACK_CACHE_CHARS, SYS_FALLBACK_MAX_FILE, file_coverage, ranges_hold};
#[cfg(not(target_arch = "wasm32"))]
@@ -42,14 +42,52 @@ pub(crate) use names::{last_resort_face, legacy_family};
static GLOBAL: std::sync::OnceLock<FontDb> = std::sync::OnceLock::new();
/// Fixed-capacity FIFO cache shared by outline and hinting tables so old zoom/script entries evict
/// incrementally instead of wiping the whole table at once.
pub(super) struct BoundedCache<K, V> {
map: HashMap<K, V>,
order: std::collections::VecDeque<K>,
cap: usize,
}
impl<K: Eq + std::hash::Hash + Clone, V> BoundedCache<K, V> {
pub(super) fn new(cap: usize) -> Self {
Self { map: HashMap::new(), order: std::collections::VecDeque::new(), cap: cap.max(1) }
}
pub(super) fn get(&self, key: &K) -> Option<&V> {
self.map.get(key)
}
pub(super) fn insert(&mut self, key: K, val: V) {
if let Some(existing) = self.map.get_mut(&key) {
*existing = val;
return;
}
while self.map.len() >= self.cap {
let Some(oldest) = self.order.pop_front() else {
break;
};
self.map.remove(&oldest);
}
self.order.push_back(key.clone());
self.map.insert(key, val);
}
#[cfg(test)]
pub(super) fn len(&self) -> usize {
self.map.len()
}
}
/// Process-wide font database.
pub struct FontDb {
faces: RwLock<Vec<Arc<FontFace>>>,
outlines: Mutex<HashMap<(u32, u32), Arc<BezPath>>>,
outlines: Mutex<BoundedCache<(u32, u32), Arc<BezPath>>>,
/// Screen-hinted outlines per (face, glyph, ppem bits); `None` where the face can't be hinted.
hinted: Mutex<HashMap<(u32, u32, u32), Option<Arc<BezPath>>>>,
hinted: Mutex<BoundedCache<(u32, u32, u32), Option<Arc<BezPath>>>>,
/// Light hinting instances per (face, ppem bits); `None` where the face can't be hinted.
hinters: Mutex<HashMap<(u32, u32), Option<Arc<HintingInstance>>>>,
hinters: Mutex<BoundedCache<(u32, u32), Option<Arc<HintingInstance>>>>,
/// Fallback faces found per (character, excluded face), valid while the face count is the
/// one stored (faces are only ever added). Layout asks once per uncovered character, and the
/// search sorts every loaded face, so without this text in a script the requested font lacks
@@ -63,6 +101,8 @@ pub struct FontDb {
diagram_search_hook: Mutex<Option<Box<dyn FnOnce(&FontDb) + Send>>>,
#[cfg(test)]
diagram_publish_hook: Mutex<Option<Box<dyn FnOnce(&FontDb) + Send>>>,
#[cfg(test)]
run_style_hook: Mutex<Option<Box<dyn FnOnce(&FontDb) + Send>>>,
#[cfg(not(target_arch = "wasm32"))]
catalog: RwLock<Vec<CatalogEntry>>,
/// Fonts the user added at run time, and the folder they are stored in (#582).
@@ -121,9 +161,9 @@ impl FontDb {
}
Self {
faces: RwLock::new(faces),
outlines: Mutex::new(HashMap::new()),
hinted: Mutex::new(HashMap::new()),
hinters: Mutex::new(HashMap::new()),
outlines: Mutex::new(BoundedCache::new(face::OUTLINE_CACHE_MAX)),
hinted: Mutex::new(BoundedCache::new(face::HINTED_CACHE_MAX)),
hinters: Mutex::new(BoundedCache::new(face::HINTER_CACHE_MAX)),
fallbacks: RwLock::new(FallbackCache::default()),
run_fallbacks: RwLock::new(RunFallbackCache::default()),
diagram_fallbacks: RwLock::new(DiagramFallbackCache::default()),
@@ -133,6 +173,8 @@ impl FontDb {
diagram_search_hook: Mutex::new(None),
#[cfg(test)]
diagram_publish_hook: Mutex::new(None),
#[cfg(test)]
run_style_hook: Mutex::new(None),
#[cfg(not(target_arch = "wasm32"))]
catalog: RwLock::new(Vec::new()),
user: RwLock::new(user::UserFonts::default()),
+18 -4
View File
@@ -13,6 +13,16 @@ pub fn bundled() -> &'static [&'static [u8]] {
BUNDLED
}
/// The bundled Inter Regular and SemiBold, each with its style name: the same bytes as in [`bundled`], so a caller
/// adds no second copy to the binary. The interface draws with them behind the suite's Inter, which is cut to Latin,
/// Greek and Cyrillic.
pub fn bundled_inter() -> [(&'static str, &'static [u8]); 2] {
[("Regular", INTER_REGULAR), ("SemiBold", INTER_SEMIBOLD)]
}
static INTER_REGULAR: &[u8] = include_bytes!("../../../../assets/fonts/Inter-Regular.ttf");
static INTER_SEMIBOLD: &[u8] = include_bytes!("../../../../assets/fonts/Inter-SemiBold.ttf");
pub(super) static BUNDLED: &[&[u8]] = &[
include_bytes!("../../../../assets/fonts/SourceSans3-Regular.ttf"),
include_bytes!("../../../../assets/fonts/SourceSans3-Semibold.ttf"),
@@ -23,9 +33,9 @@ pub(super) static BUNDLED: &[&[u8]] = &[
include_bytes!("../../../../assets/fonts/SourceSerif4-Semibold.ttf"),
include_bytes!("../../../../assets/fonts/SourceSerif4-Bold.ttf"),
include_bytes!("../../../../assets/fonts/SourceSerif4-BoldIt.ttf"),
include_bytes!("../../../../assets/fonts/Inter-Regular.ttf"),
INTER_REGULAR,
include_bytes!("../../../../assets/fonts/Inter-Medium.ttf"),
include_bytes!("../../../../assets/fonts/Inter-SemiBold.ttf"),
INTER_SEMIBOLD,
include_bytes!("../../../../assets/fonts/JetBrainsMono-Regular.ttf"),
];
@@ -541,9 +551,13 @@ fn is_explicit_serif(name: &str) -> bool {
pub(super) static NEXT_ID: AtomicU32 = AtomicU32::new(1);
pub(super) const OUTLINE_CACHE_MAX: usize = 50_000;
/// Unhinted glyph outlines kept per (face, glyph).
pub(super) const OUTLINE_CACHE_MAX: usize = 16_384;
/// Screen-hinted outlines kept per (face, glyph, ppem bits); narrower than [`OUTLINE_CACHE_MAX`]
/// because zoom changes create entries per size.
pub(super) const HINTED_CACHE_MAX: usize = 8_192;
/// Hinting instances kept (one per face and text size on screen).
pub(super) const HINTER_CACHE_MAX: usize = 256;
pub(super) const HINTER_CACHE_MAX: usize = 128;
/// Sizes hinted, in device pixels per em: below, text is too small to read anyway; above, the
/// half-pixel hinting moves is invisible (and each size would cost a cache entry).
pub(super) const HINT_PPEM: std::ops::RangeInclusive<f32> = 4.0..=96.0;
+66 -9
View File
@@ -1,9 +1,10 @@
use super::face::{FALLBACK_FAMILY, FontFace};
use super::fallback_data::{
BALLOT_BOXES, DiagramFallbackKey, FALLBACK_CACHE_MAX, RTL_FALLBACKS, RUN_FALLBACK_CACHE_CHARS, RUN_FALLBACK_CACHE_MAX, arabic_block,
fallback_order,
};
#[cfg(not(target_arch = "wasm32"))]
use super::fallback_data::{CoverageIndex, IndexedFile, SYS_MISSES_MAX, SYSTEM_FALLBACKS, file_stamp, ranges_hold, read_fallback_file};
use super::fallback_data::{
DiagramFallbackKey, FALLBACK_CACHE_MAX, RTL_FALLBACKS, RUN_FALLBACK_CACHE_CHARS, RUN_FALLBACK_CACHE_MAX, arabic_block, fallback_order,
};
use super::{Arc, FontDb};
#[cfg(not(target_arch = "wasm32"))]
use super::{HashMap, Ordering};
@@ -28,7 +29,11 @@ impl FontDb {
_ => "Italic",
};
let styled = self.face(&base.family, style);
Some(if styled.family.eq_ignore_ascii_case(&base.family) && styled.covers(c) && styled.id != exclude { styled } else { base })
Some(if styled.family.eq_ignore_ascii_case(&base.family) && styled_covers(&styled, &base, &[c]) && styled.id != exclude {
styled
} else {
base
})
}
/// The fallback search, cached per (character, excluded face) until loaded faces or font
@@ -70,6 +75,9 @@ impl FontDb {
if let Some(face) = self.circle_fallback(c, exclude) {
return (Some(face), self.read_faces().len());
}
if let Some((face, n)) = self.ballot_box_fallback(c, exclude) {
return (Some(face), n);
}
let (found, n) = self.loaded_fallback(c, exclude);
if found.is_some() {
return (found, n);
@@ -97,6 +105,38 @@ impl FontDb {
find()
}
/// A ballot box (☐ ☑ ☒, a check box's symbols) the face lacks: the first of the symbol faces
/// ([`crate::word::SYMBOL`], in that order) that has all three, so a check box looks the same
/// ticked and unticked (#7863). The UI fallback has ☐, drawn with a drop shadow, and ☑ but no
/// ☒, which put a box's two states in different fonts. `None` when no listed face has all
/// three: the ordinary fallback then. With the face, the number of loaded faces before the
/// search: a face loaded during it (by it, or by another thread for a family it had passed)
/// leaves that number behind, so the answer isn't cached for the new face list.
fn ballot_box_fallback(&self, c: char, exclude: u32) -> Option<(Arc<FontFace>, usize)> {
if !BALLOT_BOXES.contains(&c) {
return None;
}
let n = self.read_faces().len();
let all = |f: &Arc<FontFace>| f.id != exclude && BALLOT_BOXES.iter().all(|b| f.covers(*b));
for family in crate::word::SYMBOL {
if let Some(face) = self.find(family, "Regular").filter(all) {
return Some((face, n));
}
// An installed family is loaded only when its files map all three.
#[cfg(not(target_arch = "wasm32"))]
{
let enabled = self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).enabled;
if enabled && !self.is_loaded(family) && BALLOT_BOXES.iter().all(|b| self.family_maps(family, *b)) {
self.load_cataloged(family);
if let Some(face) = self.find(family, "Regular").filter(all) {
return Some((face, n));
}
}
}
}
None
}
/// [`Self::search_fallback`] when no loaded face covers `c`: load a system font that does,
/// one search at a time.
#[cfg(not(target_arch = "wasm32"))]
@@ -199,8 +239,13 @@ impl FontDb {
/// The face for a run, and the number of loaded faces the search last chose from.
fn search_run(&self, chars: &[char], exclude: u32, bold: bool, italic: bool) -> (Option<Arc<FontFace>>, usize) {
// A run of ballot boxes draws in their one face, as each of them alone does (#7863).
let ballot = chars.first().filter(|_| chars.iter().all(|c| BALLOT_BOXES.contains(c))).and_then(|c| self.ballot_box_fallback(*c, exclude));
#[cfg_attr(target_arch = "wasm32", allow(unused_mut))]
let (mut base, mut checked) = self.loaded_covering(chars, exclude);
let (mut base, mut checked) = match ballot {
Some((face, n)) => (Some(face), n),
None => self.loaded_covering(chars, exclude),
};
#[cfg(not(target_arch = "wasm32"))]
if base.is_none() {
// A character no loaded face covers: load a system font for it, then retry (the run's
@@ -235,12 +280,16 @@ impl FontDb {
(true, false) => "Bold",
_ => "Italic",
};
let before_style = self.read_faces().len();
// The count stays the one `base` was chosen from. `base` is loaded, so the style lookup
// only picks among the family's loaded faces and loads nothing: a later count could only
// take in a face another thread loaded meanwhile, and cache this answer for faces it never
// saw (#7863).
let styled = self.face(&base.family, style);
if before_style == checked {
checked = self.read_faces().len();
#[cfg(test)]
if let Some(hook) = self.run_style_hook.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take() {
hook(self);
}
let face = if styled.family.eq_ignore_ascii_case(&base.family) && chars.iter().all(|c| styled.covers(*c)) && styled.id != exclude {
let face = if styled.family.eq_ignore_ascii_case(&base.family) && styled_covers(&styled, &base, chars) && styled.id != exclude {
styled
} else {
base
@@ -557,3 +606,11 @@ impl FontDb {
false
}
}
/// Can `styled`, a bold or italic face of `base`'s family, draw `chars` in its place? It must map
/// them all, and all three ballot boxes when they are ballot boxes and `base` has all three, so a
/// check box's states stay in one face in bold or italic text too (#7863).
fn styled_covers(styled: &FontFace, base: &FontFace, chars: &[char]) -> bool {
let boxes = chars.iter().all(|c| BALLOT_BOXES.contains(c)) && BALLOT_BOXES.iter().all(|b| base.covers(*b));
chars.iter().chain(BALLOT_BOXES.iter().filter(|_| boxes)).all(|c| styled.covers(*c))
}
+3
View File
@@ -242,6 +242,9 @@ pub const RTL_FALLBACKS: &[&str] = &[
pub const RTL_FALLBACKS: &[&str] =
&["Noto Naskh Arabic", "Noto Sans Arabic", "Noto Sans Hebrew", "Vazirmatn", "Segoe UI", "Arial", "Tahoma", "DejaVu Sans"];
/// The ballot boxes ☐ ☑ ☒: a check box's unchecked symbol and its two usual checked ones.
pub(super) const BALLOT_BOXES: [char; 3] = ['\u{2610}', '\u{2611}', '\u{2612}'];
/// Families tried (when installed) for characters the loaded fonts lack: CJK, symbols, emoji.
#[cfg(not(target_arch = "wasm32"))]
pub(super) const SYSTEM_FALLBACKS: &[&str] = &[
+4 -16
View File
@@ -1,4 +1,4 @@
use super::face::{FALLBACK_FAMILY, FontBytes, FontFace, HINT_PPEM, HINTER_CACHE_MAX, OUTLINE_CACHE_MAX};
use super::face::{FALLBACK_FAMILY, FontBytes, FontFace, HINT_PPEM};
#[cfg(not(target_arch = "wasm32"))]
use super::fallback_data::read_fallback_file;
#[cfg(not(target_arch = "wasm32"))]
@@ -220,11 +220,7 @@ impl FontDb {
return p.clone();
}
let p = Arc::new(face.glyph_outline(gid));
let mut cache = self.outlines.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if cache.len() >= OUTLINE_CACHE_MAX {
cache.clear();
}
cache.insert(key, p.clone());
self.outlines.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(key, p.clone());
p
}
@@ -247,21 +243,13 @@ impl FontDb {
None => {
// Built outside the lock: running a font's hinting programs takes a while.
let h = face.screen_hinter(ppem).map(Arc::new);
let mut cache = self.hinters.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if cache.len() >= HINTER_CACHE_MAX {
cache.clear();
}
cache.insert(hkey, h.clone());
self.hinters.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(hkey, h.clone());
h
}
}
};
let p = hinter.and_then(|h| face.hinted_glyph_outline(gid, &h)).map(Arc::new);
let mut cache = self.hinted.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if cache.len() >= OUTLINE_CACHE_MAX {
cache.clear();
}
cache.insert(key, p.clone());
self.hinted.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(key, p.clone());
p
}
}
+12
View File
@@ -154,6 +154,18 @@ fn screen_hinting_refuses_hostile_sizes() {
assert!(db.hinted_outline(&face, u32::MAX, 20.0).is_none_or(|o| o.elements().is_empty()));
}
#[test]
fn bounded_outline_cache_evicts_oldest_incrementally() {
let mut c = BoundedCache::new(2);
c.insert(1u32, "a");
c.insert(2u32, "b");
c.insert(3u32, "c");
assert_eq!(c.len(), 2);
assert!(c.get(&1).is_none(), "oldest entry evicted");
assert_eq!(c.get(&2), Some(&"b"), "newer entry retained");
assert_eq!(c.get(&3), Some(&"c"));
}
/// The issue's run (#1549): Thai letters and digits, Latin letters, digits and the baht sign.
const THAI_RUN: &str = "[D] น้ำ ค่ำ ปั้น ฝั่ง ปู่ ๑๒๓๔๕๖๗๘๙๐ ฿1,250.50";
+124
View File
@@ -866,6 +866,130 @@ fn circle_checks_face_coverage() {
assert_eq!(db.fallback_for('●', primary.id()).unwrap().family, FALLBACK_FAMILY);
}
/// A bundled Source Sans 3 Regular named `family` that maps ☒ (U+2612) too: its ☐–☑ cmap group
/// runs on one character further (the next group starts at U+2615, so the groups stay sorted).
fn with_every_ballot_box(family: &str) -> Vec<u8> {
let mut data = named_face("SourceSans3-Regular.ttf", family);
let (from, to) = ([0x2610_u32, 0x2611].map(u32::to_be_bytes).concat(), [0x2610_u32, 0x2612].map(u32::to_be_bytes).concat());
let mut patched = 0;
while let Some(at) = data.windows(from.len()).position(|w| w == from) {
data[at..at + to.len()].copy_from_slice(&to);
patched += 1;
}
assert!(patched > 0);
data
}
#[test]
fn a_check_box_draws_every_state_in_one_face() {
// #7863: with the check box's font missing, ☐ and ☑ came from the UI fallback, which has no
// ☒, and ☒ from another face, so ticking a box changed how it looked.
let db = FontDb::with_font_dirs(Vec::new());
db.set_system_fallback(false);
let primary = db.face("Inter", "Regular");
assert!(!primary.covers('☐'), "the requested face lacks the boxes");
// A listed symbol face with ☐ and ☑ only, then a later one with all three.
db.add_document_fonts(vec![
(named_face("SourceSerif4-Regular.ttf", "Apple Symbols"), "Apple Symbols".to_string()),
(with_every_ballot_box("DejaVu Sans"), "DejaVu Sans".to_string()),
]);
let faces: Vec<u32> = ['☐', '☑', '☒'].iter().map(|c| db.fallback_for(*c, primary.id()).expect("a face has it").id()).collect();
assert!(faces.iter().all(|f| *f == faces[0]), "one face for every state: {faces:?}");
let run = db.fallback_for_run(&['☐', '☑'], primary.id(), false, false).expect("a face has them");
assert_eq!(run.id(), faces[0], "a run of them takes the same face");
}
#[test]
fn a_bold_check_box_draws_every_state_in_one_face() {
// The listed family's Regular face has all three boxes and its Bold face only ☐ and ☑: bold ☐
// and ☑ took the Bold face, and ☒ the Regular one.
let db = FontDb::with_font_dirs(Vec::new());
db.set_system_fallback(false);
let primary = db.face("Inter", "Regular");
db.add_document_fonts(vec![
(with_every_ballot_box("DejaVu Sans"), "DejaVu Sans".to_string()),
(named_face("SourceSans3-Bold.ttf", "DejaVu Sans"), "DejaVu Sans".to_string()),
]);
let faces: Vec<u32> = ['☐', '☑', '☒'].iter().map(|c| db.fallback_styled(*c, primary.id(), true, false).expect("a face has it").id()).collect();
assert!(faces.iter().all(|f| *f == faces[0]), "one face for every state: {faces:?}");
let run = db.fallback_for_run(&['☐', '☑'], primary.id(), true, false).expect("a face has them");
assert_eq!(run.id(), faces[0], "a bold run of them takes the same face");
}
#[test]
fn ballot_boxes_load_an_installed_symbol_face() {
let dir = font_dir("ballot-boxes");
std::fs::write(dir.join("Symbols-Regular.ttf"), with_every_ballot_box("DejaVu Sans")).unwrap();
// An earlier listed family with only two of the boxes: never loaded for them.
std::fs::write(dir.join("TwoBoxes-Regular.ttf"), named_face("SourceSerif4-Regular.ttf", "Apple Symbols")).unwrap();
let db = FontDb::with_font_dirs(vec![dir.clone()]);
let primary = db.face("Inter", "Regular");
db.set_system_fallback(false);
assert!(db.fallback_for('☐', primary.id()).is_some());
assert!(!db.is_loaded("DejaVu Sans"), "nothing is loaded with the system fallback off");
db.set_system_fallback(true);
let found = db.fallback_for('☐', primary.id()).unwrap();
assert_eq!(found.family, "DejaVu Sans", "the installed face with all three");
assert_eq!(db.fallback_for('☒', primary.id()).unwrap().id(), found.id());
assert!(!db.is_loaded("Apple Symbols"), "a listed family without all three is not loaded");
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn a_check_box_keeps_one_face_when_a_symbol_face_loads_during_its_search() {
// A search for ☐ passed Apple Symbols, not loaded yet, and was loading the installed Segoe UI
// Symbol when another thread loaded Apple Symbols. Its answer was remembered for the face count
// after both loads, so ☐ kept Segoe UI Symbol while ☑ and ☒ took Apple Symbols, the first
// listed face with all three.
let dir = font_dir("ballot-box-race");
std::fs::write(dir.join("Symbols-Regular.ttf"), with_every_ballot_box("Segoe UI Symbol")).unwrap();
let db = FontDb::with_font_dirs(vec![dir.clone()]);
let primary = db.face("Inter", "Regular");
let reads = || db.coverage.lock().unwrap().reads;
let unread = reads();
let loading = db.loading.lock().unwrap();
std::thread::scope(|s| {
let search = s.spawn(|| db.fallback_for('☐', primary.id()));
// Past Apple Symbols, the search reads the installed file's character map, then waits for
// `loading` to load the file. (A search that finishes without reading it ends the wait too.)
while reads() == unread && !search.is_finished() {
std::thread::yield_now();
}
// Another thread loads Apple Symbols meanwhile, as a font load adds faces (`loading` is
// held here).
db.add_fonts(vec![(with_every_ballot_box("Apple Symbols"), None)]);
drop(loading);
assert!(search.join().unwrap().is_some());
});
let faces: Vec<String> = ['☐', '☑', '☒'].iter().map(|c| db.fallback_for(*c, primary.id()).expect("a face has it").family.clone()).collect();
assert_eq!(faces, ["Apple Symbols"; 3], "the first listed face with all three, for every state");
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn a_bold_run_of_check_boxes_keeps_one_face_when_a_symbol_face_loads_during_its_style_lookup() {
// A bold run of boxes chose DejaVu Sans, the first listed face loaded with all three, and
// looked up its bold face while another thread loaded Apple Symbols, listed earlier. The run's
// answer was remembered for the face count after that load, so the run kept DejaVu Sans while
// each box alone took Apple Symbols.
let db = FontDb::with_font_dirs(Vec::new());
db.set_system_fallback(false);
let primary = db.face("Inter", "Regular");
db.add_document_fonts(vec![(with_every_ballot_box("DejaVu Sans"), "DejaVu Sans".to_string())]);
let apple = with_every_ballot_box("Apple Symbols");
*db.run_style_hook.lock().unwrap() = Some(Box::new(move |db| {
// A font load adds faces and leaves the generation as it is.
db.add_fonts(vec![(apple, None)]);
}));
let run = ['☐', '☑', '☒'];
assert!(db.fallback_for_run(&run, primary.id(), true, false).is_some());
assert!(db.run_style_hook.lock().unwrap().is_none(), "Apple Symbols loaded during the run's style lookup");
let boxes: Vec<String> = run.iter().map(|c| db.fallback_styled(*c, primary.id(), true, false).expect("a face has it").family.clone()).collect();
assert_eq!(boxes, ["Apple Symbols"; 3], "the first listed face with all three, for every state");
let again = db.fallback_for_run(&run, primary.id(), true, false).expect("a face has them");
assert_eq!(again.family, "Apple Symbols", "the run takes the face each box takes");
}
#[test]
fn catalog_postscript_names() {
let dir = font_dir("postscript");
+1 -1
View File
@@ -17,7 +17,7 @@ pub mod word;
pub use fontdb::{
FALLBACK_FAMILY, FONT_FILE_EXTS, FaceRef, FontDb, FontFace, FontFormat, Installed, LocalName, MAX_FONT_FILE_BYTES, UserFont, UserFontError,
base_style, bundled, decode_font_file, is_font_file_name, name_language_matches, sniff, system_font_dirs,
base_style, bundled, bundled_inter, decode_font_file, is_font_file_name, name_language_matches, sniff, system_font_dirs,
};
pub use harfrust::Feature;
use harfrust::{Direction, ShapeOptions, ShapePlan, ShapePlanKey, Shaper, Tag, UnicodeBuffer};
+5 -3
View File
@@ -40,6 +40,11 @@ pub fn has_named_substitutes(family: &str) -> bool {
const SANS: &[&str] = &["Carlito", "Helvetica Neue", "Arial", "Liberation Sans", "Noto Sans", "DejaVu Sans", "Source Sans 3"];
/// Word's symbol fonts (Symbol, Wingdings…) are proprietary: their characters are drawn as their
/// Unicode equivalents (`wordcraft_doc::symbol_fonts`) from these faces or any face that has them.
/// A check box's ballot boxes take their face from this list too (`FontDb::fallback_for`, #7863).
pub(crate) const SYMBOL: &[&str] = &["Apple Symbols", "Segoe UI Symbol", "DejaVu Sans", "Noto Sans Symbols", "Noto Sans Symbols 2", "Source Sans 3"];
/// Serif faces known by name with no open clone of their own (lowercase): they take the generic
/// serif list, but as fonts we know, not by a guess from the name ([`has_own_substitutes`]).
const KNOWN_SERIFS: &[&str] = &[
@@ -75,9 +80,6 @@ fn substitutes_by_name(family: &str) -> (&'static [&'static str], bool) {
const ARIAL: &[&str] = &["Liberation Sans", "Helvetica", "Helvetica Neue", "Arimo", "Source Sans 3"];
const ARIAL_UNICODE: &[&str] = &["Arial", "Liberation Sans", "Helvetica", "Helvetica Neue", "Arimo", "Source Sans 3"];
const TIMES: &[&str] = &["Liberation Serif", "Times", "Tinos", "Source Serif 4"];
// Word's symbol fonts (Symbol, Wingdings…) are proprietary: their characters are drawn as their
// Unicode equivalents (`wordcraft_doc::symbol_fonts`) from these faces or any face that has them.
const SYMBOL: &[&str] = &["Apple Symbols", "Segoe UI Symbol", "DejaVu Sans", "Noto Sans Symbols", "Noto Sans Symbols 2", "Source Sans 3"];
// Persian / Arabic document fonts. Naskh (book) faces such as B Nazanin, B Lotus, B Zar and
// Traditional Arabic, then the sans faces (B Yekan, B Titr, IRANSans) people use for
// headings and screens. Open fonts with full Persian coverage first.
+14 -24
View File
@@ -4,38 +4,28 @@ use wordcraft_doc::{Document, SectionProps};
pub use craft_html::doc::{ImageLoader, PAGE_FONT, css_len_pt, decode, decode_as, decode_entity, esc, export_flow, parse, parse_with, unescape};
fn shared_section(page: &SectionProps) -> craft_wordmodel::SectionProps {
let mut d = Document::new();
d.last_section = page.clone();
wordcraft_docx::to_shared_model(&d).map(|s| s.last_section).unwrap_or_default()
use crate::{from_shared, shared_section, to_shared};
pub fn import(html: &str) -> Result<Document, String> {
from_shared(craft_html::doc::import(html))
}
pub fn import(html: &str) -> Document {
wordcraft_docx::from_shared_model(craft_html::doc::import(html)).unwrap_or_default()
pub fn import_page(html: &str, images: ImageLoader<'_>) -> Result<Document, String> {
from_shared(craft_html::doc::import_page(html, images))
}
pub fn import_page(html: &str, images: ImageLoader<'_>) -> Document {
wordcraft_docx::from_shared_model(craft_html::doc::import_page(html, images)).unwrap_or_default()
pub fn import_with(html: &str, images: ImageLoader<'_>) -> Result<Document, String> {
from_shared(craft_html::doc::import_with(html, images))
}
pub fn import_with(html: &str, images: ImageLoader<'_>) -> Document {
wordcraft_docx::from_shared_model(craft_html::doc::import_with(html, images)).unwrap_or_default()
pub fn import_on(html: &str, images: ImageLoader<'_>, page: &SectionProps) -> Result<Document, String> {
from_shared(craft_html::doc::import_on(html, images, &shared_section(page)?))
}
pub fn import_on(html: &str, images: ImageLoader<'_>, page: &SectionProps) -> Document {
wordcraft_docx::from_shared_model(craft_html::doc::import_on(html, images, &shared_section(page))).unwrap_or_default()
pub fn export(doc: &Document) -> Result<String, String> {
Ok(craft_html::doc::export(&to_shared(doc)?))
}
pub fn export(doc: &Document) -> String {
match wordcraft_docx::to_shared_model(doc) {
Ok(shared) => craft_html::doc::export(&shared),
Err(_) => String::new(),
}
}
pub fn export_fragment(doc: &Document) -> String {
match wordcraft_docx::to_shared_model(doc) {
Ok(shared) => craft_html::doc::export_fragment(&shared),
Err(_) => String::new(),
}
pub fn export_fragment(doc: &Document) -> Result<String, String> {
Ok(craft_html::doc::export_fragment(&to_shared(doc)?))
}
+9 -10
View File
@@ -4,23 +4,22 @@ use wordcraft_doc::{Document, SectionProps};
pub use craft_latex::{escape_text, latex_to_linear, linear_to_latex};
pub fn import(bytes: &[u8]) -> Document {
wordcraft_docx::from_shared_model(craft_latex::import(bytes)).unwrap_or_default()
use crate::{from_shared, to_shared};
pub fn import(bytes: &[u8]) -> Result<Document, String> {
from_shared(craft_latex::import(bytes))
}
pub fn import_on(bytes: &[u8], page: &SectionProps) -> Document {
let mut d = import(bytes);
pub fn import_on(bytes: &[u8], page: &SectionProps) -> Result<Document, String> {
let mut d = import(bytes)?;
d.last_section = page.clone();
d
Ok(d)
}
pub fn parse(text: &str) -> craft_flow::Flow {
craft_latex::parse(text)
}
pub fn export(doc: &Document) -> String {
match wordcraft_docx::to_shared_model(doc) {
Ok(shared) => craft_latex::export(&shared),
Err(_) => String::new(),
}
pub fn export(doc: &Document) -> Result<String, String> {
Ok(craft_latex::export(&to_shared(doc)?))
}
+39 -15
View File
@@ -28,6 +28,27 @@ use wordcraft_doc::Document;
/// (`wordcraft_docx::package::MAX_ENTRIES`); checked before `zip` parses them (#3660).
pub const MAX_ZIP_ENTRIES: u64 = 20_000;
/// The document as the shared model the format crates read and write.
///
/// A conversion that fails is an error, never an empty document or an empty file: the caller
/// says so instead of writing a file with nothing in it.
pub(crate) fn to_shared(doc: &Document) -> Result<craft_wordmodel::Document, String> {
wordcraft_docx::to_shared_model(doc).map_err(|e| e.to_string())
}
/// The shared model as the app's document model. A conversion that fails is an error, never
/// an empty document.
pub(crate) fn from_shared(shared: craft_wordmodel::Document) -> Result<Document, String> {
wordcraft_docx::from_shared_model(shared).map_err(|e| e.to_string())
}
/// The page a file that gives no page size starts on, as the shared model.
pub(crate) fn shared_section(page: &wordcraft_doc::SectionProps) -> Result<craft_wordmodel::SectionProps, String> {
let mut d = Document::new();
d.last_section = page.clone();
Ok(to_shared(&d)?.last_section)
}
/// Extensions this crate handles.
pub const EXTENSIONS: &[&str] =
&["txt", "text", "md", "markdown", "html", "htm", "xhtml", "mht", "mhtml", "rtf", "odt", "ott", "fodt", "tex", "latex", "ltx"];
@@ -35,15 +56,15 @@ pub const EXTENSIONS: &[&str] =
/// Import `bytes` in the format named by `ext` (no dot, any case). `None` = not our format.
pub fn import(ext: &str, bytes: &[u8]) -> Option<Result<Document, String>> {
let ext = ext.trim_start_matches('.').to_ascii_lowercase();
let r = match ext.as_str() {
let r: Result<Document, String> = match ext.as_str() {
"txt" | "text" => Ok(txt::import(bytes)),
"md" | "markdown" => Ok(markdown::import(&txt::decode(bytes))),
"html" | "htm" | "xhtml" => Ok(html::import_page(&html::decode(bytes), &|_| None)),
"mht" | "mhtml" => Ok(mht::import(bytes)),
"md" | "markdown" => markdown::import(&txt::decode(bytes)),
"html" | "htm" | "xhtml" => html::import_page(&html::decode(bytes), &|_| None),
"mht" | "mhtml" => mht::import(bytes),
"rtf" => rtf::import(bytes),
"odt" | "ott" => odt::import(bytes),
"fodt" => odt::import_flat(bytes),
"tex" | "latex" | "ltx" => Ok(latex::import(bytes)),
"tex" | "latex" | "ltx" => latex::import(bytes),
_ => return None,
};
Some(r.map(|mut d| {
@@ -57,33 +78,36 @@ pub fn import(ext: &str, bytes: &[u8]) -> Option<Result<Document, String>> {
/// formats keep the page their file gives.
pub fn import_on(ext: &str, bytes: &[u8], page: &wordcraft_doc::SectionProps) -> Option<Result<Document, String>> {
let ext = ext.trim_start_matches('.').to_ascii_lowercase();
let mut doc = match ext.as_str() {
let mut doc: Result<Document, String> = match ext.as_str() {
"odt" | "ott" => return Some(odt::import_on(bytes, page)),
"fodt" => return Some(odt::import_flat_on(bytes, page)),
"txt" | "text" => txt::import_on(bytes, page),
"txt" | "text" => Ok(txt::import_on(bytes, page)),
"md" | "markdown" => markdown::import_on(&txt::decode(bytes), page),
"html" | "htm" | "xhtml" => html::import_on(&html::decode(bytes), &|_| None, page),
"mht" | "mhtml" => mht::import_on(bytes, page),
_ => return import(&ext, bytes),
};
doc.ensure_nonempty();
Some(Ok(doc))
if let Ok(d) = doc.as_mut() {
d.ensure_nonempty();
}
Some(doc)
}
/// Export `doc` in the format named by `ext`. `None` = not our format.
pub fn export(ext: &str, doc: &Document) -> Option<Result<Vec<u8>, String>> {
let ext = ext.trim_start_matches('.').to_ascii_lowercase();
Some(match ext.as_str() {
let out: Result<Vec<u8>, String> = match ext.as_str() {
"txt" | "text" => Ok(txt::export(doc)),
"md" | "markdown" => Ok(markdown::export(doc).into_bytes()),
"html" | "htm" | "xhtml" => Ok(html::export(doc).into_bytes()),
"rtf" => Ok(rtf::export(doc).into_bytes()),
"md" | "markdown" => markdown::export(doc).map(String::into_bytes),
"html" | "htm" | "xhtml" => html::export(doc).map(String::into_bytes),
"rtf" => rtf::export(doc).map(String::into_bytes),
"odt" => odt::export(doc),
"ott" => odt::export_template(doc),
"fodt" => odt::export_flat(doc),
"tex" | "latex" | "ltx" => Ok(latex::export(doc).into_bytes()),
"tex" | "latex" | "ltx" => latex::export(doc).map(String::into_bytes),
_ => return None,
})
};
Some(out)
}
/// How [`export_with`] writes a copy.
+11 -18
View File
@@ -4,23 +4,19 @@ use wordcraft_doc::{Block, Document, SectionProps};
pub use craft_markdown::{Refs, escape, parse, parse_inlines};
fn shared_section(page: &SectionProps) -> craft_wordmodel::SectionProps {
let mut d = Document::new();
d.last_section = page.clone();
wordcraft_docx::to_shared_model(&d).map(|s| s.last_section).unwrap_or_default()
use crate::{from_shared, shared_section, to_shared};
pub fn import(text: &str) -> Result<Document, String> {
from_shared(craft_markdown::import(text))
}
pub fn import(text: &str) -> Document {
wordcraft_docx::from_shared_model(craft_markdown::import(text)).unwrap_or_default()
}
pub fn import_on(text: &str, page: &SectionProps) -> Document {
wordcraft_docx::from_shared_model(craft_markdown::import_on(text, &shared_section(page))).unwrap_or_default()
pub fn import_on(text: &str, page: &SectionProps) -> Result<Document, String> {
from_shared(craft_markdown::import_on(text, &shared_section(page)?))
}
/// [`import_on`] returning the document and the 0-based starting line of each top-level block.
pub fn import_on_with_lines(text: &str, page: &SectionProps) -> (Document, Vec<usize>) {
let doc = import_on(text, page);
pub fn import_on_with_lines(text: &str, page: &SectionProps) -> Result<(Document, Vec<usize>), String> {
let doc = import_on(text, page)?;
let src_lines: Vec<&str> = text.strip_prefix('\u{FEFF}').unwrap_or(text).lines().collect();
let mut out = Vec::with_capacity(doc.body.len());
let mut cursor = 0usize;
@@ -57,12 +53,9 @@ pub fn import_on_with_lines(text: &str, page: &SectionProps) -> (Document, Vec<u
}
out.push(found.min(src_lines.len()));
}
(doc, out)
Ok((doc, out))
}
pub fn export(doc: &Document) -> String {
match wordcraft_docx::to_shared_model(doc) {
Ok(shared) => craft_markdown::export(&shared),
Err(_) => String::new(),
}
pub fn export(doc: &Document) -> Result<String, String> {
Ok(craft_markdown::export(&to_shared(doc)?))
}
+3 -3
View File
@@ -15,7 +15,7 @@ pub fn is_mht(bytes: &[u8]) -> bool {
}
/// Import an MHT file.
pub fn import(bytes: &[u8]) -> Document {
pub fn import(bytes: &[u8]) -> Result<Document, String> {
import_on(bytes, &SectionProps::default())
}
@@ -38,7 +38,7 @@ fn part_bytes(part: &Part) -> &[u8] {
}
/// [`import`] onto `page`.
pub fn import_on(bytes: &[u8], page: &SectionProps) -> Document {
pub fn import_on(bytes: &[u8], page: &SectionProps) -> Result<Document, String> {
let msg = craft_mime::parse(bytes, &craft_mime::Limits::DEFAULT);
let mut leaves = Vec::new();
collect_leaves(&msg.root, &mut leaves);
@@ -46,7 +46,7 @@ pub fn import_on(bytes: &[u8], page: &SectionProps) -> Document {
.or_else(|| leaves.iter().copied().find(|p| matches!(p.declared_media_type(), Some("text/html" | "application/xhtml+xml"))));
let Some(root) = root else {
let text = leaves.iter().copied().find(|p| p.declared_media_type().unwrap_or("text/plain") == "text/plain").map(part_bytes).unwrap_or(&[]);
return crate::txt::import_on(text, page);
return Ok(crate::txt::import_on(text, page));
};
let html = crate::html::decode_as(part_bytes(root), root.content_type.get("charset"));
let base = root.content_location().unwrap_or("");
+5 -6
View File
@@ -2,9 +2,11 @@
use wordcraft_doc::Document;
use crate::{from_shared, to_shared};
pub fn import(bytes: &[u8]) -> Result<Document, String> {
let shared = craft_rtf::doc::import(bytes)?;
wordcraft_docx::from_shared_model(shared).map_err(|e| e.to_string())
from_shared(shared)
}
pub fn parse(bytes: &[u8]) -> Result<crate::model::Flow, String> {
@@ -12,9 +14,6 @@ pub fn parse(bytes: &[u8]) -> Result<crate::model::Flow, String> {
Ok(craft_flow::from_doc(&shared))
}
pub fn export(doc: &Document) -> String {
let Ok(shared) = wordcraft_docx::to_shared_model(doc) else {
return String::new();
};
craft_rtf::doc::export(&shared)
pub fn export(doc: &Document) -> Result<String, String> {
Ok(craft_rtf::doc::export(&to_shared(doc)?))
}
+301 -9
View File
@@ -95,15 +95,7 @@ pub fn read_rows(bytes: &[u8], pick: Pick<'_>) -> Result<(Vec<String>, Vec<Vec<S
let names: Vec<String> = book.sheets.iter().map(|s| s.name.clone()).collect();
let i = resolve(&names, pick)?;
let sheet = &book.sheets[i];
let rows = cells_to_rows(&sheet.cells, |c| {
if !c.text.is_empty() {
clamp_cell(c.text.clone())
} else if let Some(v) = c.value() {
format_value(&v)
} else {
String::new()
}
});
let rows = cells_to_rows(&sheet.cells, ods_value);
return Ok((names, rows));
}
Err("not an Excel or OpenDocument spreadsheet".into())
@@ -178,6 +170,178 @@ fn format_value(v: &Value) -> String {
}
}
/// An OpenDocument cell's display string, from `office:value-type`: floats from `office:value`,
/// dates and times from `office:date-value` / `office:time-value` in ISO 8601 form (`yyyy-mm-dd`,
/// `yyyy-mm-dd hh:mm[:ss]`, `hh:mm[:ss]`), booleans as `TRUE`/`FALSE`, and strings, percentages
/// and currencies as the cell's text (their value when the text is blank). A value that does not
/// parse falls back to the text. A covered cell under a merged cell is blank.
///
/// A float merges its value, not the text its number format shows: a ZIP code `01234` shown
/// through the format `00000` merges as `1234`, and `1,234` shown with a thousands separator
/// merges as `1234`.
fn ods_value(c: &craft_ods::Cell) -> String {
use craft_ods::ValueType as T;
if c.covered {
return String::new();
}
let typed = match (c.value_type, c.raw.as_deref().map(str::trim)) {
(Some(T::Float | T::Boolean), Some(_)) => c.value().map(|v| format_value(&v)),
(Some(T::Date), Some(v)) => iso_datetime(v),
(Some(T::Time), Some(v)) => iso_time(v),
(Some(T::Percentage | T::Currency | T::String), Some(_)) if c.text.is_empty() => c.value().map(|v| format_value(&v)),
_ => None,
};
typed.unwrap_or_else(|| clamp_cell(c.text.clone()))
}
/// An ISO 8601 date or date-time (`2024-03-05`, `2024-03-05T13:45:00.000`) as `yyyy-mm-dd`,
/// with ` hh:mm[:ss]` when the time isn't midnight. `None` unless the whole value is a valid
/// calendar date and clock time.
fn iso_datetime(v: &str) -> Option<String> {
use chrono::Datelike;
let v = v.trim();
let (date, time) = match v.split_once('T') {
Some((date, time)) => (date, Some(time)),
None => (v, None),
};
// A date alone may carry a zone (`Z` or `±hh:mm`), which is left out.
let date = match (time, date.strip_suffix('Z')) {
(None, Some(d)) => d,
(None, None) if date.len() > 6 && date.get(date.len() - 6..).is_some_and(|z| z.starts_with(['+', '-']) && z.get(3..4) == Some(":")) => {
zone_offset(date.get(date.len() - 5..)?)?;
date.get(..date.len() - 6)?
}
_ => date,
};
let date = chrono::NaiveDate::parse_from_str(date, "%Y-%m-%d").ok()?;
let mut out = format!("{:04}-{:02}-{:02}", date.year(), date.month(), date.day());
if let Some(time) = time {
let clock = clock_time(time)?;
if clock != chrono::NaiveTime::MIN {
out.push(' ');
out.push_str(&hh_mm(clock));
}
}
Some(out)
}
/// A clock time `hh:mm[:ss[.s…]]` with an optional `Z` or `±hh:mm` zone (one, not both), which is
/// left out.
fn clock_time(t: &str) -> Option<chrono::NaiveTime> {
let t = match (t.strip_suffix('Z'), t.rfind(['+', '-'])) {
(Some(t), _) => t,
(None, Some(i)) => {
zone_offset(t.get(i + 1..)?)?;
t.get(..i)?
}
(None, None) => t,
};
let clock = chrono::NaiveTime::parse_from_str(t, "%H:%M:%S%.f").or_else(|_| chrono::NaiveTime::parse_from_str(t, "%H:%M")).ok()?;
// A leap second (`23:59:60`) is not a time a cell holds.
(chrono::Timelike::nanosecond(&clock) < 1_000_000_000).then_some(clock)
}
/// A zone offset's `hh:mm`, two digits each and at most `14:00` as XML Schema allows.
fn zone_offset(z: &str) -> Option<()> {
use chrono::Timelike;
let two_digit = z.len() == 5 && z.bytes().enumerate().all(|(i, b)| if i == 2 { b == b':' } else { b.is_ascii_digit() });
if !two_digit {
return None;
}
let z = chrono::NaiveTime::parse_from_str(z, "%H:%M").ok()?;
(z.hour() < 14 || (z.hour() == 14 && z.minute() == 0)).then_some(())
}
/// `hh:mm`, with `:ss` when the seconds aren't zero and their fraction when it isn't.
fn hh_mm(t: chrono::NaiveTime) -> String {
use chrono::Timelike;
let (h, m, s, nanos) = (t.hour(), t.minute(), t.second(), t.nanosecond());
if nanos != 0 {
let fraction = format!("{nanos:09}");
format!("{h:02}:{m:02}:{s:02}.{}", fraction.trim_end_matches('0'))
} else if s == 0 {
format!("{h:02}:{m:02}")
} else {
format!("{h:02}:{m:02}:{s:02}")
}
}
/// An ISO 8601 duration (`PT13H45M00S`, `P1DT2H`, `-PT1H`) or clock time (`13:45[:00]`) as
/// `hh:mm[:ss]`, a duration's days counted as hours and a negative one with a leading `-`.
/// `None` for anything else, years and months included.
fn iso_time(v: &str) -> Option<String> {
let t = v.trim();
let (negative, t) = match t.strip_prefix('-') {
Some(rest) => (true, rest),
None => (false, t),
};
let Some(t) = t.strip_prefix('P') else {
return if negative { None } else { clock_time(t).map(hh_mm) };
};
let (days, t, has_t) = match t.split_once('T') {
Some((days, time)) => (days, time, true),
None => (t, "", false),
};
// A `T` needs a time after it.
if has_t && t.is_empty() {
return None;
}
let mut any = !days.is_empty();
let days: u64 = if days.is_empty() { 0 } else { days.strip_suffix('D')?.parse().ok()? };
let (mut h, mut m, mut s) = (0u64, 0u64, 0u64);
// The seconds' fraction digits, kept as written.
let mut fraction = String::new();
let mut num = String::new();
// Units come in the order H, M, S, each at most once.
let mut next_unit = 0;
for c in t.chars() {
let unit = match c {
'H' => 1,
'M' => 2,
'S' => 3,
'0'..='9' | '.' if num.len() < 20 => {
num.push(c);
continue;
}
_ => return None,
};
if unit <= next_unit {
return None;
}
next_unit = unit;
let n = std::mem::take(&mut num);
match unit {
1 => h = n.parse().ok()?,
2 => m = n.parse().ok()?,
_ => {
let (whole, frac) = n.split_once('.').unwrap_or((&n, ""));
if whole.is_empty() || (n.contains('.') && frac.is_empty()) || !frac.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
s = whole.parse().ok()?;
fraction = frac.trim_end_matches('0').to_string();
}
}
any = true;
}
if !any || !num.is_empty() {
return None;
}
// A duration too long to count in hours is not a time.
m = m.checked_add(s / 60)?;
s %= 60;
h = h.checked_add(m / 60)?.checked_add(days.checked_mul(24)?)?;
m %= 60;
let sign = if negative && ((h, m, s) != (0, 0, 0) || !fraction.is_empty()) { "-" } else { "" };
Some(if !fraction.is_empty() {
format!("{sign}{h:02}:{m:02}:{s:02}.{fraction}")
} else if s == 0 {
format!("{sign}{h:02}:{m:02}")
} else {
format!("{sign}{h:02}:{m:02}:{s:02}")
})
}
fn cells_to_rows<C>(cells: &BTreeMap<CellRef, C>, fmt: impl Fn(&C) -> String) -> Vec<Vec<String>> {
let mut grid: BTreeMap<(u32, u32), String> = BTreeMap::new();
for (r, c) in cells {
@@ -208,3 +372,131 @@ fn grid_to_rows(grid: &BTreeMap<(u32, u32), String>) -> Vec<Vec<String>> {
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
/// An `.ods` package whose body is `tables` (`table:table` elements).
fn spreadsheet(tables: &str) -> Result<Vec<u8>, craft_odf::Error> {
let content = format!(
r#"<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"><office:body><office:spreadsheet>{tables}</office:spreadsheet></office:body></office:document-content>"#
);
let mut w = craft_odf::PackageWriter::new(craft_odf::mime::SPREADSHEET);
w.file("content.xml", "text/xml", content.as_bytes());
w.finish()
}
#[test]
fn ods_cells_read_their_typed_values() {
let book = spreadsheet(
r#"<table:table table:name="Guests">
<table:table-row><table:table-cell office:value-type="string"><text:p>Name</text:p></table:table-cell><table:table-cell table:number-columns-repeated="2"/><table:table-cell office:value-type="string"><text:p>When</text:p></table:table-cell><table:table-cell office:value-type="string" table:number-columns-repeated="2"><text:p>Tag</text:p></table:table-cell></table:table-row>
<table:table-row table:number-rows-repeated="2"><table:table-cell office:value-type="string" table:number-columns-spanned="2"><text:p>Ada<text:s text:c="2"/>L</text:p><text:p>x</text:p><office:annotation><text:p>note</text:p></office:annotation></table:table-cell><table:covered-table-cell office:value-type="string"><text:p>hidden</text:p></table:covered-table-cell><table:table-cell office:value-type="float" office:value="3.50"><text:p>3,5</text:p></table:table-cell><table:table-cell office:value-type="date" office:date-value="2024-03-05T00:00:00"><text:p>05/03/24</text:p></table:table-cell><table:table-cell office:value-type="boolean" office:boolean-value="false"><text:p>NO</text:p></table:table-cell><table:table-cell office:value-type="time" office:time-value="PT13H45M00S"><text:p>01:45 PM</text:p></table:table-cell></table:table-row>
<table:table-row><table:table-cell office:value-type="date" office:date-value="2024-03-05T13:45:30"><text:p>Tue</text:p></table:table-cell><table:table-cell office:value-type="date" office:date-value="not a date"><text:p>someday</text:p></table:table-cell><table:table-cell office:value-type="percentage" office:value="0.25"><text:p>25%</text:p></table:table-cell><table:table-cell office:value-type="currency" office:value="9"/></table:table-row>
</table:table>"#,
)
.unwrap();
let (_, rows) = read_rows(&book, Pick::Name("Guests")).unwrap();
assert_eq!(rows.len(), 4);
assert_eq!(rows[0], ["Name", "", "", "When", "Tag", "Tag"]);
assert_eq!(rows[1], ["Ada L\nx", "", "3.5", "2024-03-05", "FALSE", "13:45"]);
assert_eq!(rows[1], rows[2]);
assert_eq!(rows[3], ["2024-03-05 13:45:30", "someday", "25%", "9"]);
}
#[test]
fn an_ods_date_with_two_zones_reads_its_text() {
let book = spreadsheet(
r#"<table:table table:name="Dates">
<table:table-row><table:table-cell office:value-type="date" office:date-value="2024-03-05T13:45:00+02:00Z"><text:p>offset then Z</text:p></table:table-cell><table:table-cell office:value-type="date" office:date-value="2024-03-05T13:45:00Z+02:00"><text:p>Z then offset</text:p></table:table-cell><table:table-cell office:value-type="date" office:date-value="2024-03-05T13:45:00+02:00"><text:p>one zone</text:p></table:table-cell></table:table-row>
</table:table>"#,
)
.unwrap();
let (_, rows) = read_rows(&book, Pick::Name("Dates")).unwrap();
assert_eq!(rows, [["offset then Z", "Z then offset", "2024-03-05 13:45"]]);
}
#[test]
fn ods_dates_and_durations() {
assert_eq!(iso_time("PT1H59M59.6S").as_deref(), Some("01:59:59.6"));
assert_eq!(iso_time("PT0.25S").as_deref(), Some("00:00:00.25"));
assert_eq!(iso_time("PT59M60.50S").as_deref(), Some("01:00:00.5"));
assert_eq!(iso_time("PT0H0M59S").as_deref(), Some("00:00:59"));
assert_eq!(iso_time("PT1H2M3S").as_deref(), Some("01:02:03"));
assert_eq!(iso_time("PT1.S"), None);
assert_eq!(iso_time("P1000000000000000000D"), None);
}
#[test]
fn a_date_alone_drops_its_zone() {
assert_eq!(iso_datetime("2024-03-05Z").as_deref(), Some("2024-03-05"));
assert_eq!(iso_datetime("2024-03-05+02:00").as_deref(), Some("2024-03-05"));
assert_eq!(iso_datetime("2024-03-05-05:00").as_deref(), Some("2024-03-05"));
assert_eq!(iso_datetime("2024-03-05+02:99"), None);
}
#[test]
fn a_zone_is_at_most_fourteen_hours() {
assert_eq!(iso_datetime("2024-03-05+14:00").as_deref(), Some("2024-03-05"));
assert_eq!(iso_datetime("2024-03-05-14:00").as_deref(), Some("2024-03-05"));
assert_eq!(iso_datetime("2024-03-05+14:01"), None);
assert_eq!(iso_datetime("2024-03-05-15:00"), None);
assert_eq!(iso_datetime("2024-03-05T13:45:00+14:00").as_deref(), Some("2024-03-05 13:45"));
assert_eq!(iso_datetime("2024-03-05T13:45:00+14:01"), None);
assert_eq!(iso_time("13:45:00-15:00"), None);
}
#[test]
fn a_zone_is_z_or_an_offset_not_both() {
assert_eq!(iso_datetime("2024-03-05T13:45:00+02:00Z"), None);
assert_eq!(iso_datetime("2024-03-05T13:45:00Z+02:00"), None);
assert_eq!(iso_datetime("2024-03-05+02:00Z"), None);
assert_eq!(iso_datetime("2024-03-05Z+02:00"), None);
assert_eq!(iso_time("13:45:00+02:00Z"), None);
assert_eq!(iso_time("13:45:00Z+02:00"), None);
assert_eq!(iso_datetime("2024-03-05T13:45:00Z").as_deref(), Some("2024-03-05 13:45"));
assert_eq!(iso_datetime("2024-03-05T13:45:00-05:00").as_deref(), Some("2024-03-05 13:45"));
assert_eq!(iso_time("13:45:00+02:00").as_deref(), Some("13:45"));
}
#[test]
fn a_zone_offset_has_two_digit_hours_and_minutes() {
assert_eq!(iso_datetime("2024-03-05T13:45:00+2:00"), None);
assert_eq!(iso_datetime("2024-03-05T13:45:00+ 2:00"), None);
assert_eq!(iso_time("13:45:00-5:00"), None);
}
#[test]
fn a_leap_second_is_not_a_time() {
assert_eq!(iso_datetime("2024-03-05T23:59:60Z"), None);
assert_eq!(iso_time("23:59:60"), None);
}
#[test]
fn a_duration_with_t_needs_a_time() {
assert_eq!(iso_time("P1DT"), None);
assert_eq!(iso_time("P0DT"), None);
assert_eq!(iso_time("P1D").as_deref(), Some("24:00"));
assert_eq!(iso_time("PT.S"), None);
assert_eq!(iso_time("13:45:00Z").as_deref(), Some("13:45"));
assert_eq!(iso_time("-PT1H").as_deref(), Some("-01:00"));
assert_eq!(iso_time("P2DT1H30M").as_deref(), Some("49:30"));
assert_eq!(iso_time("P1D").as_deref(), Some("24:00"));
assert_eq!(iso_time("P1Y2M"), None);
assert_eq!(iso_time("PT"), None);
assert_eq!(iso_time("PT5"), None);
assert_eq!(iso_time("PT1H2H"), None);
assert_eq!(iso_time("PT1S2H"), None);
assert_eq!(iso_datetime("2024-03-05T"), None);
assert_eq!(iso_datetime("2024-03-05T00:00:00.500").as_deref(), Some("2024-03-05 00:00:00.5"));
assert_eq!(iso_time("00:00:00.250").as_deref(), Some("00:00:00.25"));
assert_eq!(iso_time("25:00"), None);
assert_eq!(iso_datetime("2024-03-05T00:00:00.000").as_deref(), Some("2024-03-05"));
assert_eq!(iso_datetime("2024-03-05T13:45:30+02:00").as_deref(), Some("2024-03-05 13:45:30"));
assert_eq!(iso_datetime("2024-13-05"), None);
assert_eq!(iso_datetime("2023-02-29"), None);
assert_eq!(iso_datetime("2024-03-05junk"), None);
assert_eq!(iso_datetime("2024-03-05T13:99"), None);
}
}
+24 -14
View File
@@ -330,6 +330,14 @@ fn rtf_round_trip() {
assert_eq!(back.core.creator, "Ada Writer");
}
/// A file the format cannot read is an error, not a blank document: the reader says what it
/// could not read, so the caller can say so too.
#[test]
fn a_format_that_cannot_be_read_is_an_error_not_a_blank_document() {
let e = import("rtf", b"not an RTF document").unwrap().unwrap_err();
assert!(e.contains("RTF"), "{e}");
}
#[test]
fn odt_round_trip() {
check_round_trip("odt", true);
@@ -599,7 +607,7 @@ fn latex_export_carries_no_commands_from_the_document() {
assert_eq!(crate::latex::linear_to_latex("\\alpha+\\sin x+\\mathbb R"), "\\alpha+\\sin x+\\mathbb R");
assert_eq!(crate::latex::linear_to_latex("x^2^3"), "x^2^3");
// The same through a whole file, and for a bookmark name.
let d = crate::latex::import("Text $\\input secret.txt $ and \\hypertarget{^^5cinput secret.txt ^^5c}{here}.".as_bytes());
let d = crate::latex::import("Text $\\input secret.txt $ and \\hypertarget{^^5cinput secret.txt ^^5c}{here}.".as_bytes()).unwrap();
let out = String::from_utf8(export("tex", &d).unwrap().unwrap()).unwrap();
assert!(!out.contains("\\input") && !out.contains("^^"), "{out}");
}
@@ -612,11 +620,11 @@ fn latex_export_carries_no_commands_from_the_document() {
fn latex_labels_in_a_row_are_read_in_linear_time() {
let started = std::time::Instant::now();
for src in ["\\label{a} ".repeat(100_000) + "x", "\\label{a}".repeat(100_000) + "x", "\\hypertarget{a}{} ".repeat(100_000)] {
let d = crate::latex::import(src.as_bytes());
let d = crate::latex::import(src.as_bytes()).unwrap();
assert!(d.body.len() <= 2);
}
assert!(started.elapsed() < std::time::Duration::from_secs(10), "{:?}", started.elapsed());
let d = crate::latex::import("\\label{one}First \\label{two}second \\label{three}third.".as_bytes());
let d = crate::latex::import("\\label{one}First \\label{two}second \\label{three}third.".as_bytes()).unwrap();
let p = d.para_at(&wordcraft_doc::Pos::body(0, 0)).unwrap();
let names: Vec<&str> = p
.objects
@@ -733,7 +741,8 @@ fn html_img_sources_go_through_the_loader() {
let d = crate::html::import_with(html, &|src| {
seen.borrow_mut().push(src.to_string());
(src == "logo.png").then(|| std::sync::Arc::new(pic.clone()))
});
})
.unwrap();
assert_eq!(*seen.borrow(), ["logo.png", "gone.png"]);
assert_eq!(d.media.len(), 1);
let text = d.plain_text(wordcraft_doc::StoryRef::Body);
@@ -1121,7 +1130,7 @@ fn hidden_drawings_are_left_out_of_exports() {
d.insert_object(&wordcraft_doc::Pos::body(0, 0), image, &Default::default()).unwrap();
}
// Two pictures, one hidden: one comes out.
assert_eq!(crate::html::export(&d).matches("<img").count(), 1);
assert_eq!(crate::html::export(&d).unwrap().matches("<img").count(), 1);
}
/// Every text span of the flow, with its formatting.
@@ -1209,16 +1218,17 @@ fn dropped_names_and_links_are_logged_once_per_document() {
let count = |w: &[String], what: &str| w.iter().filter(|l| l.contains(what)).count();
for _ in 0..2 {
// Each import is its own document: the second is reported too.
let (doc, warned) = crate::test_log::warnings(|| crate::html::import(&html));
let (doc, warned) = crate::test_log::warnings(|| crate::html::import(&html).unwrap());
assert!(doc.body.len() == 1, "the text is kept");
assert_eq!(count(&warned, "font names longer"), 1, "{warned:?}");
assert_eq!(count(&warned, "links longer"), 1, "{warned:?}");
}
let (_, warned) = crate::test_log::warnings(|| crate::html::import("<p><a href=\"https://e.com\" style=\"font-family:Georgia\">fine</a></p>"));
let (_, warned) =
crate::test_log::warnings(|| crate::html::import("<p><a href=\"https://e.com\" style=\"font-family:Georgia\">fine</a></p>").unwrap());
assert!(warned.is_empty(), "nothing left out, nothing said: {warned:?}");
let md = format!("[a](https://e.com/{long}) [b](https://e.com/{long})");
let (_, warned) = crate::test_log::warnings(|| crate::markdown::import(&md));
let (_, warned) = crate::test_log::warnings(|| crate::markdown::import(&md).unwrap());
assert_eq!(count(&warned, "links longer"), 1, "{warned:?}");
let rtf =
@@ -1228,14 +1238,14 @@ fn dropped_names_and_links_are_logged_once_per_document() {
assert_eq!(count(&warned, "style names longer"), 1, "{warned:?}");
let tex = format!("\\href{{https://e.com/{long}}}{{a}} \\url{{https://e.com/{long}}}");
let (_, warned) = crate::test_log::warnings(|| crate::latex::import(tex.as_bytes()));
let (_, warned) = crate::test_log::warnings(|| crate::latex::import(tex.as_bytes()).unwrap());
assert_eq!(count(&warned, "links longer"), 1, "{warned:?}");
}
#[test]
fn html_title_outside_head_is_metadata_not_body() {
for html in ["<title>T</title><p>b</p>", "<html><title>T</title><body>b</body></html>"] {
let d = crate::html::import(html);
let d = crate::html::import(html).unwrap();
assert_eq!(para_texts(&d), vec!["b".to_string()], "{html}");
assert_eq!(d.core.title, "T", "{html}");
}
@@ -1261,7 +1271,7 @@ fn html_container_shading_is_paragraph_shading_while_inline_highlight_stays_on_r
r#"<div style="background-color:#1e1e1e"><p>text <code style="background-color:#eeeeee">x</code></p></div>"#,
r#"<div style="background-color:#1e1e1e"><div>a</div><div>&nbsp;</div><div>b</div></div>"#,
);
let doc = crate::html::import(html);
let doc = crate::html::import(html).unwrap();
assert_eq!(doc.body.len(), 7);
let Block::Para(code) = &*doc.body[0] else { panic!("expected code paragraph") };
@@ -1286,8 +1296,8 @@ fn html_container_shading_is_paragraph_shading_while_inline_highlight_stays_on_r
assert_eq!(line.props.shading, Some(wordcraft_doc::Rgb(0x1e, 0x1e, 0x1e)), "line {idx} (blank included) keeps container shading");
}
for exported in [crate::html::export(&doc), crate::html::export_fragment(&doc)] {
let back = crate::html::import(&exported);
for exported in [crate::html::export(&doc).unwrap(), crate::html::export_fragment(&doc).unwrap()] {
let back = crate::html::import(&exported).unwrap();
let Block::Para(p0) = &*back.body[0] else { panic!("expected paragraph 0") };
let Block::Para(p1) = &*back.body[1] else { panic!("expected paragraph 1") };
let Block::Para(p2) = &*back.body[2] else { panic!("expected paragraph 2") };
@@ -1306,7 +1316,7 @@ fn odt_list_item_later_paragraphs_stay_in_the_item() {
let fodt = r#"<?xml version="1.0" encoding="UTF-8"?>
<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" office:version="1.3" office:mimetype="application/vnd.oasis.opendocument.text"><office:automatic-styles><text:list-style style:name="L1"><text:list-level-style-number text:level="1" style:num-format="1"/></text:list-style></office:automatic-styles><office:body><office:text><text:list text:style-name="L1"><text:list-item><text:p>One</text:p><text:p>Still one</text:p></text:list-item><text:list-item><text:p>Two</text:p></text:list-item></text:list></office:text></office:body></office:document>"#;
let doc = crate::odt::import_flat(fodt.as_bytes()).unwrap();
let html = crate::html::export(&doc);
let html = crate::html::export(&doc).unwrap();
assert_eq!(html.matches("<ol").count(), 1, "one list, not restarted: {html}");
let (one, still, two) = (html.find("One").unwrap(), html.find("Still one").unwrap(), html.find("Two").unwrap());
assert!(one < still && still < two, "{html}");
+13 -5
View File
@@ -276,7 +276,7 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
Block::Para(p) => {
// A paragraph after one whose mark is hidden goes on from that one's last line
// (Word, #3986; see `Joint`); one that shows nothing passes the place on.
let (mark_hidden, shows_nothing, taken) = Joint::arrive(ctx, &mut joint, (i, p), (width, frames), table);
let (mark_hidden, shows_nothing, taken) = Joint::arrive(ctx, &mut joint, (i, p), (width, frames), table, cell_frame);
let p = taken.as_ref().map_or(p, |t| &t.para);
let label = ctx.next_label(p);
let listed = label.is_some();
@@ -477,7 +477,7 @@ fn natural_width(pl: &ParaLayout) -> f32 {
}
/// A text frame's placement as a floating object's (`w:framePr` → anchors, alignment, wrap).
fn frame_float(fr: &wordcraft_doc::props::TextFrame) -> Float {
pub(crate) fn frame_float(fr: &wordcraft_doc::props::TextFrame) -> Float {
let anchor = |a: &str, text: Anchor| match a {
"page" => Anchor::Page,
"margin" => Anchor::Margin,
@@ -777,13 +777,14 @@ impl Joint {
(i, p): (usize, &Paragraph),
(width, frames): (f32, bool),
table: Option<&para::CellText>,
cell_frame: impl Fn(&wordcraft_doc::props::TextFrame) -> bool,
) -> (bool, bool, Option<TakenUp>) {
let chr = table.map(|t| &t.chr);
let mark_hidden = ctx.mark_hidden(p, chr);
let shows_nothing = mark_hidden && ctx.text_hidden(p, chr);
let came = joint.take().filter(|j| j.next == i);
*joint = came.filter(|_| shows_nothing).map(|j| Joint { next: i + 1, ..j });
let taken = came.filter(|_| !shows_nothing).and_then(|j| j.take_up(ctx, p, (width, frames), table));
let taken = came.filter(|_| !shows_nothing).and_then(|j| j.take_up(ctx, p, (width, frames), table, cell_frame));
(mark_hidden, shows_nothing, taken)
}
@@ -827,9 +828,16 @@ impl Joint {
/// Paragraph `p` of a box `width` wide going on from here, unless a page break comes before
/// it, it runs right to left or it is a text frame (`frames`: placed apart, sharing no line):
/// without its space before, as [`Joint::fit`] lays it out.
fn take_up(self, ctx: &mut Ctx, p: &Paragraph, (width, frames): (f32, bool), table: Option<&para::CellText>) -> Option<TakenUp> {
fn take_up(
self,
ctx: &mut Ctx,
p: &Paragraph,
(width, frames): (f32, bool),
table: Option<&para::CellText>,
cell_frame: impl Fn(&wordcraft_doc::props::TextFrame) -> bool,
) -> Option<TakenUp> {
let own = ctx.doc.styles.resolve_para_in(&p.props, table.map(|t| &t.para));
if own.page_break_before || own.bidi || (frames && own.frame.is_some()) {
if own.page_break_before || own.bidi || own.frame.as_ref().is_some_and(|fr| frames && cell_frame(fr)) {
return None;
}
let mut para = p.clone();
+57 -3
View File
@@ -32,6 +32,14 @@ pub(crate) struct Key {
pub(crate) joined: Option<(u32, bool)>,
}
pub(crate) struct StylesEnv {
styles: std::sync::Weak<wordcraft_doc::styles::StyleSheet>,
numbering: std::sync::Weak<wordcraft_doc::numbering::Numbering>,
default_tab: u32,
footnote_format: wordcraft_doc::section::NumFormat,
hash: u64,
}
/// Memoised paragraph layouts.
#[derive(Default)]
pub struct LayoutCache {
@@ -44,6 +52,7 @@ pub struct LayoutCache {
/// kept, so no other picture's bytes can come to have its address ([`Outlines`]).
pub(crate) outlines: Outlines,
pub(crate) env: u64,
pub(crate) styles_env: Option<StylesEnv>,
pub(crate) used: HashSet<Key>,
/// The STYLEREF style index of the last pass and what it was built from: the body blocks
/// (shared, so an edited block is a different pointer) and `env` (styles and numbering). Kept
@@ -67,6 +76,7 @@ impl LayoutCache {
self.paras.clear();
self.measures.clear();
self.outlines.clear();
self.styles_env = None;
self.styleref = None;
}
@@ -91,12 +101,56 @@ pub(crate) fn hash_of<T: Hash>(t: &T) -> u64 {
h.finish()
}
pub(crate) fn env_hash(doc: &Document, opts: &LayoutOptions) -> u64 {
let s = serde_json::to_string(&(&doc.styles, &doc.numbering, doc.settings.default_tab, &doc.settings.footnote_format)).unwrap_or_default();
struct HashWriter<'a>(&'a mut std::collections::hash_map::DefaultHasher);
impl std::io::Write for HashWriter<'_> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0.write(buf);
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
/// Fingerprint of stylesheet, numbering, default tab, and footnote format, memoised on
/// [`LayoutCache::styles_env`] via `Weak` pointers so unchanged passes skip JSON serialisation.
/// Holding live `Weak` references keeps the underlying `ArcInner` allocations reserved, ensuring a
/// fresh `Arc` allocation cannot reuse a still-cached address.
fn styles_env_hash(doc: &Document, cache: &mut LayoutCache) -> u64 {
let tab = doc.settings.default_tab.to_bits();
if let Some(cached) = &cache.styles_env
&& cached.styles.as_ptr() == Arc::as_ptr(&doc.styles)
&& cached.styles.strong_count() > 0
&& cached.numbering.as_ptr() == Arc::as_ptr(&doc.numbering)
&& cached.numbering.strong_count() > 0
&& cached.default_tab == tab
&& cached.footnote_format == doc.settings.footnote_format
{
return cached.hash;
}
let mut sh = std::collections::hash_map::DefaultHasher::new();
let _ = serde_json::to_writer(HashWriter(&mut sh), &(&doc.styles, &doc.numbering, doc.settings.default_tab, &doc.settings.footnote_format));
let hash = sh.finish();
cache.styles_env = Some(StylesEnv {
styles: Arc::downgrade(&doc.styles),
numbering: Arc::downgrade(&doc.numbering),
default_tab: tab,
footnote_format: doc.settings.footnote_format,
hash,
});
hash
}
pub(crate) fn env_hash(doc: &Document, cache: &mut LayoutCache, opts: &LayoutOptions) -> u64 {
let styles = styles_env_hash(doc, cache);
// Outline view lays paragraphs out changed (no indents; plain without text formatting).
let outline = (opts.view == ViewMode::Outline).then(|| opts.outline.as_ref().is_some_and(|o| o.plain));
let mut h = std::collections::hash_map::DefaultHasher::new();
s.hash(&mut h);
styles.hash(&mut h);
// The compatibility mode changes paragraph layout too (widow control in table cells).
doc.settings.compat_mode.hash(&mut h);
opts.show_hidden.hash(&mut h);
opts.hide_deleted.hash(&mut h);
opts.hide_marked.hash(&mut h);
+31 -6
View File
@@ -1,9 +1,9 @@
use super::boxes::{BoxInput, BoxLayout, Edges, Joint, joined, layout_box, push_para};
use super::boxes::{BoxInput, BoxLayout, Edges, Joint, frame_float, joined, layout_box, push_para};
use super::cache::has_page_number_fields;
use super::ctx::{Ctx, Joining};
use super::floats::{
FloatAnchor, LateFloats, ObjFrame, ObjectPlacement, anchor_floats, body_wraps, continued_exclusions, fitting, late_floats, place_late,
place_objects,
FloatAnchor, LateFloats, ObjFrame, ObjectPlacement, anchor_floats, body_wraps, continued_exclusions, fitting, float_rect, late_floats,
place_late, place_objects,
};
use super::notes::{DECOR_STORY, NoteBox, para_notes};
use super::page::{PageBuilder, PageFrame, item_bottom};
@@ -19,6 +19,9 @@ use crate::WRAP_RELAYS;
/// A body paragraph. One after a paragraph whose mark is hidden goes on from that one's last line,
/// as Word shows them, on one line (#3986): see [`Joint`].
pub(crate) fn place_para(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block: usize, body_top: f32) {
if place_page_text_frame(ctx, pb, p, block) {
return;
}
let joint = pb.joint.take().filter(|j| !pb.web && j.next == block && j.page == pb.pages.len() && j.col == pb.col);
let mark_hidden = ctx.mark_hidden(p, None);
// Nothing of it is shown: the place passes on to the paragraph after it.
@@ -96,6 +99,28 @@ fn unjoin(ctx: &mut Ctx, p: &Paragraph) {
}
}
fn place_page_text_frame(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block: usize) -> bool {
if pb.web {
return false;
}
let Some(fr) = ctx.doc.styles.resolve_para_in(&p.props, None).frame else { return false };
if fr.h_anchor != "page" || fr.v_anchor != "page" {
return false;
}
let width = fr.w.unwrap_or_else(|| pb.col_w()).clamp(1.0, 1584.0);
let label = ctx.next_label(p);
let pl = ctx.para_labelled(p, width, None, &[], label);
let height = fr.h.map_or(pl.height, |h| if fr.h_exact { h } else { h.max(pl.height) });
let float = frame_float(&fr);
let page = PageFrame { sect: pb.sect, margin_top: None, origin: (0.0, 0.0), number: pb.number, mirror: ctx.mirror };
let rect = float_rect(Some(page), (pb.col_x(), pb.col_w()), pb.y, width, height, &float);
let path = [block as u32];
if let Some(page) = pb.page() {
push_para(&mut page.items, (StoryRef::Body, &path), &pl, (0, pl.lines.len()), (rect.x, rect.y), width, Edges::own(&pl, 0, pl.lines.len()));
}
true
}
/// A closing mark before a continuous section takes no room after content. An otherwise empty
/// section starting a new page retains its paragraph line.
fn place_para_alone(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block: usize, body_top: f32) {
@@ -890,10 +915,10 @@ fn notes_limit(pb: &PageBuilder, new_notes: &[NoteBox], line_notes: &[NoteBox])
/// the text (see `baseline_offset`), and Word lets that leading of a page's last line run into the
/// bottom margin: only the text has to fit (observed: a double-spaced 12pt line stays on the page
/// while its text ends above the margin, about half a line lower than when the whole line must
/// fit). Only the bottom margin takes that leading: a footer taller than the margin, or
/// footnotes (`free` is false), keep the whole line clear of them.
/// fit). Only the bottom margin takes that leading, or the top of a footer that reaches above it
/// (see [`PageBuilder::at_margin`]): footnotes (`free` is false) keep the whole line clear of them.
fn fit_height(pb: &PageBuilder, l: &para::Line, rp: &wordcraft_doc::resolve::ResolvedPara, free: bool) -> f32 {
let at_margin = pb.bottom >= pb.sect.page_h - pb.sect.margin_bottom - 0.01;
let at_margin = pb.at_margin();
match rp.line_spacing {
// The text (or a taller picture) ends `leading` above the line's bottom.
wordcraft_doc::props::LineSpacing::Multiple(m) if m > 1.0 && at_margin && free => (l.height - l.leading).clamp(0.0, l.height),
+11
View File
@@ -89,6 +89,9 @@ pub(crate) struct PageBuilder<'a> {
/// Top of the footer of the pages being started: a footer reaching above the bottom margin
/// pushes the body up (`f32::MAX`: no footer).
pub(crate) foot_top: f32,
/// How low the last line's leading may reach on the current page: the bottom margin, or the
/// top of a footer reaching above it (set as the page starts, from that page's footer).
pub(crate) leading_floor: f32,
/// The wrap areas pages start with ([`EarlyFloats`]) ...
pub(crate) early: &'a EarlyFloats,
/// ... and how many of the current page's `excl` they are (its first ones).
@@ -359,6 +362,7 @@ impl PageBuilder<'_> {
self.number = self.restart_at.take().unwrap_or_else(|| self.number.saturating_add(1));
let (w, h) = if self.web { (s.page_w, f32::MAX / 4.0) } else { (s.page_w, s.page_h) };
let bottom = self.body_bottom(body_top);
self.leading_floor = (s.page_h - s.margin_bottom).min(self.foot_top);
let body = Rect::new(s.margin_left + s.gutter, body_top, s.text_width(), (bottom - body_top).max(36.0));
let mut decor = Vec::new();
if !self.web {
@@ -437,6 +441,13 @@ impl PageBuilder<'_> {
self.bottom = self.bottom.min(self.top + h);
}
}
/// Whether the body ends at the bottom margin, or at the top of a footer that reaches above
/// it: the page's last multiple-spaced line may leave its leading there (see `fit_height`).
/// Word lets it run past the footer's top as into the margin, whatever the footer holds (a
/// page number, several lines of text, an empty paragraph): only the text has to end above it.
pub(crate) fn at_margin(&self) -> bool {
self.bottom >= self.leading_floor - 0.01
}
/// The bottom of the body on a page started with its body at `body_top`: a footer taller than
/// the bottom margin pushes it up (Word: no gap), leaving it at least a little room.
fn body_bottom(&self, body_top: f32) -> f32 {
+94 -9
View File
@@ -5,7 +5,7 @@ use super::chars::{
};
use super::grid::east_asian;
use super::model::{ClKind, Cluster, Enclosed, Glyph, ParaEnv, RubyLayout, StyleRun, SymbolRun};
use super::{Arc, Document, FaceRef, NumeralMode, ResolvedChar, RubyAlign, SOFT_HYPHEN};
use super::{Arc, Document, FaceRef, NumeralMode, OBJ, ResolvedChar, RubyAlign, SOFT_HYPHEN};
use wordcraft_fonts::ShapeContext;
pub(super) struct Builder<'a> {
@@ -52,6 +52,25 @@ struct SegmentInput<'a> {
context: &'a [bool],
}
/// Whether `face` draws `cluster`, a character and its combining marks, with no missing glyph.
/// The shaper composes a pair the face has a precomposed glyph for (`=` and U+0338 as `≠`), so a
/// face without the mark itself can still draw the pair.
fn draws_all(face: FaceRef, cluster: &str) -> bool {
let glyphs = wordcraft_fonts::shape_in(&face, cluster, &[], |c| c, ShapeContext::default());
!glyphs.is_empty() && glyphs.iter().all(|g| g.gid != 0)
}
/// A face other than `current` that draws all of `cluster` (CSS Fonts 4 §5.3, cluster matching):
/// the run's Thai face or its own font when one does, else the first face in fallback order with
/// every character of it that draws something.
fn cluster_face(cluster: &str, current: FaceRef, run_face: Option<FaceRef>, primary: FaceRef, bold: bool, italic: bool) -> Option<FaceRef> {
if let Some(f) = run_face.into_iter().chain([primary]).filter(|f| f.id() != current.id()).find(|f| draws_all(*f, cluster)) {
return Some(f);
}
let chars: Vec<char> = cluster.chars().filter(|c| draws_something(*c)).collect();
wordcraft_fonts::FontDb::global().fallback_for_run(&chars, primary.id(), bold, italic).map(|f| FaceRef::of(&f))
}
impl<'a> Builder<'a> {
/// Displayed form of `c` at run-relative byte `at` (Word › Numeral): one char in, one
/// char out. `rtl` is the shaping direction; in Context mode `context` (from
@@ -68,6 +87,10 @@ impl<'a> Builder<'a> {
let mut seg_start = 0;
let mut cur: Option<SegKey> = None;
let mut segs = Vec::new();
// The character the marks after it belong to: where it starts, and as drawn.
let mut base: Option<(usize, char)> = None;
// The character whose cluster was matched, and whether its marks stay with it.
let mut matched: Option<(usize, bool)> = None;
for (i, c) in text.char_indices() {
let rtl = use_levels && levels.get(lbase + i).is_some_and(|l| l % 2 == 1);
let c = show(c);
@@ -78,19 +101,67 @@ impl<'a> Builder<'a> {
_ => rc_cs.is_some() && rc.uses_complex(dc),
};
let primary = if complex { primary_cs.unwrap_or(primary) } else { primary };
let face = match cur {
Some(k) if mark => k.face,
let (bold, italic) = if complex { (rc.bold_cs, rc.italic_cs) } else { (rc.bold, rc.italic) };
// A mark stays in the face of the character it belongs to (Arabic harakat with their
// letter, so the letters join) while that face draws it. When it doesn't, the
// character and its marks go together to a face that draws them all (CSS Fonts 4
// §5.3, cluster matching). With no such face, a mark in left-to-right text that isn't
// complex script is matched on its own like any other character; in right-to-left or
// complex-script text it stays with its letter (#7865). A cluster is matched once, at
// its first mark the face lacks: matching it again at every later mark would make a
// long run of marks quadratic.
let mut with_base = false;
let mut moved = None;
if let Some(k) = cur.filter(|_| mark) {
let current = k.face.unwrap_or(primary);
with_base = !draws_something(c) || current.covers(dc);
if !with_base {
match (base.filter(|(at, _)| *at >= seg_start), matched) {
(Some((at, _)), Some((done, stays))) if done == at => with_base = stays,
(Some((at, b)), _) => {
let marks = text.get(at..).unwrap_or("").chars().skip(1).map(show).take_while(|m| is_mark(*m));
let all: String = std::iter::once(b).chain(marks).inspect(|_| crate::work::steps(1)).collect();
if draws_all(current, &all) {
with_base = true;
} else if let Some(f) = cluster_face(&all, current, run_face, primary, bold, italic) {
// The character goes to that face with its marks.
if at > seg_start {
segs.push((seg_start, at, k));
seg_start = at;
}
let face = (f.id() != primary.id()).then_some(f);
cur = Some(SegKey { face, ..k });
moved = Some(face);
} else {
with_base = k.complex || k.rtl;
}
matched = Some((at, with_base || moved.is_some()));
}
(None, _) => with_base = k.complex || k.rtl,
}
}
}
if !mark {
base = (!c.is_control() && c != OBJ).then_some((i, dc));
}
let face = match (moved, cur) {
(Some(face), _) => face,
(None, Some(k)) if with_base => k.face,
_ if !complex && east_asian(c) && primary_ea.is_some_and(|f| f.covers(c)) => primary_ea,
_ if !c.is_control() && c != SOFT_HYPHEN && run_face.is_some_and(|f| f.covers(dc)) => run_face,
_ if primary.covers(dc) || c.is_whitespace() || c.is_control() || c == SOFT_HYPHEN => None,
Some(SegKey { face: Some(face), .. }) if face.covers(dc) => Some(face),
(None, Some(SegKey { face: Some(face), .. })) if face.covers(dc) => Some(face),
_ if !complex && ea_face.is_some() && crate::kinsoku::is_east_asian(c) => ea_face,
_ => {
let (bold, italic) = if complex { (rc.bold_cs, rc.italic_cs) } else { (rc.bold, rc.italic) };
wordcraft_fonts::FontDb::global().fallback_styled(dc, primary.id(), bold, italic).map(|f| FaceRef::of(&f))
}
_ => wordcraft_fonts::FontDb::global().fallback_styled(dc, primary.id(), bold, italic).map(|f| FaceRef::of(&f)),
};
let key = SegKey { face, small: rc.small_caps && !rc.caps && c.is_lowercase(), complex, rtl };
// A mark is set like the character it belongs to, as for `complex`: in small capitals at
// that character's size, so the two stay in one shaping run and its cluster is matched
// whole.
let small = match cur {
Some(k) if mark => k.small,
_ => rc.small_caps && !rc.caps && c.is_lowercase(),
};
let key = SegKey { face, small, complex, rtl };
match cur {
Some(previous) if previous.same(&key) => {}
Some(previous) => {
@@ -139,6 +210,15 @@ impl<'a> Builder<'a> {
// the height Word gives it.
let (a, d) = match wordcraft_fonts::word::symbol_line(&rc.font, &r) {
Some((a, d)) => (a * face.upem, d * face.upem),
// A character Times New Roman or its metric twin lacks: the twin lacks more than
// Times New Roman ("‒", "₽" in Liberation Serif), so the line is as tall as the run's
// font, as with Times New Roman in Word, not as the taller fallback. East Asian text
// keeps its face's height.
None if face_override.is_some() && is_times_twin(&r.face.family) && !face.is_east_asian() => {
let (a, d) = wordcraft_fonts::word::line_metrics(&r.face);
let k = face.upem / r.face.upem.max(1.0);
(a * k, d * k)
}
None => wordcraft_fonts::word::line_metrics(&face),
};
let k = size as f64 / face.upem.max(1.0);
@@ -615,6 +695,11 @@ impl<'a> Builder<'a> {
}
}
/// Times New Roman or one of its metric twins.
fn is_times_twin(family: &str) -> bool {
["Times New Roman", "Liberation Serif", "Tinos"].iter().any(|f| family.eq_ignore_ascii_case(f))
}
/// Lay out an `EQ \o` field (ECMA-376 Part 1 §17.16.5.20): its arguments drawn on top of one
/// another, as one cluster. An enclosure symbol among them (○ □ △ ◇, see
/// [`wordcraft_doc::eq::EncloseShape`]) is drawn as a shape around the text rather than as a
+2 -1
View File
@@ -55,7 +55,8 @@ pub(super) fn caps_expands(c: char) -> bool {
}
/// Combining marks and joiners (bidi classes NSM, BN: harakat, ZWNJ, ZWJ) belong to the
/// character before them: same font, same shaping run, so Arabic joining isn't broken.
/// character before them: same font, same shaping run, so Arabic joining isn't broken. A mark
/// that font can't draw takes its character to a face that draws both (`segment_keys`, #7865).
pub(super) fn is_mark(c: char) -> bool {
use unicode_bidi::BidiClass::{BN, NSM};
// No ASCII character is a mark (its BN characters are controls).
+14 -5
View File
@@ -442,7 +442,7 @@ impl<'e> Breaker<'e> {
/// tallest picture on it (which sits on the baseline).
fn extents(&self, pl: &ParaLayout, (c0, c1): (usize, usize)) -> Extents {
let rp = &self.rp;
let mut ex = Extents { asc: 0.0, desc: 0.0, obj_asc: 0.0, obj_desc: 0.0, text: false };
let mut ex = Extents { asc: 0.0, desc: 0.0, obj_asc: 0.0, obj_desc: 0.0, text: false, single: 0.0 };
let mut any = false;
let dropped = pl.drop_cap.map_or(0, |d| d.0);
for (k, c) in pl.clusters.get(c0..c1).into_iter().flatten().enumerate() {
@@ -486,6 +486,7 @@ impl<'e> Breaker<'e> {
};
ex.asc = ex.asc.max(a);
ex.desc = ex.desc.max(d);
ex.single = ex.single.max(a + d);
any = true;
// Text needs its descent below the line; so do inline math (an object with its own
// descent) and a check box. A line break ending the line is no text.
@@ -503,7 +504,7 @@ impl<'e> Breaker<'e> {
/// The line's height, baseline and text extent.
fn measure(&self, pl: &ParaLayout, range: (usize, usize)) -> Measure {
let rp = &self.rp;
let Extents { mut asc, mut desc, obj_asc, obj_desc, text } = self.extents(pl, range);
let Extents { mut asc, mut desc, obj_asc, obj_desc, text, single } = self.extents(pl, range);
let mut text_natural = asc + desc;
let font_desc = desc;
desc = desc.max(obj_desc);
@@ -516,8 +517,8 @@ impl<'e> Breaker<'e> {
// Word, measured with Arial at 10 and 20 pt, single, 1.15 and 1.5 spacing: a 30 pt picture
// alone takes 30, 30 + 0.15 and 30 + 0.5 times the font's height, lowered 10 or 30 pt or
// not; raised 10 pt, 10 more; a 6 pt one, the font's height; beside text and lowered
// 10 pt, 30. Not on a line lowered further than the picture's height, which layout limits
// to that height where Word's line keeps growing.
// 10 pt, 30; lowered 30 pt, a 6 pt one makes a 30 pt line (`drawing` leaves the lowering
// whole; exact spacing keeps it to the picture's height, see `extents`).
let spacing = if let LineSpacing::Multiple(m) = rp.line_spacing { Some(m) } else { None };
let pictures_alone = !text && obj_asc + obj_desc > 0.0 && spacing.is_some();
let below = if pictures_alone { obj_desc } else { desc };
@@ -554,6 +555,10 @@ impl<'e> Breaker<'e> {
}
}
}
// Multiple spacing adds (m - 1) x the tallest of the line's runs, not of the line: a line
// mixing fonts is as much taller as its runs' extents make it, once (Word for Mac and
// Windows: 10 pt Times New Roman with 10 pt Courier New at 1.5 and double spacing).
let run_leading = if single > 0.0 && !pictures_alone { single.min(text_natural) } else { text_natural };
// Keep the picture floor independent of list-label metrics.
let natural = asc + desc;
let pictures = if obj_asc > asc { obj_asc + desc } else { 0.0 };
@@ -562,7 +567,9 @@ impl<'e> Breaker<'e> {
let (height, centred) = match (rp.line_spacing, grid) {
(LineSpacing::Multiple(m), Some(g)) => ((g.snap_height(natural) * m).max(g.snap_height(pictures)), true),
(LineSpacing::AtLeast(v), Some(g)) => (g.snap_height(natural.max(pictures)).max(v), true),
(LineSpacing::Multiple(m), None) => ((text_natural * m + label_extra).max(text_pictures + (m - 1.0).max(0.0) * font_natural), false),
(LineSpacing::Multiple(m), None) => {
((text_natural + (m - 1.0) * run_leading + label_extra).max(text_pictures + (m - 1.0).max(0.0) * font_natural), false)
}
(LineSpacing::AtLeast(v), None) => (natural.max(text_pictures).max(v), false),
(LineSpacing::Exactly(v), _) => (v, false),
};
@@ -745,6 +752,8 @@ struct Extents {
obj_desc: f32,
/// Whether the line holds text besides its pictures (spaces and tabs don't count).
text: bool,
/// The tallest of its runs' own heights (ascent plus descent): the multiple's leading.
single: f32,
}
/// A line's height and baseline, and the extent of its text.
+26 -3
View File
@@ -101,6 +101,11 @@ fn is_special(c: char) -> bool {
fn paragraph_props(p: &Paragraph, env: &ParaEnv) -> ResolvedPara {
let doc = env.doc;
let mut rp = doc.styles.resolve_para_in(&p.props, env.table.map(|t| &t.para));
// Before Word 2013 layout (compatibility mode 15) a row split across pages divides its cells'
// text at any line: widow/orphan control doesn't apply in a table (measured in modes 12, 14).
if env.table.is_some() && doc.settings.compat_mode < wordcraft_doc::COMPAT_MODE_CURRENT {
rp.widow_control = false;
}
if let Some(spacing) = env.read_line_spacing.filter(|s| s.is_finite() && (1.0..=2.0).contains(s)) {
rp.line_spacing = wordcraft_doc::props::LineSpacing::Multiple(spacing);
}
@@ -392,6 +397,11 @@ impl<'a> Shaped<'a> {
},
_ => w,
};
// Word keeps the height in whole twips and drops the rest of the EMUs: 2007874 EMU
// (3161.99tw) is drawn 158.05pt high, and only that has to fit above the bottom margin
// (Word for Mac and Windows). Back to whole EMUs first: f32 points keep them to the EMU
// for pictures up to a page high.
let h = (((h as f64 * 12_700.0).round() / 635.0).floor() / 20.0) as f32;
let (w, h) = (w.clamp(1.0, 4000.0), h.clamp(1.0, 4000.0));
let s = if env.fit_objects && w > maxw { maxw / w } else { 1.0 };
// The line makes room for effects (shadows) around the picture too, and
@@ -677,9 +687,13 @@ pub fn layout_para(p: &Paragraph, env: &ParaEnv) -> ParaLayout {
if rp.snap_to_grid {
snap_chars(&mut sh.b, &p.text, &env.grid);
}
// Text on a character grid keeps to its cells.
let auto_space =
if rp.snap_to_grid && env.grid.chars.is_some() { Vec::new() } else { auto_space(&mut sh.b, &p.text, rp.auto_space_de, rp.auto_space_dn) };
// Text snapping to every cell of a character grid (`snapToChars`) keeps to its cells. On a
// `linesAndChars` grid Word keeps the automatic space, as on a line grid (#6584).
let auto_space = if rp.snap_to_grid && env.grid.snap_all && env.grid.chars.is_some() {
Vec::new()
} else {
auto_space(&mut sh.b, &p.text, rp.auto_space_de, rp.auto_space_dn)
};
let mut skip = sh.left.clone();
skip.extend(sh.bare.iter().cloned());
let bt = BreakText::new(&p.text, skip);
@@ -854,6 +868,15 @@ fn break_positions(text: &str, rp: &wordcraft_doc::resolve::ResolvedPara) -> Vec
if !before_slash.is_empty() {
found.extend(before_slash);
}
// Word breaks after a space whatever follows it, where UAX #14 keeps a space with a closing
// bracket or punctuation after it (LB13: "x :=", "false );", "JDK} ,") and an opening bracket
// with the space after it (LB14: "( word"). Measured in Word for Mac and Windows: the next line
// starts with ":=", ";", ",", ".", ")", "]", "}", "!", "?", "%", or with "word" after "( ". Not
// before another space or a no-break space: the spaces stay together; nor before a word joiner
// or a zero-width space, which UAX #14 never lets start a line (LB11, LB7).
found.extend(text.match_indices(' ').map(|(i, _)| i + 1).filter(|&i| {
text.get(i..).and_then(|t| t.chars().next()).is_some_and(|c| !c.is_whitespace() && !matches!(c, '\u{2060}' | '\u{FEFF}' | '\u{200B}'))
}));
// Word breaks after a hyphen even when a digit follows ("2016-" / "2022"), where UAX #14
// keeps a hyphen and a number together (LB25), and when a slash and a letter follow
+10 -3
View File
@@ -54,7 +54,7 @@ struct Sec<'p> {
/// Forget cached layouts made for another environment, and what the last pass used.
fn reset_cache(doc: &Document, cache: &mut LayoutCache, opts: &LayoutOptions) {
let env = env_hash(doc, opts);
let env = env_hash(doc, cache, opts);
if env != cache.env {
cache.paras.clear();
cache.measures.clear();
@@ -234,6 +234,7 @@ fn new_page_builder<'p>(
sect_beneath: false,
beneath: false,
foot_top: f32::MAX,
leading_floor: 0.0,
early,
seeded: 0,
settle,
@@ -521,12 +522,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;
}
}
+68 -9
View File
@@ -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);
@@ -615,6 +616,51 @@ fn table_frame(ctx: &mut Ctx, t: &Table, avail: f32, depth: usize, style: Option
}
pub fn layout_table(ctx: &mut Ctx, story: StoryRef, t: &Table, path: &[u32], avail: f32, depth: usize) -> TableLayout {
layout_table_rows(ctx, story, t, path, avail, depth, None)
}
/// Row `ri` of the body table laid out again for where it lands on a page, `room` points above the
/// bottom of the page body: a merged cell starting in it that runs on past the page end is
/// aligned (and its turned text laid out) within that room, as its text is drawn with this row.
/// The row's height is the one [`layout_table`] gave it.
pub fn layout_table_row_in(ctx: &mut Ctx, t: &Table, path: &[u32], avail: f32, ri: usize, room: f32) -> Option<RowLayout> {
// A look ahead: list and equation numbers in the cells don't count again.
let (counters, eq_count) = (ctx.counters.clone(), ctx.eq_count);
let mut tl = layout_table_rows(ctx, StoryRef::Body, t, path, avail, 1, Some((ri, room)));
(ctx.counters, ctx.eq_count) = (counters, eq_count);
tl.rows.pop()
}
/// How many rows after row `ri` the merged cells starting in it run on (0 without any).
pub(crate) fn merge_rows_after(t: &Table, ri: usize) -> usize {
let Some(row) = t.rows.get(ri) else { return 0 };
let mut gx = row.first_grid();
let mut most = 0;
for c in &row.cells {
let g = gx;
gx += c.span();
if c.props.vmerge != VMerge::Restart {
continue;
}
let mut k = ri + 1;
while t.rows.get(k).is_some_and(|r| {
let mut gx = r.first_grid();
r.cells.iter().any(|x| {
let at = gx;
gx += x.span();
at == g && x.props.vmerge == VMerge::Continue
})
}) {
k += 1;
}
most = most.max(k - ri - 1);
}
most
}
/// [`layout_table`], or with `only` = (row, room) just that row, its merged cells aligned within
/// `room` (see [`layout_table_row_in`]).
fn layout_table_rows(ctx: &mut Ctx, story: StoryRef, t: &Table, path: &[u32], avail: f32, depth: usize, only: Option<(usize, f32)>) -> TableLayout {
let style = table_style(ctx, t);
// Cell text formatting and looks per set of style parts, built once per table.
let mut cell_text: Vec<(Region, CellText)> = Vec::new();
@@ -648,11 +694,13 @@ pub fn layout_table(ctx: &mut Ctx, story: StoryRef, t: &Table, path: &[u32], ava
let span = cell.span();
let x0 = colx.get(g).copied().unwrap_or(acc);
let x1 = colx.get((g + span).min(ncols)).copied().unwrap_or(acc);
// Right to left: grid columns run from the right edge, and the start (left) margin
// is on the cell's right.
// Right to left: grid columns run from the right edge. The margins stay on the sides
// they name: Word for Windows keeps a cell's `w:left` (or `w:start`) margin on its
// left in a right-to-left table, the cell's and the table's alike, though it draws the
// cell's `w:left` border on its right.
let (x0, x1) = if rtl { ((acc - x1).max(0.0), (acc - x0).max(0.0)) } else { (x0, x1) };
let m = cell.props.resolved_margins(margins_def);
let margins = if rtl { [row_top, m[3], row_bottom, m[1]] } else { [row_top, m[1], row_bottom, m[3]] };
let margins = [row_top, m[1], row_bottom, m[3]];
let cw = (x1 - x0 - margins[1] - margins[3]).max(4.0);
let region = region_of(t, style.as_ref(), ri, g, span, ncols);
// Conditional formatting, later parts winning (ECMA-376 §17.7.6): whole table, column
@@ -794,7 +842,7 @@ pub fn layout_table(ctx: &mut Ctx, story: StoryRef, t: &Table, path: &[u32], ava
rows.push(cells);
}
grow_vertical_merges(&rows, &mut heights);
finish_table_rows(ctx, TableRows { story, table: t, path, depth, cell_text, rows, heights, bottoms, edges, x, total })
finish_table_rows(ctx, TableRows { story, table: t, path, depth, cell_text, rows, heights, bottoms, edges, x, total, only })
}
fn grow_vertical_merges(rows: &[Vec<CellBox>], heights: &mut [f32]) {
@@ -829,13 +877,15 @@ struct TableRows<'a> {
edges: Vec<f32>,
x: f32,
total: f32,
/// Only this row (and the room under its top for its merged cells), when set.
only: Option<(usize, f32)>,
}
/// Place the laid-out cells of every row: vertical alignment, turned text, borders and the cell
/// rectangles, clipped where the row's exact height or a fixed table's column is too small for
/// the cell's text.
fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout {
let TableRows { story, table: t, path, depth, cell_text, rows, heights, bottoms, edges, x, total } = input;
let TableRows { story, table: t, path, depth, cell_text, rows, heights, bottoms, edges, x, total, only } = input;
// Grid columns holding a vertical-merge continuation, per row.
let cont: Vec<Vec<usize>> = t
.rows
@@ -855,6 +905,9 @@ fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout {
// Second pass: place cells with their row height, fills and borders.
let mut out = Vec::with_capacity(rows.len());
for (ri, cells) in rows.into_iter().enumerate() {
if only.is_some_and(|(row, _)| row != ri) {
continue;
}
let rh = heights.get(ri).copied().unwrap_or(0.0);
let exact = t.rows.get(ri).is_some_and(|r| r.props.height_rule == HeightRule::Exact && r.props.height.is_some_and(|h| h > 0.0));
let mut items = Vec::new();
@@ -895,10 +948,16 @@ fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout {
_ => None,
})
.fold(c.h, f32::max);
// A merged cell's text is drawn with its restart row, even when the merge runs on
// over later pages: only the room left on the page it starts on can align it.
let align_span = match only {
Some((_, room)) if c.vmerge == VMerge::Restart => span_h.min(room.max(0.0)),
_ => span_h,
};
let mut dy = match c.valign {
VAlign::Top => 0.0,
VAlign::Center => ((span_h - align_h) / 2.0).max(0.0),
VAlign::Bottom => (span_h - align_h).max(0.0),
VAlign::Center => ((align_span - align_h) / 2.0).max(0.0),
VAlign::Bottom => (align_span - align_h).max(0.0),
};
let end = (c.vmerge != VMerge::Continue && c.turned.is_none()).then_some(c.end + dy);
let mut cell_items = c.items;
@@ -906,7 +965,7 @@ fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout {
dy = 0.0;
let m = c.margins;
// The lines run the cell's whole height (laid out again if the row grew).
let len = (span_h - (c.h - tn.len)).clamp(4.0, TURNED_LIMIT);
let len = (align_span - (c.h - tn.len)).clamp(4.0, TURNED_LIMIT);
let mut across = tn.across;
if (len - tn.len).abs() > 0.01
&& let Some(cell) = t.rows.get(ri).and_then(|r| r.cells.get(tn.ci))
+20 -3
View File
@@ -73,6 +73,8 @@ pub(crate) fn footer_table_wraps(ctx: &mut Ctx, pb: &PageBuilder) -> Vec<WrapAre
/// The room a table in the text needs to start on a page: its repeated header rows and the least
/// room its first row can start in (whole, or the part of it that splits off). A paragraph kept
/// with the table goes over with it when that much is not left, as in Word.
/// Before Word 2013 layout (compatibility mode 15) the header rows may stay alone at the foot of a
/// page, so the paragraph keeps with them only.
pub(crate) fn table_start_need(ctx: &mut Ctx, t: &wordcraft_doc::Table, block: usize, width: f32) -> f32 {
// A look ahead: list and equation numbers in the cells don't count yet.
let (counters, eq_count) = (ctx.counters.clone(), ctx.eq_count);
@@ -80,6 +82,10 @@ pub(crate) fn table_start_need(ctx: &mut Ctx, t: &wordcraft_doc::Table, block: u
(ctx.counters, ctx.eq_count) = (counters, eq_count);
let headers = t.rows.iter().take_while(|r| r.props.header).count();
let head: f32 = tl.rows.iter().take(headers).map(|r| r.height).sum();
if headers > 0 && ctx.doc.settings.compat_mode < wordcraft_doc::COMPAT_MODE_CURRENT {
// With the border below the last of them, as `place_table` places them.
return head + tl.rows.get(headers - 1).map_or(0.0, |r| r.edge);
}
let (Some(row), Some(laid)) = (t.rows.get(headers), tl.rows.get(headers)) else { return head };
// ponytail: bisection assumes starting a row gets no harder with more room.
let (mut lo, mut hi) = (0.0f32, laid.height + laid.edge);
@@ -259,9 +265,11 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc
t.rows.get(ri).is_some_and(|r| r.props.height_rule == HeightRule::AtLeast && r.props.height.is_some_and(|h| h > room + 0.01))
};
// Like Word, repeated header rows don't stay alone at the bottom of a page: when the first row
// after them can't start under them there, the table starts on the next page.
// after them can't start under them there, the table starts on the next page. Before Word
// 2013 layout (compatibility mode 15) they do (measured in modes 12 and 14).
let first = header_rows.len();
if !header_rows.is_empty()
&& ctx.doc.settings.compat_mode >= wordcraft_doc::COMPAT_MODE_CURRENT
&& !pb.at_top()
&& let Some(row) = tl.rows.get(first)
{
@@ -288,13 +296,22 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc
.get(ri)
.is_some_and(|r| r.props.cant_split && !(r.props.height_rule == HeightRule::Exact && r.props.height.is_some_and(|h| h > 0.0)));
let mut rest: Option<table::RowLayout> = None;
// The row laid out again for where it lands, when a merge starting in it runs past the
// end of that page (its text is drawn with this row, so it can't be aligned below it).
let mut aligned: Option<table::RowLayout> = None;
let merge_rows = table::merge_rows_after(t, ri);
let merge_h: f32 = tl.rows.iter().skip(ri).take(merge_rows + 1).map(|r| r.height).sum();
// On a new page holding only the repeated header rows.
let mut fresh = false;
// Nothing but this table's header rows above it on a page it started at the top of.
let under_top_headers = ri == first && table_at_top;
// Each pass places the part of the row that fits, then breaks the page.
for _ in 0..1000 {
let cur = rest.as_ref().unwrap_or(row);
if rest.is_none() && merge_rows > 0 {
let room = (pb.bottom - pb.y).max(0.0);
aligned = (merge_h > room + 0.01).then(|| table::layout_table_row_in(ctx, t, &[block as u32], width, ri, room)).flatten();
}
let cur = rest.as_ref().or(aligned.as_ref()).unwrap_or(row);
// A fitting kept row follows the next row when that row cannot start below it.
// Move only the prefix's start; an oversized follower cannot separate its kept rows.
let defer_kept = pb.y + cur.height <= pb.bottom + 0.01
@@ -351,7 +368,7 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc
}
fresh = true;
}
let last = rest.as_ref().unwrap_or(row);
let last = rest.as_ref().or(aligned.as_ref()).unwrap_or(row);
place(pb, last);
table_notes(ctx, pb, &last.items);
}
+446
View File
@@ -9,6 +9,7 @@ mod balanced_tail;
mod bidi;
mod budget;
mod cell_floats;
mod combining_marks;
mod complex;
mod float_top;
mod grid;
@@ -26,6 +27,7 @@ mod styleref;
mod table_contact;
mod table_first_line;
mod textbox;
mod times_twin_fallback;
mod vertical;
const WRAP_TEST_FONT: &str = "Source Sans 3";
@@ -685,6 +687,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();
@@ -3259,6 +3298,145 @@ fn a_vertical_merge_lays_out_as_one_cell() {
assert_eq!((hit.2, hit.3), (0, 0));
}
#[test]
fn a_vertical_merge_aligns_its_text_with_the_first_page() {
crate::test_fonts();
use wordcraft_doc::props::{HeightRule, VAlign, VMerge};
let mut d = Document::new();
let mut t = Table::new(60, 2, 468.0);
for (i, row) in t.rows.iter_mut().enumerate() {
row.props.height = Some(40.0);
row.props.height_rule = HeightRule::Exact;
row.cells[1].blocks = vec![wordcraft_doc::para_block(Paragraph::with_text("row", Default::default()))];
row.cells[0].blocks = vec![wordcraft_doc::para_block(Paragraph::with_text(if i == 0 { "MERGED LABEL" } else { "" }, Default::default()))];
row.cells[0].props.vmerge = if i == 0 { VMerge::Restart } else { VMerge::Continue };
}
t.rows[0].cells[0].props.valign = Some(VAlign::Center);
d.insert_block(StoryRef::Body, &Path::top(0), wordcraft_doc::Block::Table(t)).unwrap();
let l = lay(&d);
let label = l.pages[0].items.iter().find_map(|item| match item {
Placed::Lines { path, para, l0, l1, y, .. } if path.0 == [0, 0, 0, 0] => Some((*y, para.lines[*l1 - 1].top + para.lines[*l1 - 1].height)),
_ => None,
});
assert!(label.is_some_and(|(y, _)| y >= l.pages[0].body.y && y <= l.pages[0].body.bottom()), "{label:?}, body {:?}", l.pages[0].body);
}
#[test]
fn a_vertical_merge_that_starts_on_a_later_page_is_aligned_within_its_rows() {
crate::test_fonts();
use wordcraft_doc::props::{HeightRule, VAlign, VMerge};
for direction in [TextDirection::Horizontal, TextDirection::Up] {
let mut d = Document::from_text("before");
let mut t = Table::new(40, 2, 468.0);
for (i, row) in t.rows.iter_mut().enumerate() {
row.props.height = Some(40.0);
row.props.height_rule = HeightRule::Exact;
row.cells[1].blocks = vec![wordcraft_doc::para_block(Paragraph::with_text("row", Default::default()))];
let merged = (20..25).contains(&i);
row.cells[0].blocks =
vec![wordcraft_doc::para_block(Paragraph::with_text(if i == 20 { "MERGED LABEL" } else { "" }, Default::default()))];
row.cells[0].props.vmerge = match i {
20 => VMerge::Restart,
21..=24 => VMerge::Continue,
_ => VMerge::None,
};
if merged {
row.cells[0].props.valign = Some(VAlign::Center);
row.cells[0].props.text_direction = direction;
}
}
d.insert_block(StoryRef::Body, &Path::top(1), wordcraft_doc::Block::Table(t)).unwrap();
let l = lay(&d);
let (page, rect) = l
.pages
.iter()
.enumerate()
.find_map(|(n, p)| {
p.items.iter().find_map(|item| match item {
Placed::Cell { rect, row: 20, cell: 0, .. } => Some((n, *rect)),
_ => None,
})
})
.unwrap();
assert!(page > 0, "the merge starts on a later page");
let item = l.pages[page].items.iter().find(|item| matches!(item, Placed::Lines { path, .. } if path.0 == [1, 20, 0, 0])).unwrap();
if direction.is_turned() {
let bounds = item.turned_bounds().unwrap();
assert!(bounds.y >= rect.y - 0.01 && bounds.bottom() <= rect.bottom() + 0.01, "{direction:?}: {bounds:?} in {rect:?}");
assert!(bounds.h > 20.0, "{direction:?}: the turned text runs along the merge: {bounds:?}");
} else {
let Placed::Lines { para, l0, l1, y, .. } = item else {
panic!("{item:?} is not text");
};
let bottom = para.lines[*l1 - 1].top + para.lines[*l1 - 1].height;
let height = para.lines[*l0].height;
let expected = rect.y + (rect.h - height) / 2.0;
assert!(*y >= rect.y - 0.01 && bottom <= rect.bottom() + 0.01, "{direction:?}: {y}..{bottom} in {rect:?}");
assert!((*y - expected).abs() < 1.0, "{direction:?}: centred at {y}, expected {expected}");
}
}
}
#[test]
fn a_vertical_merge_keeps_center_bottom_and_turned_text_in_first_page_body() {
crate::test_fonts();
use wordcraft_doc::props::{HeightRule, VAlign, VMerge};
for valign in [VAlign::Center, VAlign::Bottom] {
for direction in [TextDirection::Horizontal, TextDirection::Up] {
let mut d = Document::from_text("before");
let mut t = Table::new(60, 2, 468.0);
for (i, row) in t.rows.iter_mut().enumerate() {
row.props.height = Some(40.0);
row.props.height_rule = HeightRule::Exact;
row.cells[1].blocks = vec![wordcraft_doc::para_block(Paragraph::with_text("row", Default::default()))];
row.cells[0].blocks =
vec![wordcraft_doc::para_block(Paragraph::with_text(if i == 0 { "MERGED LABEL" } else { "" }, Default::default()))];
row.cells[0].props.vmerge = if i == 0 { VMerge::Restart } else { VMerge::Continue };
}
t.rows[0].cells[0].props.valign = Some(valign);
t.rows[0].cells[0].props.text_direction = direction;
d.insert_block(StoryRef::Body, &Path::top(1), wordcraft_doc::Block::Table(t)).unwrap();
let l = lay(&d);
let body = l.pages[0].body;
let restart_top = l.pages[0]
.items
.iter()
.find_map(|item| match item {
Placed::Cell { rect, row: 0, cell: 0, .. } => Some(rect.y),
_ => None,
})
.unwrap();
let item = l.pages[0].items.iter().find(|item| matches!(item, Placed::Lines { path, .. } if path.0 == [1, 0, 0, 0]));
assert!(
item.is_some(),
"{valign:?} {direction:?}: label is missing from the first page: {:?}",
l.pages[0]
.items
.iter()
.filter_map(|i| if let Placed::Lines { path, .. } = i { Some(path.0.clone()) } else { None })
.collect::<Vec<_>>()
);
if direction.is_turned() {
let bounds = item.and_then(Placed::turned_bounds).unwrap();
assert!(bounds.y >= restart_top && bounds.bottom() <= body.bottom(), "{valign:?} {direction:?}: {bounds:?}, body {body:?}");
} else {
let Some(Placed::Lines { para, l0, l1, y: top, .. }) = item else {
continue;
};
let bottom = para.lines[*l1 - 1].top + para.lines[*l1 - 1].height;
let height = para.lines[*l0].height;
assert!(*top >= body.y && bottom <= body.bottom(), "{valign:?} {direction:?}: {top}..{bottom}, body {body:?}");
let expected = match valign {
VAlign::Center => restart_top + (body.bottom() - restart_top - height) / 2.0,
VAlign::Bottom => body.bottom() - height,
VAlign::Top => restart_top,
};
assert!((*top - expected).abs() < 1.0, "{valign:?} {direction:?}: top {top}, expected {expected}, body {body:?}");
}
}
}
}
/// A 1×3 table after "before" whose middle cell holds `text` running `dir`.
fn turned_table(dir: TextDirection, text: &str, row: Option<f32>) -> Document {
let mut d = Document::from_text("before\nafter");
@@ -7212,6 +7390,40 @@ fn line_spacing_does_not_scale_pictures() {
assert!((line.baseline - line.top - 144.0).abs() < 0.01, "the picture stands on the baseline");
}
#[test]
fn a_picture_is_as_high_as_its_whole_twips_and_fits_by_them_at_the_page_bottom() {
// Word drops the EMUs past a whole twip: a picture 1 EMU short of a twip taller than the room
// left is 400pt high and stays, one 1.2tw taller is 400.05pt and moves on (Word for Mac and
// Windows: a 209.552pt picture is drawn 209.55pt high).
use wordcraft_doc::props::LineSpacing;
let room = 400.0;
let doc = |pic: f32| {
let mut d = Document::from_text("Text");
let s = d.last_section.clone();
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
p.props.line_spacing = Some(LineSpacing::Exactly(20.0));
p.props.space_before = Some(0.0);
p.props.space_after = Some(s.page_h - s.margin_bottom - s.margin_top - 20.0 - room);
let mut q = wordcraft_doc::Paragraph::with_text("", Default::default());
q.props.line_spacing = Some(LineSpacing::Multiple(1.0));
q.props.space_before = Some(0.0);
q.insert_object(0, picture(100.0, pic, Default::default()), &Default::default()).unwrap();
d.body.push(wordcraft_doc::para_block(q));
d
};
let first_line = |l: &DocLayout| {
l.pages[0].items.iter().find_map(|i| match i {
Placed::Lines { para, l0, .. } if para.lines[*l0].text_asc >= room - 1.0 => Some(para.lines[*l0].text_asc),
_ => None,
})
};
// 1 EMU short of a whole twip still drops the twip.
let l = lay(&doc(room + 0.05 - 1.0 / 12_700.0));
let Some(asc) = first_line(&l) else { panic!("a picture 1 EMU under 400.05pt should stay on page 1 ({} pages)", l.pages.len()) };
assert!((asc - room).abs() < 0.001, "the picture is {asc}pt high, want {room}");
assert!(first_line(&lay(&doc(room + 0.06))).is_none(), "a picture of 400.05pt should move on");
}
#[test]
fn multiple_line_spacing_adds_its_leading_below_the_text() {
crate::test_fonts();
@@ -9533,6 +9745,66 @@ fn no_line_break_right_after_a_slash() {
assert!(lines > 10, "{lines} lines");
}
#[test]
fn multiple_spacing_adds_a_multiple_of_the_tallest_run_not_of_the_mixed_line() {
// A line mixing fonts is taller than either font's own line; Word adds (m - 1) x the tallest
// run's own height to it, not (m - 1) x the line's (Word for Mac and Windows: 10pt Times New
// Roman with 10pt Courier New, 18.09pt at 1.5 spacing where 1.5 x the 12.34pt line gives 18.51).
let font = |(f, size): (&str, f32)| wordcraft_doc::CharProps { font: Some(f.into()), size: Some(size), ..Default::default() };
let height = |fonts: &[(&str, f32)], m: f32| {
let mut p = wordcraft_doc::Paragraph::with_text("run ", font(fonts[0]));
for &f in &fonts[1..] {
p.append(wordcraft_doc::Paragraph::with_text("run ", font(f)));
}
p.props = ParaProps { line_spacing: Some(wordcraft_doc::props::LineSpacing::Multiple(m)), ..Default::default() };
let mut d = Document::new();
d.body = vec![wordcraft_doc::para_block(p)];
let l = lay(&d);
l.pages[0].items.iter().find_map(|i| if let Placed::Lines { para, .. } = i { Some(para.lines[0].height) } else { None }).unwrap()
};
// The larger sans has the taller ascent, the serif the deeper descent.
let (sans, serif) = (("Inter", 12.0), ("Source Serif 4", 10.5));
let tallest = height(&[sans], 1.0).max(height(&[serif], 1.0));
let mixed = height(&[sans, serif], 1.0);
assert!(mixed > tallest + 0.1, "the fonts don't make a taller line together: {mixed} vs {tallest}");
for m in [1.5, 2.0] {
let got = height(&[sans, serif], m);
assert!((got - (mixed + (m - 1.0) * tallest)).abs() < 0.01, "{m}: {got}, line {mixed}, tallest run {tallest}");
}
}
#[test]
fn a_line_breaks_after_a_space_before_closing_punctuation() {
// UAX #14 (LB13) keeps a space with the ":", ")" or "," after it, so "status := 1" moved down
// whole with the word before it; Word breaks at the space and starts the next line with ":="
// (measured in Word for Mac and Windows: ":=", ";", ",", ")", "}", "!" all start a line).
let text: String =
(1..80).map(|i| format!("{} := 1; {} ); {} , ", "w".repeat(i % 9 + 1), "v".repeat(i % 7 + 1), "u".repeat(i % 5 + 1))).collect();
let lines = body_lines(&lay(&Document::from_text(&text)), &text);
assert!(lines.len() > 5, "{lines:?}");
assert!(lines.iter().any(|l| l.starts_with([':', ')', ','])), "no line starts with the punctuation: {lines:?}");
}
#[test]
fn a_line_breaks_after_a_space_before_closing_punctuation_but_not_before_a_word_joiner() {
// A word joiner (U+2060, U+FEFF) or a zero-width space (U+200B) after a space never starts a
// line (UAX #14 LB11, LB7), so no line may start with one.
for joiner in ['\u{2060}', '\u{FEFF}', '\u{200B}'] {
let text: String = (1..80).map(|i| format!("{} {joiner}{} ", "w".repeat(i % 9 + 1), "v".repeat(i % 7 + 1))).collect();
let lines = body_lines(&lay(&Document::from_text(&text)), &text);
assert!(lines.len() > 5, "{lines:?}");
assert!(!lines.iter().any(|l| l.starts_with(joiner)), "a line starts with U+{:04X}: {lines:?}", joiner as u32);
}
}
#[test]
fn a_line_breaks_after_the_space_of_an_opening_bracket() {
// UAX #14 (LB14) keeps "( " with the word after it; Word breaks after the space.
let text: String = (1..60).map(|i| format!("{} ( word ", "w".repeat(i % 9 + 1))).collect();
let lines = body_lines(&lay(&Document::from_text(&text)), &text);
assert!(lines.iter().any(|l| l.trim_end().ends_with('(')), "no line ends with the bracket: {lines:?}");
}
/// The text of every laid-out line.
fn body_lines(l: &DocLayout, text: &str) -> Vec<String> {
l.pages
@@ -18151,6 +18423,95 @@ fn a_caption_kept_with_a_table_counts_its_space_after() {
}
}
/// Before Word 2013 layout (compatibility mode 15, measured in Word for Mac in modes 12 and 14) a
/// row split across pages divides its cells' text at any line, the repeated header row may stay
/// alone at the foot of a page, and a caption kept with the table keeps with the header row only.
/// The caption's space before grows a point at a time under lines exactly 12 pt high, so it lands
/// at every offset from the foot of the page, whatever the font's metrics.
#[test]
fn before_word_2013_layout_a_kept_caption_goes_with_the_header_row_only() {
let (mut one_line, mut header_alone) = (false, false);
// 44 lines end 120 pt above the bottom margin.
let fill = 44;
for push in 0..120 {
let mut d = Document::from_text(&format!("{}Caption", "filler\n".repeat(fill)));
d.settings.compat_mode = wordcraft_doc::LEGACY_COMPAT_MODE;
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(fill - 1, 0), &|p| {
p.line_spacing = Some(wordcraft_doc::props::LineSpacing::Exactly(12.0));
p.space_before = Some(0.0);
p.space_after = Some(0.0);
})
.unwrap();
// (No space after the caption: the table starts right under it.)
d.format_paragraphs(&Pos::body(fill, 0), &Pos::body(fill, 0), &|p| {
p.keep_next = Some(true);
p.space_before = Some(push as f32);
p.space_after = Some(0.0);
})
.unwrap();
let mut t = Table::new(2, 1, 468.0);
t.rows[0].props.header = true;
t.rows[0].cells[0].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Header", Default::default()))];
t.rows[1].cells[0].blocks =
vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text(&"first row words go on and on ".repeat(60), Default::default()))];
d.insert_block(StoryRef::Body, &Path::top(fill + 1), wordcraft_doc::Block::Table(t)).unwrap();
let l = lay(&d);
let page = l
.pages
.iter()
.find(|p| p.items.iter().any(|it| matches!(it, Placed::Lines { story: StoryRef::Body, path, .. } if *path == Path::top(fill))))
.unwrap();
let rows: Vec<usize> = page.items.iter().filter_map(|it| if let Placed::Cell { row, .. } = it { Some(*row) } else { None }).collect();
let lines: usize = page
.items
.iter()
.filter_map(|it| match it {
Placed::Lines { path, l0, l1, .. } if path.0.len() > 1 && path.0.get(1) == Some(&1) => Some(l1 - l0),
_ => None,
})
.sum();
assert!(rows.contains(&0), "{push} pt before the caption: the caption is alone on its page");
one_line |= lines == 1;
header_alone |= !rows.contains(&1);
}
assert!(one_line && header_alone, "one line of the first row: {one_line}, the header row alone: {header_alone}");
}
/// Before Word 2013 layout a cell's text drops widow/orphan control whatever the table's style:
/// a table with no style at all (no `w:tblStyle`) is still a table.
#[test]
fn before_word_2013_layout_cells_of_a_table_without_a_style_drop_widow_control() {
for (mode, styled) in
[(wordcraft_doc::LEGACY_COMPAT_MODE, true), (wordcraft_doc::LEGACY_COMPAT_MODE, false), (wordcraft_doc::COMPAT_MODE_CURRENT, false)]
{
let mut d = Document::from_text("before");
d.settings.compat_mode = mode;
let mut t = Table::new(1, 1, 468.0);
if !styled {
t.props.style = None;
}
t.rows[0].cells[0].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("cell", Default::default()))];
d.insert_block(StoryRef::Body, &Path::top(1), wordcraft_doc::Block::Table(t)).unwrap();
let widow = cell_para(&lay(&d), 0, 0).rp.widow_control;
assert_eq!(widow, mode == wordcraft_doc::COMPAT_MODE_CURRENT, "compatibility mode {mode}, table style {styled}");
}
}
/// A layout cache reused after the compatibility mode changes lays the cells' paragraphs out
/// again: their widow control depends on the mode.
#[test]
fn a_reused_layout_cache_follows_a_change_of_compatibility_mode() {
let mut d = Document::from_text("before");
let mut t = Table::new(1, 1, 468.0);
t.rows[0].cells[0].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("cell", Default::default()))];
d.insert_block(StoryRef::Body, &Path::top(1), wordcraft_doc::Block::Table(t)).unwrap();
let mut cache = LayoutCache::new();
d.settings.compat_mode = wordcraft_doc::LEGACY_COMPAT_MODE;
assert!(!cell_para(&layout(&d, &mut cache, &LayoutOptions::default()), 0, 0).rp.widow_control);
d.settings.compat_mode = wordcraft_doc::COMPAT_MODE_CURRENT;
assert!(cell_para(&layout(&d, &mut cache, &LayoutOptions::default()), 0, 0).rp.widow_control);
}
/// A header paragraph beside a Square float on its last lines only: those lines are shorter than
/// the first. A click on the first line past the short last line's end is still on the header's
/// text, so a Behind Text picture under it is not grabbed there (#5601 review).
@@ -18317,3 +18678,88 @@ fn a_decimal_tab_by_the_margin_still_wraps_its_number() {
let (first, end) = (l.caret(&Pos::body(0, 0)).unwrap(), l.caret(&Pos::body(0, n)).unwrap());
assert!(end.top > first.top, "the number stays on the first line and ends at {}", end.x);
}
/// Page-anchored body text frames use page coordinates; other anchors remain in body flow.
#[test]
fn a_body_text_frame_respects_its_anchors() {
crate::test_fonts();
use wordcraft_doc::props::TextFrame;
let mut d = Document::new();
for i in 0..5 {
d.insert_block(
StoryRef::Body,
&Path::top(i),
(*wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Body line", Default::default()))).clone(),
)
.unwrap();
}
let mut framed = wordcraft_doc::Paragraph::with_text("Framed line", Default::default());
framed.props.frame = Some(TextFrame {
w: Some(150.0),
x: 340.0,
y: 180.0,
h_anchor: "page".into(),
v_anchor: "page".into(),
wrap: "notBeside".into(),
..Default::default()
});
d.insert_block(StoryRef::Body, &Path::top(5), (*wordcraft_doc::para_block(framed)).clone()).unwrap();
let l = lay(&d);
let at = l.caret(&Pos { story: StoryRef::Body, path: Path::top(5), off: 0 }).unwrap();
assert!((at.x - 340.0).abs() < 0.5, "page-anchored frame x: {}", at.x);
assert!((at.top - 180.0).abs() < 0.5, "page-anchored frame y: {}", at.top);
let mut flowing = wordcraft_doc::Paragraph::with_text("Margin-anchored line", Default::default());
flowing.props.frame =
Some(TextFrame { w: Some(150.0), h_anchor: "margin".into(), v_anchor: "page".into(), wrap: "notBeside".into(), ..Default::default() });
d.insert_block(StoryRef::Body, &Path::top(6), (*wordcraft_doc::para_block(flowing)).clone()).unwrap();
let l = lay(&d);
let at = l.caret(&Pos { story: StoryRef::Body, path: Path::top(6), off: 0 }).unwrap();
assert!((at.x - 72.0).abs() < 0.5, "margin-anchored frame x: {}", at.x);
assert!(at.top > 180.0, "margin-anchored frame should remain in body flow: {}", at.top);
}
#[test]
fn env_hash_memoizes_styles_and_invalidates_on_change() {
let mut d = Document::new();
let mut cache = LayoutCache::new();
let opts = LayoutOptions::default();
let h0 = crate::cache::env_hash(&d, &mut cache, &opts);
assert_eq!(h0, crate::cache::env_hash(&d, &mut cache, &opts));
Arc::make_mut(&mut d.styles).default_para.space_after = Some(12.0);
let h1 = crate::cache::env_hash(&d, &mut cache, &opts);
assert_ne!(h1, h0, "modifying stylesheet must invalidate env hash");
assert_eq!(h1, crate::cache::env_hash(&d, &mut cache, &opts));
Arc::make_mut(&mut d.numbering).abstracts.push(Default::default());
let h2 = crate::cache::env_hash(&d, &mut cache, &opts);
assert_ne!(h2, h1, "modifying numbering must invalidate env hash");
d.settings.default_tab = 54.0;
let h3 = crate::cache::env_hash(&d, &mut cache, &opts);
assert_ne!(h3, h2, "modifying default tab must invalidate env hash");
d.settings.footnote_format = wordcraft_doc::section::NumFormat::LowerRoman;
let h4 = crate::cache::env_hash(&d, &mut cache, &opts);
assert_ne!(h4, h3, "modifying footnote format must invalidate env hash");
cache.clear();
assert_eq!(h4, crate::cache::env_hash(&d, &mut cache, &opts), "recomputing after clear matches");
}
#[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());
}
}
+21 -9
View File
@@ -151,22 +151,34 @@ fn a_field_result_is_classed_by_the_text_it_shows() {
}
#[test]
fn a_character_grid_the_paragraph_snaps_to_turns_it_off() {
fn a_snap_to_chars_grid_the_paragraph_snaps_to_turns_it_off() {
crate::test_fonts();
let with = |kind: DocGridType, snap: bool| {
let mut d = Document::from_text("法院94年");
d.last_section.doc_grid = Some(DocGrid { kind, line_pitch: 18.0, char_space: 0 });
para0(&mut d).props.snap_to_grid = Some(snap);
d
};
let d = with(DocGridType::LinesAndChars, true);
let d = with_grid(DocGridType::SnapToChars, true);
assert!(gaps(&d).iter().all(|g| *g == 0.0), "{:?}", gaps(&d));
// A line grid alone, or a paragraph that doesn't snap, keeps it.
for d in [with(DocGridType::Lines, true), with(DocGridType::LinesAndChars, false)] {
for d in [with_grid(DocGridType::Lines, true), with_grid(DocGridType::SnapToChars, false)] {
assert_eq!(gaps(&d), [0.0, quarter(&d), 0.0, after(&d, 7), 0.0]);
}
}
/// Measured in Word (#6584): on a `linesAndChars` grid every character stands where it does on a
/// line grid, the automatic space included. Only `snapToChars` drops it.
#[test]
fn a_lines_and_chars_grid_keeps_it() {
crate::test_fonts();
for snap in [true, false] {
let d = with_grid(DocGridType::LinesAndChars, snap);
assert_eq!(gaps(&d), [0.0, quarter(&d), 0.0, after(&d, 7), 0.0], "snap_to_grid {snap}");
}
}
fn with_grid(kind: DocGridType, snap: bool) -> Document {
let mut d = Document::from_text("法院94年");
d.last_section.doc_grid = Some(DocGrid { kind, line_pitch: 18.0, char_space: 0 });
para0(&mut d).props.snap_to_grid = Some(snap);
d
}
#[test]
fn the_space_takes_no_room_at_the_end_of_a_justified_line() {
crate::test_fonts();
+6 -4
View File
@@ -564,7 +564,8 @@ fn inline_picture_in_rtl_text_sits_in_its_place() {
/// A right-to-left table (`w:bidiVisual`, #362): the first logical column stands at the right
/// edge, the table is start-aligned against the right margin, and each cell's start (left)
/// margin and border are drawn on its right. Clicks find cells by where they are drawn.
/// border is drawn on its right. Its left margin stays on its left, as Word for Windows lays it
/// out (`w:left` and `w:start` alike). Clicks find cells by where they are drawn.
#[test]
fn rtl_table_lays_its_columns_out_right_to_left() {
crate::test_fonts();
@@ -573,7 +574,7 @@ fn rtl_table_lays_its_columns_out_right_to_left() {
let mut d = Document::from_text("before\nafter");
let mut t = Table::new(1, 3, 300.0);
t.props.bidi_visual = true;
// Start margin 10pt, end margin 2pt.
// Left margin 10pt, right margin 2pt.
t.props.cell_margins = Some([0.0, 10.0, 0.0, 2.0]);
for (i, c) in t.rows[0].cells.iter_mut().enumerate() {
c.blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text(&format!("c{i}"), Default::default()))];
@@ -592,10 +593,11 @@ fn rtl_table_lays_its_columns_out_right_to_left() {
assert!(c0.x > c1.x && c1.x > c2.x, "{c0:?} {c1:?} {c2:?}");
assert!((c1.right() - c0.x).abs() < 0.01 && (c2.right() - c1.x).abs() < 0.01);
assert!((c2.x - (right - 300.0)).abs() < 2.0, "{c2:?}");
// The first cell's text sits its end margin (2pt) in from the cell's left edge.
// The first cell's text sits its left margin (10pt) in from the cell's left edge, not its
// right margin (2pt): Word doesn't mirror the margins (measured in Word for Windows).
let text_x =
items.iter().find_map(|i| if let Placed::Lines { path, x, .. } = i { (path.0 == [1, 0, 0, 0]).then_some(*x) } else { None }).unwrap();
assert!((text_x - (c0.x + 2.0)).abs() < 0.5, "text at {text_x}, cell {c0:?}");
assert!((text_x - (c0.x + 10.0)).abs() < 0.5, "text at {text_x}, cell {c0:?}");
// The thick start border is drawn on the cell's right edge.
let thick: Vec<f32> = items
.iter()
+154
View File
@@ -0,0 +1,154 @@
//! A combining mark the face of its character can't draw (#7865): the character and its marks are
//! drawn together in a face that has them all (CSS Fonts 4 §5.3, cluster matching), and with no
//! such face the mark on its own from a face that has it, except in right-to-left and
//! complex-script text, where it stays with its letter. Marks the face draws and pairs it composes
//! stay with their character. Fixed test fonts: Source Serif 4 lacks U+0336 and U+0338; Source
//! Sans 3 has U+0338; only JetBrains Mono has U+0336.
use std::sync::Arc;
use wordcraft_doc::{CharProps, Document, Paragraph, para_block};
use wordcraft_fonts::{FaceRef, FontDb};
use super::lay;
use super::linear::assert_linear_steps;
use crate::display::DisplayOptions;
use crate::{ParaLayout, Placed};
const SERIF: &str = "Source Serif 4";
fn serif() -> FaceRef {
crate::test_fonts();
let face = wordcraft_fonts::word::resolve(SERIF, false, false).face;
assert_eq!(face.family, SERIF, "the fixed test fonts include {SERIF}");
face
}
/// A document of one paragraph, `text` set in Source Serif 4; `cs`: with complex-script
/// formatting (`w:cs`), its complex-script font Source Serif 4 too.
fn doc(text: &str, cs: bool) -> Document {
let chr = CharProps { font: Some(SERIF.into()), font_cs: Some(SERIF.into()), cs: Some(cs), size: Some(12.0), ..Default::default() };
let mut d = Document::new();
d.body = vec![para_block(Paragraph::with_text(text, chr))];
d
}
/// [`doc`] laid out: its paragraph and the characters drawn as missing glyphs.
fn laid(text: &str, cs: bool) -> (Arc<ParaLayout>, Vec<char>) {
laid_doc(&doc(text, cs))
}
/// `d`, a document of one paragraph, laid out: the paragraph and the characters drawn as missing
/// glyphs.
fn laid_doc(d: &Document) -> (Arc<ParaLayout>, Vec<char>) {
crate::test_fonts();
let l = lay(d);
let missing = l.missing_glyphs(d, &DisplayOptions::default(), None).chars.iter().map(|(c, _)| *c).collect();
let para = l
.pages
.iter()
.flat_map(|p| &p.items)
.find_map(|it| match it {
Placed::Lines { para, .. } => Some(para.clone()),
_ => None,
})
.expect("the paragraph is laid out");
(para, missing)
}
/// The face that draws the character at byte `at` of the paragraph.
fn face_at(para: &ParaLayout, at: usize) -> FaceRef {
let c = para.clusters.iter().find(|c| c.start <= at && at < c.end).expect("a cluster holds the character");
para.styles[c.style as usize].face
}
#[test]
fn a_mark_its_letters_font_lacks_goes_with_its_letter_to_a_face_that_has_both() {
let serif = serif();
let (letter, mark) = ('∞', '\u{338}');
assert!(serif.covers(letter) && !serif.covers(mark), "{SERIF} has {letter} and lacks U+0338");
let text = format!("x {letter}{mark} y");
let (para, missing) = laid(&text, false);
assert!(missing.is_empty(), "nothing is drawn as a missing glyph, but {missing:?} were");
let at = text.find(letter).expect("the letter is in the text");
let face = face_at(&para, at);
assert_eq!(face.id(), face_at(&para, at + letter.len_utf8()).id(), "the letter and its mark are drawn in one face");
assert!(face.covers(letter) && face.covers(mark), "that face has both");
assert_eq!(face_at(&para, 0).id(), serif.id(), "the text before stays in the run's font");
assert_eq!(face_at(&para, text.len() - 1).id(), serif.id(), "the text after goes back to the run's font");
}
/// In small capitals a mark is set at the size of the lower-case letter it belongs to, so the
/// letter and its marks still go together to a face that has them all, also when the run's font has
/// the first mark and lacks the second.
#[test]
fn in_small_capitals_a_letter_and_its_marks_go_together_to_a_face_that_has_them_all() {
let serif = serif();
let (letter, has, lacks) = ('x', '\u{301}', '\u{336}');
assert!(serif.covers(letter) && serif.covers(has) && !serif.covers(lacks), "{SERIF} has x and U+0301 and lacks U+0336");
let text: String = [letter, has, lacks].iter().collect();
let chr = CharProps { font: Some(SERIF.into()), size: Some(12.0), small_caps: Some(true), ..Default::default() };
let mut d = Document::new();
d.body = vec![para_block(Paragraph::with_text(&text, chr))];
let (para, missing) = laid_doc(&d);
assert!(missing.is_empty(), "nothing is drawn as a missing glyph, but {missing:?} were");
let style_at = |at: usize| para.clusters.iter().find(|c| c.start <= at && at < c.end).expect("a cluster holds the character").style;
let face = face_at(&para, 0);
assert!(face.covers(lacks), "the letter is drawn in a face that has U+0336");
for (at, c) in text.char_indices().skip(1) {
assert_eq!(face_at(&para, at).id(), face.id(), "U+{:04X} is drawn in its letter's face", c as u32);
assert_eq!(style_at(at), style_at(0), "U+{:04X} is set at its letter's size", c as u32);
}
}
#[test]
fn a_mark_the_font_composes_with_its_letter_stays_in_the_run_font() {
let serif = serif();
// The font has no U+0338, but the shaper draws = with it as ≠, which the font has.
assert!(!serif.covers('\u{338}') && serif.covers('≠'), "{SERIF} lacks U+0338 and has ≠");
let text = "x =\u{338} y";
let (para, missing) = laid(text, false);
assert!(missing.is_empty(), "nothing is drawn as a missing glyph, but {missing:?} were");
for (at, c) in text.char_indices() {
assert_eq!(face_at(&para, at).id(), serif.id(), "U+{:04X} stays in the run's font", c as u32);
}
}
#[test]
fn a_mark_no_face_draws_with_its_letter_is_drawn_from_a_face_that_has_it() {
let serif = serif();
let (letter, mark) = ('ǹ', '\u{336}');
let db = FontDb::global();
assert!(serif.covers(letter) && !serif.covers(mark), "{SERIF} has {letter} and lacks U+0336");
assert!(db.fallback_for_run(&[letter, mark], serif.id(), false, false).is_none(), "no face has both");
assert!(db.fallback_for(mark, serif.id()).is_some(), "a face has U+0336");
let text = format!("{letter}{mark}");
let (para, missing) = laid(&text, false);
assert!(missing.is_empty(), "the mark is drawn, but {missing:?} were missing glyphs");
assert_eq!(face_at(&para, 0).id(), serif.id(), "the letter stays in the run's font");
assert!(face_at(&para, letter.len_utf8()).covers(mark), "the mark comes from a face that has it");
}
/// In complex-script text a mark no face draws with its letter stays in the letter's face, so it is
/// never split from its letter (Arabic harakat would lose their place on it).
#[test]
fn in_complex_script_text_a_mark_no_face_draws_with_its_letter_stays_with_it() {
let serif = serif();
let (letter, mark) = ('ǹ', '\u{336}');
assert!(FontDb::global().fallback_for_run(&[letter, mark], serif.id(), false, false).is_none(), "no face has both");
let (para, _) = laid(&format!("{letter}{mark}"), true);
assert_eq!(face_at(&para, 0).id(), serif.id(), "the letter stays in the run's font");
assert_eq!(face_at(&para, letter.len_utf8()).id(), serif.id(), "the mark stays with its letter");
}
/// A letter followed by many marks no face draws with it, in complex-script text, where they stay
/// with it: their cluster is matched once, not again at every mark, which made the layout quadratic
/// in their number.
#[test]
fn a_long_run_of_marks_after_one_letter_lays_out_in_linear_time() {
let serif = serif();
let (letter, mark) = ('ǹ', '\u{336}');
assert!(FontDb::global().fallback_for_run(&[letter, mark], serif.id(), false, false).is_none(), "no face has both");
let text = |n: usize| std::iter::once(letter).chain(std::iter::repeat_n(mark, n)).collect::<String>();
assert_linear_steps("marks after one letter", 200, |n| doc(&text(n), true), |d| drop(std::hint::black_box(lay(d))));
}
+5 -2
View File
@@ -82,12 +82,15 @@ fn character_grid_places_east_asian_text_on_the_pitch() {
let (g, p) = (first(&l), first(&plain));
let line = &g.lines[0];
let latin = text.find('a').unwrap();
let last_asian = text[..latin].char_indices().last().unwrap().0;
for (k, c) in g.clusters.iter().enumerate() {
let x = line.xs[k] - line.xs[0];
if c.start < latin {
// Ideographs and kana sit on the pitch, one cell each.
// Ideographs and kana sit on the pitch, one cell each; the last one before the Latin
// text keeps the automatic space after it, as on a line grid (#6584).
assert!((x - pitch * k as f32).abs() < 0.01, "cluster {k} at {x}, pitch {pitch}");
assert!((c.adv - pitch).abs() < 0.01);
let auto_space = if c.start == last_asian { size / 4.0 } else { 0.0 };
assert!((c.adv - pitch - auto_space).abs() < 0.01, "cluster {k} advances {}", c.adv);
} else {
// Latin text keeps its own advances.
assert!((c.adv - p.clusters[k].adv).abs() < 0.01, "latin cluster {k}");
+14
View File
@@ -89,6 +89,20 @@ fn a_joined_paragraphs_drawings_are_relative_to_the_shared_line() {
assert!(boxed < alpha + 12.0, "the box's text at {boxed} is below the shared line at {alpha}");
}
#[test]
fn a_margin_anchored_frame_in_a_cell_joins_after_a_hidden_mark() {
let mut d = Document::from_text("Alpha\nOmega");
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().mark.hidden = Some(true);
d.para_mut(StoryRef::Body, &Path::top(1)).unwrap().props.frame =
Some(TextFrame { h_anchor: "page".into(), v_anchor: "margin".into(), ..Default::default() });
in_cell(&mut d);
let l = lay(&d);
let alpha = top_of(&l, &Path(vec![0, 0, 0, 0]));
let omega = top_of(&l, &Path(vec![0, 0, 0, 1]));
assert!((omega - alpha).abs() < 1.0, "framed paragraph should share hidden-mark line: {alpha} vs {omega}");
}
#[test]
fn a_text_frame_after_a_hidden_mark_is_not_joined() {
// A framed paragraph is placed apart, so it shares no line with the one before: its number is
+64
View File
@@ -874,6 +874,70 @@ fn a_roman_page_number_in_the_footer_stays_roman_with_the_page_count_in_the_body
}
}
#[test]
fn a_multiple_spaced_lines_leading_may_run_past_a_footer_above_the_margin() {
// A footer reaching above the bottom margin: Word lets the leading of the page's last
// 1.5-spaced line run past its top as into the margin, only the text has to fit, whatever the
// footer holds. Word for Mac and Windows, a 1.5-spaced 12pt line pushed down by half a point:
// it stays while its text ends above the footer (up to 0.4pt above), with a one-line
// page-number footer above the margin by 6.6pt and by 28pt, with a four-line footer, and with
// an empty exact-height 120pt paragraph. Also when the footer is the first page's own (a title
// page footer, the other pages' footer short): the first page's footer counts there.
use wordcraft_doc::props::LineSpacing;
// (footer lines, their text, the title page's own footer, footer distance from the page bottom)
let cases: [(usize, &str, bool, Option<f32>); 4] =
[(1, "", false, None), (1, "", true, None), (1, "7", false, Some(72.0)), (4, "Footer line", false, None)];
for (lines, text, first, from_bottom) in cases {
let mut past_footer = 0;
for shift in (0..28).step_by(2) {
let mut d = Document::from_text(&"Several words wrap onto many lines of a long paragraph. ".repeat(60));
if let Some(wordcraft_doc::Block::Para(p)) = d.body.get_mut(0).map(Arc::make_mut) {
p.props.line_spacing = Some(LineSpacing::Multiple(1.5));
p.props.space_before = Some(shift as f32);
p.props.widow_control = Some(false);
}
let foot_paras = (0..lines)
.map(|_| {
let mut f = Paragraph::with_text(text, Default::default());
if text.is_empty() {
f.props.line_spacing = Some(LineSpacing::Exactly(120.0));
}
para_block(f)
})
.collect();
let id = d.add_part(PartKind::Footer, foot_paras);
if let Some(f) = from_bottom {
d.last_section.footer = f;
}
if first {
d.last_section.title_page = true;
d.last_section.footers.first = Some(id);
} else {
d.last_section.footers.default = Some(id);
}
let l = lay(&d);
let foot = l.pages[0].body.bottom();
let what = format!("footer of {lines} x {text:?}, shift {shift}");
assert!(foot < d.last_section.page_h - d.last_section.margin_bottom - 1.0, "{what}: the footer reaches above the margin: {foot}");
let Some(Placed::Lines { y, para, l0, l1, .. }) =
l.pages[0].items.iter().find(|i| matches!(i, Placed::Lines { story: StoryRef::Body, .. }))
else {
panic!("{what}: no body lines on page 1")
};
let (first, last, next) = (&para.lines[*l0], &para.lines[*l1 - 1], &para.lines[*l1]);
let top = y + last.top - first.top;
let text_end = top + (last.baseline - last.top) + last.text_desc;
assert!(text_end <= foot + 0.01, "{what}: the last line's text ends at {text_end}, below the footer at {foot}");
let next_text_end = top + last.height + (next.baseline - next.top) + next.text_desc;
assert!(next_text_end > foot + 0.01, "{what}: the next line's text would end at {next_text_end}, above the footer at {foot}");
if top + last.height > foot + 0.01 {
past_footer += 1;
}
}
assert!(past_footer > 0, "footer of {lines} x {text:?}: some shift should leave the last line's leading past the footer");
}
}
#[test]
fn a_page_ends_when_a_multiple_spaced_lines_text_no_longer_fits() {
// Multiple spacing puts its extra leading below the text, and Word lets that leading of a
@@ -0,0 +1,52 @@
//! A character Times New Roman's metric twin lacks ("‒", "₽" in Liberation Serif) is drawn from
//! a fallback face, but the line is as tall as the twin's: Times New Roman has those characters,
//! so Word's line is as tall as Times New Roman's, not the taller UI sans.
use crate::{Document, LayoutCache, LayoutOptions, Placed, layout};
/// Inter under the family name "Tinos" (a metric twin of Times New Roman), from the bundled font
/// so the test needs no installed font. Inter lacks "☐"; Source Sans 3 (the fallback) has it and
/// its line is taller (1.326 em against 1.21).
fn fake_tinos() -> &'static str {
const FAMILY: &str = "Tinos";
let inter = wordcraft_fonts::word::resolve("Inter", false, false).face;
assert!(!inter.covers('☐'));
let mut data = inter.data().to_vec();
let u16_at = |d: &[u8], o: usize| u16::from_be_bytes([d[o], d[o + 1]]) as usize;
let u32_at = |d: &[u8], o: usize| u32::from_be_bytes([d[o], d[o + 1], d[o + 2], d[o + 3]]) as usize;
let (name, len) = (0..u16_at(&data, 4))
.map(|i| 12 + 16 * i)
.find(|&r| &data[r..r + 4] == b"name")
.map(|r| (u32_at(&data, r + 8), u32_at(&data, r + 12)))
.unwrap();
let wide = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::<Vec<u8>>();
for (from, to) in [(wide("Inter"), wide(FAMILY)), (b"Inter".to_vec(), FAMILY.as_bytes().to_vec())] {
for i in name..name + len - from.len() {
if data[i..i + from.len()] == from[..] {
data[i..i + from.len()].copy_from_slice(&to);
}
}
}
wordcraft_fonts::FontDb::global().add_font(data);
FAMILY
}
fn line_height(text: &str, font: &str) -> f32 {
let chr = wordcraft_doc::CharProps { font: Some(font.into()), size: Some(14.0), ..Default::default() };
let mut d = Document::new();
d.body = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text(text, chr))];
let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default());
l.pages.iter().flat_map(|p| &p.items).find_map(|it| if let Placed::Lines { para, .. } = it { Some(para.lines[0].height) } else { None }).unwrap()
}
#[test]
fn a_twin_fallback_keeps_the_twins_line_height() {
crate::test_fonts();
let tinos = fake_tinos();
assert_eq!(wordcraft_fonts::word::resolve(tinos, false, false).face.family, tinos, "the test font is installed under its own name");
let plain = line_height("Aa", tinos);
let boxed = line_height("A☐a", tinos);
assert!((boxed - plain).abs() < 0.01, "a line with a fallback character is {boxed} pt, without it {plain} pt");
// Other fonts keep the fallback's taller line.
assert!(line_height("A☐a", "Inter") > line_height("Aa", "Inter") + 1.0);
}
+26 -12
View File
@@ -1,6 +1,5 @@
//! Decoded-media cache: hits need the same allocation, and the byte budget bounds what is kept.
use std::collections::HashMap;
use std::sync::Arc;
use wordcraft_doc::Document;
@@ -11,7 +10,7 @@ use super::{CACHE_BYTES, MediaCache, RenderOptions, render_items, wave_path};
#[test]
fn media_cache_only_hits_the_same_allocation() {
let mut c: MediaCache<u32> = MediaCache { map: HashMap::new(), bytes: 0 };
let mut c: MediaCache<u32> = MediaCache::default();
let a = Arc::new(vec![1u8, 2, 3]);
let b = Arc::new(vec![1u8, 2, 3]);
c.insert("pic", &a, 7, 3);
@@ -22,22 +21,26 @@ fn media_cache_only_hits_the_same_allocation() {
}
#[test]
fn media_cache_is_bounded_by_bytes() {
let mut c: MediaCache<u32> = MediaCache { map: HashMap::new(), bytes: 0 };
fn media_cache_is_bounded_by_bytes_and_evicts_lru() {
let mut c: MediaCache<u32> = MediaCache::default();
let src = Arc::new(vec![0u8]);
let big = CACHE_BYTES / 2 + 1;
c.insert("a", &src, 1, big);
c.insert("b", &src, 2, big);
assert_eq!(c.get("a", &src), None, "the first entry is evicted to make room");
assert_eq!(c.get("b", &src), Some(2));
let third = CACHE_BYTES / 3;
c.insert("a", &src, 1, third);
c.insert("b", &src, 2, third);
// Touch "a" so "b" becomes the least recently used entry.
assert_eq!(c.get("a", &src), Some(1));
c.insert("c", &src, 3, CACHE_BYTES / 2);
assert_eq!(c.get("a", &src), Some(1), "recently used entry stays cached");
assert_eq!(c.get("b", &src), None, "least recently used entry is evicted to make room");
assert_eq!(c.get("c", &src), Some(3));
assert!(c.bytes <= CACHE_BYTES);
c.insert("huge", &src, 3, CACHE_BYTES + 1);
c.insert("huge", &src, 4, CACHE_BYTES + 1);
assert_eq!(c.get("huge", &src), None, "a value over the whole budget is not kept");
}
#[test]
fn media_cache_counts_what_it_keeps_and_lets_sources_go() {
let mut c: MediaCache<Option<u32>> = MediaCache { map: HashMap::new(), bytes: 0 };
fn media_cache_prunes_dropped_sources_and_lets_sources_go() {
let mut c: MediaCache<Option<u32>> = MediaCache::default();
let src = Arc::new(vec![0u8; 1000]);
c.insert("broken", &src, None, 0);
c.insert("pic", &src, Some(1), 24);
@@ -49,6 +52,17 @@ fn media_cache_counts_what_it_keeps_and_lets_sources_go() {
c.insert("huge", &huge, None, 0);
assert_eq!(c.get("huge", &huge), Some(None));
assert_eq!(CACHE_BYTES * 2, 256 * 1024 * 1024, "the image and vector caches share about 256 MB");
let live = Arc::new(vec![1u8]);
let dead = Arc::new(vec![2u8]);
let half = CACHE_BYTES / 2 + 1;
c.insert("live", &live, Some(2), half);
c.insert("dead", &dead, Some(3), half / 2);
drop(dead);
// Inserting another half-budget entry prunes the dropped source without evicting "live".
c.insert("live2", &live, Some(4), half / 2);
assert_eq!(c.get("live", &live), Some(Some(2)), "live entry kept when dropped source is reclaimed");
assert_eq!(c.get("live2", &live), Some(Some(4)));
}
/// A wave stroke starting around 1e20 never advanced (`x + step == x`), pushing curves until memory ran out.
+41 -11
View File
@@ -4,7 +4,7 @@
//! and turns it into vello fills. The colours come from the font: a dark page doesn't invert them,
//! the same as pictures. Only the font's "text colour" entries follow the run's colour.
use std::collections::HashMap;
use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex};
use vello_cpu::kurbo::{self, Affine, Point, Rect, Shape};
@@ -29,15 +29,17 @@ impl Drawable {
}
}
/// Upper bounds on the colour-glyph cache: entries and approximate bytes. Past either it starts over.
/// Upper bounds on the colour-glyph cache: entries and approximate bytes. Evicts oldest entries
/// incrementally past either cap.
const CACHE_ENTRIES: usize = 4096;
const CACHE_BYTES: usize = 64 * 1024 * 1024;
const CACHE_BYTES: usize = 32 * 1024 * 1024;
type Key = (u32, u32, u32);
#[derive(Default)]
struct Cache {
map: HashMap<Key, Option<Arc<Drawable>>>,
map: HashMap<Key, (Option<Arc<Drawable>>, usize)>,
order: VecDeque<Key>,
bytes: usize,
}
@@ -62,23 +64,40 @@ pub(crate) fn drawable(face: &FontFace, gid: u32, ppem: f64, cached: bool) -> Op
return build(face, gid, bucket).map(Arc::new);
}
let key = (face.id(), gid, bucket);
if let Some(v) = crate::lock(cache()).map.get(&key) {
if let Some((v, _)) = crate::lock(cache()).map.get(&key) {
return v.clone();
}
let d = build(face, gid, bucket).map(Arc::new);
let size = d.as_ref().map_or(0, |d| d.bytes()).saturating_add(64);
let mut c = crate::lock(cache());
if c.map.len() >= CACHE_ENTRIES || c.bytes.saturating_add(size) > CACHE_BYTES {
c.map.clear();
c.bytes = 0;
}
if size <= CACHE_BYTES {
c.map.insert(key, d.clone());
c.bytes = c.bytes.saturating_add(size);
c.insert(key, d.clone(), size);
}
d
}
impl Cache {
fn insert(&mut self, key: Key, val: Option<Arc<Drawable>>, size: usize) {
if let Some((_, old_size)) = self.map.remove(&key) {
self.bytes = self.bytes.saturating_sub(old_size);
}
while self.map.len() >= CACHE_ENTRIES || self.bytes.saturating_add(size) > CACHE_BYTES {
let Some(oldest) = self.order.pop_front() else {
break;
};
if let Some((_, old_size)) = self.map.remove(&oldest) {
self.bytes = self.bytes.saturating_sub(old_size);
}
}
if self.map.capacity() > self.map.len().saturating_mul(4).max(64) {
self.map.shrink_to(self.map.len().saturating_mul(2).max(32));
}
self.order.push_back(key);
self.map.insert(key, (val, size));
self.bytes = self.bytes.saturating_add(size);
}
}
fn build(face: &FontFace, gid: u32, ppem: u32) -> Option<Drawable> {
match face.color_glyph(gid, ppem as f32)? {
ColorGlyph::Layers(ops) => Some(Drawable::Layers(ops)),
@@ -438,4 +457,15 @@ mod tests {
assert_eq!((p.width, p.height), (4, 4), "a plain glyph reads");
assert_eq!(decode_png(&png(1, 1), 1, 1).map(|p| (p.width(), p.height())), Some((1, 1)));
}
#[test]
fn color_glyph_cache_evicts_oldest_within_byte_budget() {
let mut c = Cache::default();
let entry = CACHE_BYTES / 2 + 1;
c.insert((1, 1, 16), None, entry);
c.insert((1, 2, 16), None, entry);
assert!(!c.map.contains_key(&(1, 1, 16)), "oldest entry evicted to stay under budget");
assert!(c.map.contains_key(&(1, 2, 16)), "newest entry retained");
assert!(c.bytes <= CACHE_BYTES);
}
}
+195 -29
View File
@@ -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);
}
}
}
+56 -10
View File
@@ -17,22 +17,56 @@ const CACHE_ENTRIES: usize = 256;
pub(crate) struct MediaCache<T> {
pub(crate) map: HashMap<String, Entry<T>>,
pub(crate) bytes: usize,
clock: u64,
}
impl<T> Default for MediaCache<T> {
fn default() -> Self {
Self { map: HashMap::new(), bytes: 0, clock: 0 }
}
}
pub(crate) struct Entry<T> {
src: Weak<Vec<u8>>,
val: T,
size: usize,
stamp: u64,
}
impl<T: Clone> MediaCache<T> {
pub(crate) fn get(&self, key: &str, src: &Arc<Vec<u8>>) -> Option<T> {
let e = self.map.get(key)?;
std::ptr::eq(e.src.as_ptr(), Arc::as_ptr(src)).then(|| e.val.clone())
pub(crate) fn get(&mut self, key: &str, src: &Arc<Vec<u8>>) -> Option<T> {
let hit = self.map.get(key).is_some_and(|e| std::ptr::eq(e.src.as_ptr(), Arc::as_ptr(src)));
if hit {
self.clock = self.clock.wrapping_add(1);
let stamp = self.clock;
if let Some(e) = self.map.get_mut(key) {
e.stamp = stamp;
return Some(e.val.clone());
}
}
// Reclaim dead entry immediately if its source document/allocation is gone.
if self.map.get(key).is_some_and(|e| e.src.strong_count() == 0)
&& let Some(dead) = self.map.remove(key)
{
self.bytes = self.bytes.saturating_sub(dead.size);
}
None
}
/// Stores `val` (about `size` bytes) for `src`. Clears the cache first when the budget or entry
/// cap is hit; an entry larger than the whole budget is not kept.
/// Reclaims decoded media whose source allocations have already been dropped.
fn prune_dead(&mut self) {
let bytes = &mut self.bytes;
self.map.retain(|_, e| {
let alive = e.src.strong_count() > 0;
if !alive {
*bytes = bytes.saturating_sub(e.size);
}
alive
});
}
/// Stores `val` (about `size` bytes) for `src`, reclaiming dropped sources and evicting
/// least-recently-used entries incrementally within the entry and byte caps.
pub(crate) fn insert(&mut self, key: &str, src: &Arc<Vec<u8>>, val: T, size: usize) {
if size > CACHE_BYTES {
return;
@@ -41,10 +75,22 @@ impl<T: Clone> MediaCache<T> {
self.bytes = self.bytes.saturating_sub(old.size);
}
if self.map.len() >= CACHE_ENTRIES || self.bytes.saturating_add(size) > CACHE_BYTES {
self.map.clear();
self.bytes = 0;
self.prune_dead();
}
self.map.insert(key.to_string(), Entry { src: Arc::downgrade(src), val, size });
while self.map.len() >= CACHE_ENTRIES || self.bytes.saturating_add(size) > CACHE_BYTES {
let Some(oldest) = self.map.iter().min_by_key(|(_, e)| e.stamp).map(|(k, _)| k.clone()) else {
break;
};
if let Some(removed) = self.map.remove(&oldest) {
self.bytes = self.bytes.saturating_sub(removed.size);
}
}
if self.map.capacity() > self.map.len().saturating_mul(4).max(32) {
self.map.shrink_to(self.map.len().saturating_mul(2).max(16));
}
self.clock = self.clock.wrapping_add(1);
let stamp = self.clock;
self.map.insert(key.to_string(), Entry { src: Arc::downgrade(src), val, size, stamp });
self.bytes = self.bytes.saturating_add(size);
}
}
@@ -58,12 +104,12 @@ pub(crate) type Decoded = Result<Arc<Pixmap>, Refusal>;
fn images() -> &'static Mutex<MediaCache<Decoded>> {
static C: std::sync::OnceLock<Mutex<MediaCache<Decoded>>> = std::sync::OnceLock::new();
C.get_or_init(|| Mutex::new(MediaCache { map: HashMap::new(), bytes: 0 }))
C.get_or_init(|| Mutex::new(MediaCache::default()))
}
fn vectors() -> &'static Mutex<MediaCache<Option<Arc<Vector>>>> {
static C: std::sync::OnceLock<Mutex<MediaCache<Option<Arc<Vector>>>>> = std::sync::OnceLock::new();
C.get_or_init(|| Mutex::new(MediaCache { map: HashMap::new(), bytes: 0 }))
C.get_or_init(|| Mutex::new(MediaCache::default()))
}
/// Largest side (pixels) a document picture may decode to: what a `Pixmap` can hold (`u16`
+2 -2
View File
@@ -572,7 +572,7 @@ fn pictures_too_large_for_the_cache_are_kept_smaller() {
assert!(bytes <= CACHE_BYTES / 2, "{} x {}", small.width(), small.height());
assert!(small.width() >= 3000 && small.width() == small.height(), "aspect kept");
assert!(small.data().iter().all(|p| (p.r, p.g, p.b, p.a) == (40, 80, 120, 200)), "flat stays flat");
let mut cache = MediaCache { map: HashMap::new(), bytes: 0 };
let mut cache = MediaCache::default();
// A source file larger than the whole cache (an uncompressed BMP, say) doesn't count against it.
let src = Arc::new(vec![0u8; CACHE_BYTES + 1]);
cache.insert("big", &src, Some(Arc::new(small)), bytes);
@@ -1237,7 +1237,7 @@ fn heavy_geometry_still_leaves_the_bitmaps_a_cacheable_size() {
assert!(size + geometry <= CACHE_BYTES, "{size} bytes");
// The shrunk picture is accepted by the cache and hit again.
let src = Arc::new(vec![0u8; 1]);
let mut c: MediaCache<u8> = MediaCache { map: Default::default(), bytes: 0 };
let mut c: MediaCache<u8> = MediaCache::default();
c.insert("heavy", &src, 7, size + geometry);
assert_eq!(c.get("heavy", &src), Some(7));
// Just under and just over the eighth: both shrink the bitmap to a positive size, none to nothing.
+196 -16
View File
@@ -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}");
}
+10 -1
View File
@@ -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 {
@@ -355,6 +363,7 @@ impl WordApp {
// draws, for itself.
self.window_work(ctx);
self.drain_inbox();
crate::keys::tick_paste_wait(self, ctx);
self.paste_arrived(ctx);
// Focus hides the title bar's search box: a search left open there has no box to show it, and would keep
// Escape from leaving Focus (#5398).
+25 -12
View File
@@ -348,7 +348,11 @@ impl WordApp {
let params = if fired.command.params.is_null() { json!({}) } else { fired.command.params.clone() };
let from_key = fired.source == FireSource::Key;
let (id, params) = if id == "edit.pasteFormat" && from_key { self.paste_format_command(ctx, params) } else { (id, params) };
let (id, params) = if id == "edit.pasteFormat" && from_key { self.paste_format_command(ctx, fired.mods, params) } else { (id, params) };
if from_key && id != "edit.pasteFormat" {
self.canvas.ignore_next_paste = false;
self.canvas.paste_wait_since = None;
}
// An Undo or Redo that is not a focused field's own edit (S-L187 sends that one to the
// field) first takes back the gesture under way and every running one (S-L364).
if matches!(id, "edit.undo" | "edit.redo") {
@@ -368,25 +372,34 @@ impl WordApp {
self.canvas.focus_page(ctx);
}
}
self.canvas.paste_event_consumed_same_frame = false;
}
/// Paste Formatting from its key. Mod+Shift+V pastes the formatting Mod+Shift+C (or the Format
/// Painter) picked up; with none picked up it pastes the clipboard as text only, as Word for
/// Windows does (#1537, #4943). Another key bound to Paste Formatting only pastes formatting.
/// The framework fires one command per chord, so nothing waits for a browser paste event.
fn paste_format_command(&self, ctx: &egui::Context, params: Value) -> (&'static str, Value) {
/// On platforms where a browser paste event follows Mod+Shift+V, pasting formatting arms
/// `ignore_next_paste` so that paired paste event is dropped.
fn paste_format_command(&mut self, ctx: &egui::Context, fired_mods: craft::keymap::Mods, params: Value) -> (&'static str, Value) {
let formatting = self.session.painter.is_some() || self.session.copied_format.is_some();
// The command runs a pass after its press, when a quick tap's modifiers are already up: with none held the fire
// is Mod+Shift+V's while that chord is still the command's.
let mods = ctx.input(|i| i.modifiers);
let chord = if mods.any() {
mods.command && mods.shift && !mods.alt
// `fired.mods` carries the chord's modifiers across every OS window, even after a quick
// tap releases the physical keys before `run_fired` runs.
let platform = if craft::ui::runtime::windows::os_of(ctx) == craft::host::target::Os::Mac {
craft::keymap::Platform::Mac
} else {
let default = Binding::parse("Mod+Shift+V").ok().map(|binding| binding.trigger.chord);
craft::ui::runtime::commands::bindings(ctx, &CommandRef::new("edit.pasteFormat"))
.iter()
.any(|binding| Some(binding.trigger.chord) == default)
craft::keymap::Platform::Windows
};
let eff = fired_mods.effective(platform);
let mod_shift = eff.cmd && eff.shift && !eff.alt && !eff.ctrl;
let default = Binding::parse("Mod+Shift+V").ok().map(|binding| binding.trigger.chord);
let chord = mod_shift
&& craft::ui::runtime::commands::bindings(ctx, &CommandRef::new("edit.pasteFormat"))
.iter()
.any(|binding| Some(binding.trigger.chord.effective(platform)) == default);
if formatting && chord && self.canvas.paste_event_follows_chord && !std::mem::take(&mut self.canvas.paste_event_consumed_same_frame) {
self.canvas.ignore_next_paste = true;
self.canvas.paste_wait_since = Some(ctx.input(|i| i.time));
}
if !formatting && chord { ("edit.pasteText", json!({})) } else { ("edit.pasteFormat", params) }
}
}
+67 -15
View File
@@ -10,6 +10,9 @@ use super::{
};
use crate::colors;
/// The document's own save stamps: zoom, last-modified-by, created, modified and revision.
type SaveStamps = (Option<wordcraft_doc::Zoom>, String, String, String, u32);
impl WordApp {
/// `run` for a command a mouse drag on a table sends: the view stays where it is.
pub(crate) fn run_keep_view(&mut self, id: &str, params: Value) -> Result<Value, String> {
@@ -34,6 +37,11 @@ impl WordApp {
/// Close, Envelopes, Labels and Finish & Merge on a document with unsaved changes first ask
/// Save / Don't Save / Cancel, and the command runs once that is answered (`ui.saveChanges`).
pub fn run(&mut self, id: &str, params: Value) -> Result<Value, String> {
if id == "file.close"
&& let Some(result) = self.raise_closing()
{
return Ok(result);
}
// Undo and Redo act on whole steps: a SmartArt typing run still open is folded into its one step first,
// or Undo would take back only the last keystroke of it.
if matches!(id, "edit.undo" | "edit.undoTo" | "edit.redo") {
@@ -109,6 +117,42 @@ impl WordApp {
r
}
/// File › Export's `copy` (#6131) writes a copy and never the document's own file. A host
/// page's Save writes the opened file under its own name and its flag can't say "copy", so a
/// copy named like the opened file would overwrite it with unsaved text; and `password`
/// changes the document's own later saves. Both are refused before anything is written.
fn copy_save(&self, id: &str, name: &str, params: &Value) -> Result<bool, String> {
let as_copy = params.get("copy").and_then(Value::as_bool) == Some(true);
if !as_copy {
return Ok(false);
}
let opened = self.session.path.as_ref().and_then(|p| p.file_name()).map(|n| n.to_string_lossy().to_string());
// Compare file names only: a copy given as a path still lands on the opened file's name.
let copy_name = std::path::Path::new(name).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| name.to_string());
if opened.as_deref() == Some(copy_name.as_str()) {
return Err("a copy can't have the same name as the open document: choose another name".into());
}
if matches!(id, "file.save" | "file.saveAs") && params.get("password").is_some_and(|pw| !pw.is_null()) {
return Err("`password` changes the document's own saves, so it can't come with `copy` (use file.encrypt)".into());
}
Ok(true)
}
/// A copy (File › Export, #6131) writes its bytes with fresh save stamps; the document's own
/// are then put back, so its next Save still goes to the original file.
fn restore_copy_stamps(&mut self, as_copy: bool, stamps: &SaveStamps) {
if as_copy {
let (zoom, by, created, modified, revision) = stamps;
(
self.session.doc.settings.zoom,
self.session.doc.core.last_modified_by,
self.session.doc.core.created,
self.session.doc.core.modified,
self.session.doc.core.revision,
) = (*zoom, by.clone(), created.clone(), modified.clone(), *revision);
}
}
/// Run a command for a script or an agent (control channel, MCP bridge): never asks first.
/// UI-level commands (`ui.*`) are handled here, the rest by the engine.
pub fn execute(&mut self, id: &str, params: Value) -> Result<Value, String> {
@@ -148,6 +192,9 @@ impl WordApp {
// Inspect only the suffix bytes: no full-name allocation or UTF-8 slicing.
let has_pdf_suffix = name.as_bytes().last_chunk::<4>().is_some_and(|suffix| suffix.eq_ignore_ascii_case(b".pdf"));
let name = if id == "file.exportPdf" && !has_pdf_suffix { format!("{name}.pdf") } else { name };
// `copy` (File › Export, #6131) writes a copy: the document keeps its unsaved changes,
// its name and its save stamps, as for a PDF.
let as_copy = self.copy_save(id, &name, &params)?;
// A save with a password encrypts this and later saves (`file.save`'s `password`).
if matches!(id, "file.save" | "file.saveAs")
&& let Some(pw) = params.get("password").filter(|v| !v.is_null())
@@ -167,6 +214,7 @@ impl WordApp {
self.session.doc.core.revision,
);
// A save is a save, download or not: advance the revision and modified stamp (#262).
// A copy carries fresh stamps too, but the document's own are put back after.
if matches!(id, "file.save" | "file.saveAs") {
self.session.stamp_save();
}
@@ -187,23 +235,26 @@ impl WordApp {
return Err(error);
}
};
self.restore_copy_stamps(as_copy, &before_stamp);
// An export is a copy, and so is a save in a format that doesn't keep everything (a
// page image, plain text): the document itself still has unsaved changes.
let marked_saved = matches!(id, "file.save" | "file.saveAs") && keeps_everything(&name);
let marked_saved = matches!(id, "file.save" | "file.saveAs") && !as_copy && keeps_everything(&name);
// The ticket's answer may be a failure: what the save stamped is put back then (`settle_saves`).
let undo_stamp: Option<Box<dyn FnOnce(&mut wordcraft_engine::Session)>> = matches!(id, "file.save" | "file.saveAs").then(|| {
let dirty = dirty_before;
Box::new(move |session: &mut wordcraft_engine::Session| {
(
session.doc.settings.zoom,
session.doc.core.last_modified_by,
session.doc.core.created,
session.doc.core.modified,
session.doc.core.revision,
) = before_stamp;
session.dirty = dirty;
}) as Box<dyn FnOnce(&mut wordcraft_engine::Session)>
});
// A copy already restored its stamps above, so settling it leaves the document's own stamps alone.
let undo_stamp: Option<Box<dyn FnOnce(&mut wordcraft_engine::Session)>> =
(matches!(id, "file.save" | "file.saveAs") && !as_copy).then(|| {
let dirty = dirty_before;
Box::new(move |session: &mut wordcraft_engine::Session| {
(
session.doc.settings.zoom,
session.doc.core.last_modified_by,
session.doc.core.created,
session.doc.core.modified,
session.doc.core.revision,
) = before_stamp;
session.dirty = dirty;
}) as Box<dyn FnOnce(&mut wordcraft_engine::Session)>
});
// Save As tells the host page the document is now this file, which it only is when the
// save marks it saved. A Save under a name the page never sent (an untitled document,
// an imported .doc saved as .docx) is a new file too, never an overwrite.
@@ -887,8 +938,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")));
}
+110 -31
View File
@@ -11,6 +11,10 @@ use super::{AutoSaveBlock, PromptSave, Value, WordApp, file_dialogs, i18n, json,
pub(crate) struct Closing {
/// Decides, one document at a time, what the operation does next.
pub guard: CloseGuard<u64>,
/// The window owning the current prompt. Quit advances the guard before installing its
/// next prompt, so keep that prompt's document binding separately.
pub window: u64,
pub document: u64,
/// The command that runs once every document is answered (a quit sets `quit_requested` instead).
pub then: String,
/// The held-back command's parameters; Don't Save adds `force` for a close.
@@ -28,29 +32,33 @@ impl WordApp {
/// Feed one answer to the guard and do what it says next. `all` is the prompt's "Apply to All".
fn apply_close_answer(&mut self, answer: CloseAnswer, all: bool) -> Result<Value, String> {
let document = self.session.document_id();
match self.closing.as_ref().map(|c| c.guard.current() != Some(&document)) {
None => return Err("no Save Changes prompt is open".into()),
Some(true) => {
self.cancel_closing();
return Err("the document the prompt asked about has been replaced".into());
}
Some(false) => {}
let Some((window, document)) = self.closing.as_ref().map(|c| (c.window, c.document)) else {
return Err("no Save Changes prompt is open".into());
};
if !self.activate_close_owner(window, document) {
self.cancel_closing();
return Err("the document the prompt asked about has been replaced".into());
}
if let Some(id) = self.closing.as_mut().and_then(|c| c.prompt.take()) {
self.close_prompt(id);
self.close_prompt(window, id);
}
let step = self.with_guard(|g| if all { g.answer_all(answer) } else { g.answer(answer) });
self.drive_guard(step, None)
let result = self.drive_guard(step, None);
if let Some(active) = self.windows.active() {
self.enter_window(active);
}
result
}
/// Start a close operation over `documents` (asked in this order) that ends by running `then`
/// (or, for a quit, by quitting), and ask about the first one.
pub(crate) fn begin_closing(&mut self, scope: CloseScope, documents: Vec<u64>, then: String, params: Value) -> Result<Value, String> {
// PLAN: shell-w6's `run` starts `file.close` and the other held-back commands through this
if let Some(result) = self.raise_closing() {
return Ok(result);
}
let guard = CloseGuard::new(scope, documents);
let step = guard.current().copied().map_or(GuardStep::Finished, GuardStep::Ask);
self.closing = Some(Closing { guard, then, params, prompt: None });
self.closing = Some(Closing { guard, then, params, prompt: None, window: self.windows.shown(), document: self.session.document_id() });
self.drive_guard(step, None)
}
@@ -68,6 +76,7 @@ impl WordApp {
GuardStep::Discard(doc) => {
self.discard_for_guard(doc);
step = self.with_guard(|g| g.discarded());
self.sync_document();
}
GuardStep::Save(doc) => {
if let Err(e) = self.show_guard_document(doc) {
@@ -114,7 +123,17 @@ impl WordApp {
}
fn show_guard_document(&mut self, doc: u64) -> Result<(), String> {
if doc == self.session.document_id() { Ok(()) } else { self.show_document(doc) }
if let Some(window) = self.closing.as_ref().filter(|c| c.document == doc).map(|c| c.window) {
if !self.activate_close_owner(window, doc) {
return Err("the document the prompt asked about has been replaced".into());
}
self.focus_window(window);
Ok(())
} else if doc == self.session.document_id() {
Ok(())
} else {
self.show_document(doc)
}
}
/// Show `doc` and open its Save Changes prompt, with `reason` under the message when the last
@@ -135,6 +154,8 @@ impl WordApp {
let id = self.dialog_host.open(dialog);
if let Some(closing) = self.closing.as_mut() {
closing.prompt = Some(id);
closing.window = self.windows.shown();
closing.document = doc;
}
Ok(json!({"pending": "saveChanges"}))
}
@@ -149,7 +170,6 @@ impl WordApp {
self.session.discard_recovery_copy();
} else {
let _ = self.session.close_document(doc);
self.sync_document();
}
} else if let Some(closing) = self.closing.as_mut() {
match closing.params.as_object_mut() {
@@ -168,30 +188,81 @@ impl WordApp {
self.quit_requested = true;
return Ok(json!({"quit": true}));
}
if !self.activate_close_owner(closing.window, closing.document) {
return Err("the document the prompt asked about has been replaced".into());
}
self.execute_held_back(&closing.then, closing.params).map(|r| json!({"done": true, "result": r}))
}
/// End the operation without running anything; the prompt closes with it.
fn cancel_closing(&mut self) {
if let Some(id) = self.closing.take().and_then(|c| c.prompt) {
self.close_prompt(id);
/// Activate the recorded owner, never an arbitrary view of the same document.
fn activate_close_owner(&mut self, window: u64, document: u64) -> bool {
if !self.session.is_open(document) || !self.window_has_document(window, document) {
return false;
}
// A caller may have switched the session before following it in the window state.
self.enter_window(window) && self.session.switch_document(document).is_ok()
}
/// Consume a repeated close and raise its prompt when its owner still exists. `None`
/// permits a new close; either existing outcome consumes this request, so cancelling an
/// obsolete operation cannot close an unrelated window or report that it is still pending.
pub(crate) fn raise_closing(&mut self) -> Option<Value> {
let (window, document) = self.closing.as_ref().map(|c| (c.window, c.document))?;
if self.activate_close_owner(window, document) {
self.focus_window(window);
Some(json!({"done": false, "pending": "close"}))
} else {
self.cancel_closing();
Some(json!({"done": false}))
}
}
/// Close prompt `id` from outside and drop the answer that leaves behind.
pub(crate) fn close_prompt(&mut self, id: DialogId) {
if let Some(ctx) = self.ctx.clone() {
crate::dialogs::chrome::forget_nudge(&ctx, id);
self.dialog_host.cancel_by_id(&ctx, id);
/// Release obsolete guards before pruning their hosts, even if the shown document did not
/// change. Quit can advance to its next document before syncing the one it just discarded.
pub(crate) fn reconcile_closing(&mut self) {
let obsolete = self.closing.as_ref().is_some_and(|c| {
c.guard.current().is_some_and(|doc| !self.session.is_open(*doc) || (*doc == c.document && !self.window_has_document(c.window, *doc)))
});
if obsolete {
self.cancel_closing();
}
}
/// End the operation without running anything; its owning window's prompt closes with it.
fn cancel_closing(&mut self) {
if let Some(closing) = self.closing.take()
&& let Some(id) = closing.prompt
{
self.close_prompt(closing.window, id);
}
}
fn close_prompt(&mut self, window: u64, id: DialogId) {
if let Some(ctx) = &self.ctx {
crate::dialogs::chrome::forget_nudge(ctx, id);
}
// Before the first frame no overlay state has been installed in a context. Remove
// the prompt now: a deferred close by its reused id would cancel a retry instead.
let ctx = self.ctx.clone().unwrap_or_default();
if let Some(host) = self.window_dialog_host_mut(window) {
host.cancel_by_id(&ctx, id);
let _ = host.take_by_id::<UnsavedChangesDialog>(id);
}
}
/// An embedded/full-screen root draws only this logical window. Its old window's question
/// must end too, rather than waiting forever in a host that no longer draws.
pub(crate) fn reconcile_single_window_close(&mut self, window: u64) {
if self.closing.as_ref().is_some_and(|c| c.window != window && c.guard.current() == Some(&c.document)) {
self.cancel_closing();
}
let _ = self.dialog_host.take_by_id::<UnsavedChangesDialog>(id);
}
/// Take the answer of the open Save Changes prompt, if the user gave one. Called every frame
/// from `logic`.
pub(crate) fn pump_close_prompt(&mut self) {
let Some(id) = self.closing.as_ref().and_then(|c| c.prompt) else { return };
let Some(result) = self.dialog_host.take_by_id::<UnsavedChangesDialog>(id) else { return };
let Some((window, id)) = self.closing.as_ref().and_then(|c| c.prompt.map(|id| (c.window, id))) else { return };
let Some(result) = self.window_dialog_host_mut(window).and_then(|host| host.take_by_id::<UnsavedChangesDialog>(id)) else { return };
if let Some(ctx) = self.ctx.as_ref() {
crate::dialogs::chrome::forget_nudge(ctx, id);
}
@@ -211,14 +282,19 @@ impl WordApp {
/// Whether the window may close now, for the platform's close request: `Hold` while a close
/// operation runs or only one window of several closes, else as [`Self::close_requested`].
pub fn close_decision(&mut self) -> CloseDecision {
if self.closing.is_none() && self.closes_a_window() {
if self.raise_closing().is_some() {
return CloseDecision::Hold;
}
if self.closes_a_window() {
// The root window's close button closes that window alone (File › Close in it, which asks
// about unsaved changes first); the framework leaves the root's window open on `Hold`, and
// the root entry moves to the window that stays.
let root = self.windows.root_key();
self.close_window(root);
CloseDecision::Hold
} else if self.closing.is_some() {
let key = if self.ctx.as_ref().is_some_and(|ctx| craft::ui::runtime::windows::WindowHost::of(ctx).opens_windows()) {
self.windows.root_key()
} else {
self.windows.shown()
};
self.close_window(key);
CloseDecision::Hold
} else if self.close_requested() {
CloseDecision::Close
@@ -462,6 +538,9 @@ impl WordApp {
/// changes are never discarded unasked: a dirty document closes only with `{"force": true}`
/// (Don't Save in the prompt passes it).
pub(super) fn close_document(&mut self, params: &Value) -> Result<Value, String> {
if let Some(result) = self.raise_closing() {
return Ok(result);
}
if self.closes_only_its_window("file.close", params) && self.close_window_only() {
return Ok(json!({"closed": true, "window": true}));
}
+33 -10
View File
@@ -16,12 +16,18 @@ use crate::i18n::Lang;
// PLAN(chrome-w12): build.rs embeds the craft faces into `craft_fonts.rs`
pub static CRAFT_FONTS: &[EmbeddedFace] = include!(concat!(env!("OUT_DIR"), "/craft_fonts.rs"));
/// The interface fonts for `lang`: the embedded craft faces, ordered by the language's scripts,
/// and installed system fonts loaded on demand where the platform has them.
/// The interface fonts for `lang`: WordCraft's own Inter and the embedded craft faces, ordered by the language's
/// scripts, and installed system fonts loaded on demand where the platform has them.
pub fn ui_fonts(lang: Lang) -> UiFonts<'static> {
ui_fonts_with_optional_faces(lang, CRAFT_FONTS)
}
/// [`ui_fonts`] with `faces` as the optional craft-fonts faces. Tests pass none, so the faces a CI build embeds
/// can't hide a character the interface's own faces lack.
pub(crate) fn ui_fonts_with_optional_faces(lang: Lang, faces: &[EmbeddedFace]) -> UiFonts<'static> {
let codes: Vec<&str> = Lang::all().map(Lang::code).collect();
let os_locale = wordcraft_engine::system_locale();
let fonts = UiFonts::new(&I18nScripts).craft_faces(CRAFT_FONTS).languages(&codes).ui_language(lang.code());
let fonts = UiFonts::new(&I18nScripts).craft_faces(&own_inter()).craft_faces(faces).languages(&codes).ui_language(lang.code());
let fonts = match os_locale {
Some(locale) => fonts.os_locale(locale),
None => fonts,
@@ -31,6 +37,21 @@ pub fn ui_fonts(lang: Lang) -> UiFonts<'static> {
fonts
}
/// WordCraft's own Inter Regular and SemiBold, from the bytes the document fonts embed. The suite's interface face is
/// the same Inter release cut to Latin, Greek and Cyrillic; tagged with those scripts, these come right after the
/// suite's faces and draw the rest of Inter (○ ✓ ★, the macOS key symbols) in the same design and row height, as the
/// interface did before it moved onto the shared font stack (#7101).
fn own_inter() -> [EmbeddedFace; 2] {
wordcraft_fonts::bundled_inter().map(|(style, bytes)| EmbeddedFace {
family: "Inter",
style,
scripts: &["Latn", "Grek", "Cyrl"],
index: 0,
bytes,
role: None,
})
}
#[cfg(test)]
/// One character of each script the app ships, to find the document fonts that cover it.
const FALLBACK_SAMPLES: [char; 6] = ['ع', 'א', 'ก', 'ა', 'ա', '汉'];
@@ -116,12 +137,12 @@ mod tests {
}
}
/// Symbols written as text in the interface code must exist in the interface fonts; a missing
/// glyph draws as an empty box, as the panes' "✕" close button once did. Letters are the
/// catalogs' business (see the i18n font tests).
/// Symbols written as text in the interface code must exist in the interface fonts, also in a build without the
/// optional craft-fonts faces; a missing glyph draws as an empty box, as the panes' "✕" close button once did.
/// Letters are the catalogs' business (see the i18n font tests).
#[test]
fn interface_symbols_have_glyphs() {
let stack = ui_fonts(Lang::EN).stack();
let stack = ui_fonts_with_optional_faces(Lang::EN, &[]).stack();
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
let mut symbols = BTreeSet::new();
// The i18n module's literals are catalog and pseudo-locale test text, not interface text.
@@ -154,9 +175,11 @@ mod tests {
symbols.retain(|(c, file)| !exempt(*c, file));
let files: Vec<(char, String)> = symbols.into_iter().collect();
let texts: Vec<(String, String)> = files.iter().map(|(c, f)| (c.to_string(), f.clone())).collect();
let samples = texts.iter().map(|(t, f)| Sample::new("en", f, t));
let missing = missing_glyphs(&stack, &FontRef::proportional(), samples, false);
assert!(missing.is_empty(), "symbols without a glyph: {missing:#?}");
for family in [FontRef::proportional(), FontRef::named(craft::ui::fonts::SEMIBOLD)] {
let samples = texts.iter().map(|(t, f)| Sample::new("en", f, t));
let missing = missing_glyphs(&stack, &family, samples, false);
assert!(missing.is_empty(), "symbols without a glyph in {family:?}: {missing:#?}");
}
}
/// An installed Arabic font is asked for only when Arabic text needs one (and no embedded
+4
View File
@@ -77,6 +77,10 @@ impl WordApp {
if !ClipboardHandle::of(ctx).arrived() {
return;
}
if std::mem::take(&mut self.canvas.ignore_next_paste) {
self.canvas.paste_wait_since = None;
return;
}
// PLAN(canvas-w9): cv.A10 `CanvasState::focused(&self, &egui::Context) -> bool`
if paste_target(self.canvas.focused(ctx), self.ui.backstage, self.modal_open()) {
let _ = self.run("edit.paste", json!({}));
+3
View File
@@ -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 };
+1 -1
View File
@@ -374,7 +374,7 @@ fn works_without_document(page: &str) -> bool {
/// The built-in templates in gallery order: display label and the `file.new` template id.
const TEMPLATES: [(&str, &str); 5] =
[("Blank document", "blank"), ("Studio handbook (sample)", "sample"), ("Letter", "letter"), ("Résumé", "resume"), ("Report", "report")];
[("Blank document", "blank"), ("Studio handbook", "sample"), ("Letter", "letter"), ("Résumé", "resume"), ("Report", "report")];
/// How many templates Home shows before "More templates" (the rest are on New).
const HOME_TEMPLATES: usize = 4;
+36 -1
View File
@@ -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)>,
@@ -257,11 +259,38 @@ pub struct CanvasState {
/// selection, and the document's own layout, which a view change replaces), so a still pointer
/// doesn't lay the document out every frame. Set only while the page shows the preview.
table_preview_layout: Option<(TablePreviewKey, wordcraft_doc::Document, wordcraft_engine::Selection, Arc<DocLayout>)>,
/// Snapshot of `session.doc` for `(document_id, rev)`, shared via `Arc::clone` across
/// unchanged frames instead of cloning the full `Document` every pass.
doc_snapshot: Option<((u64, u64), Arc<wordcraft_doc::Document>)>,
/// On the web, Mod+Shift+V pasted formatting from its key press: the browser's paste event
/// that follows is the same keystroke and pastes nothing (#5616). Any other key press, pointer
/// press, focus change, or wait past `PASTE_WAIT` clears it.
pub(crate) ignore_next_paste: bool,
/// Input time (seconds) when `ignore_next_paste` was armed.
pub(crate) paste_wait_since: Option<f64>,
/// Whether the platform sends a paste event after Mod+Shift+V's key (true on the web).
pub(crate) paste_event_follows_chord: bool,
/// The paired browser paste arrived and was dropped in the same frame as Mod+Shift+V, before
/// `run_fired` runs in the next frame.
pub(crate) paste_event_consumed_same_frame: bool,
}
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 +434,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,
@@ -454,6 +484,11 @@ impl Default for CanvasState {
list_preview: None,
preview_scroll: None,
table_preview_layout: None,
doc_snapshot: None,
ignore_next_paste: false,
paste_wait_since: None,
paste_event_follows_chord: cfg!(target_arch = "wasm32"),
paste_event_consumed_same_frame: false,
}
}
}
@@ -798,7 +833,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;
+5 -6
View File
@@ -151,12 +151,11 @@ fn rows(app: &mut WordApp, ui: &mut Ui) {
let _ = Menu::submenu_row(ui, tl!("Synonyms").to_string(), |ui, _cx| {
for w in syn.iter().filter_map(|x| x.as_str()) {
if MenuItem::new(w.to_string()).show(ui).ran {
let _ = app.run("select.word", json!({}));
let (a, b) = app.session.sel.ordered();
let trimmed = app.session.doc.para_at(&a).and_then(|p| p.text.get(a.off..b.off)).map(|t| t.trim_end().len()).unwrap_or(0);
let end = wordcraft_doc::Pos { off: a.off + trimmed, ..b };
app.session.set_selection(wordcraft_engine::Selection { anchor: a, focus: end });
let _ = app.run("text.insert", json!({"text": w, "raw": true}));
// The word the synonyms were looked up for: quotes around it stay (#6517).
if let Some((a, b)) = wordcraft_engine::cmd::review::thesaurus_word(&app.session) {
app.session.set_selection(wordcraft_engine::Selection { anchor: a, focus: b });
let _ = app.run("text.insert", json!({"text": w, "raw": true}));
}
}
}
});
+5 -1
View File
@@ -233,7 +233,11 @@ impl CanvasTool for PageTextTool<'_> {
if let Some((page, x, y, clicks)) = self.pointer_at(pointer.pos, pointer.clicks) {
let story = self.app.session.sel.focus.story;
let pp = PagePointer { layout: &layout, page, x, y, story, clicks };
if handle_completed_click(self.app, &pp) {
let completed = handle_completed_click(self.app, &pp);
self.app.canvas.dragging = false;
self.app.canvas.column_drag = None;
self.app.canvas.unit_drag = None;
if completed {
return;
}
}
+37 -8
View File
@@ -1,5 +1,17 @@
use std::fmt::Write as _;
use super::{DocLayout, Hash, Hasher, Page, Placed, Pos, Rect, WordApp, json};
/// Streams `Debug` formatting directly into a [`Hasher`] without intermediate `String` allocations.
struct HashFmt<'a>(&'a mut std::collections::hash_map::DefaultHasher);
impl std::fmt::Write for HashFmt<'_> {
fn write_str(&mut self, s: &str) -> std::fmt::Result {
self.0.write(s.as_bytes());
Ok(())
}
}
/// Fingerprint of everything outside the layout that changes how pages render: the view's
/// marks and markup, dark mode, the page colour and watermark, header/body dimming, the media,
/// and (while a drag lasts) the object left out of the page.
@@ -13,8 +25,8 @@ pub(super) fn view_key(app: &WordApp, dim_body: bool, hidden: Option<&Pos>) -> u
(v.read_mode, v.read_page_color, app.session.prefs.paper_color).hash(&mut h);
app.session.prefs.markup.hash(&mut h);
dim_body.hash(&mut h);
format!("{:?}{:?}{:?}", app.session.doc.settings.page_color, app.session.doc.settings.page_picture, app.session.doc.settings.watermark)
.hash(&mut h);
app.session.doc.settings.page_color.map(|c| (c.0, c.1, c.2)).hash(&mut h);
let _ = write!(HashFmt(&mut h), "{:?}|{:?}", app.session.doc.settings.page_picture, app.session.doc.settings.watermark);
app.session.doc.media.len().hash(&mut h);
// A page drawn without a dragged object must not pass for the page with it: the drag starts
// and ends change the key once each, so the page is rendered again then and only then.
@@ -30,22 +42,39 @@ pub(super) fn page_content_key(page: &Page) -> u64 {
for list in [&page.items, &page.header, &page.footer] {
list.len().hash(&mut h);
for it in list.iter() {
std::mem::discriminant(it).hash(&mut h);
match it {
Placed::Lines { para, l0, l1, x, y, turn, .. } => {
(std::sync::Arc::as_ptr(para) as usize, l0, l1, x.to_bits(), y.to_bits(), turn).hash(&mut h);
}
Placed::Fill { rect, color } => format!("{rect:?}{color:?}").hash(&mut h),
Placed::Rule { x0, y0, x1, y1, border } => format!("{x0}{y0}{x1}{y1}{border:?}").hash(&mut h),
Placed::Image { rect, media, crop, spin, fx, .. } => format!("{rect:?}{media}{crop:?}{spin:?}{fx:?}").hash(&mut h),
Placed::Fill { rect, color } => {
(rect.x.to_bits(), rect.y.to_bits(), rect.w.to_bits(), rect.h.to_bits(), color.0, color.1, color.2).hash(&mut h);
}
Placed::Rule { x0, y0, x1, y1, border } => {
(x0.to_bits(), y0.to_bits(), x1.to_bits(), y1.to_bits()).hash(&mut h);
let _ = write!(HashFmt(&mut h), "{border:?}");
}
Placed::Image { rect, media, crop, spin, fx, .. } => {
(rect.x.to_bits(), rect.y.to_bits(), rect.w.to_bits(), rect.h.to_bits()).hash(&mut h);
media.hash(&mut h);
for c in crop {
c.to_bits().hash(&mut h);
}
let _ = write!(HashFmt(&mut h), "{spin:?}|{fx:?}");
}
Placed::Shape { rect, kind, fill, stroke, stroke_width, effects, freeform, spin, extra, .. } => {
format!("{rect:?}{kind:?}{fill:?}{stroke:?}{stroke_width}{effects:?}{spin:?}{extra:?}").hash(&mut h);
(rect.x.to_bits(), rect.y.to_bits(), rect.w.to_bits(), rect.h.to_bits(), stroke_width.to_bits()).hash(&mut h);
freeform.as_ref().map(|f| std::sync::Arc::as_ptr(f) as usize).hash(&mut h);
let _ = write!(HashFmt(&mut h), "{kind:?}|{fill:?}|{stroke:?}|{effects:?}|{spin:?}|{extra:?}");
}
Placed::Graphic { rect, graphic, spin, .. } => {
(std::sync::Arc::as_ptr(graphic) as usize, rect.x.to_bits(), rect.y.to_bits(), rect.w.to_bits(), rect.h.to_bits()).hash(&mut h);
format!("{spin:?}").hash(&mut h)
let _ = write!(HashFmt(&mut h), "{spin:?}");
}
Placed::Clip { rect, spin, items } => {
(rect.x.to_bits(), rect.y.to_bits(), rect.w.to_bits(), rect.h.to_bits()).hash(&mut h);
let _ = write!(HashFmt(&mut h), "{spin:?}|{items:?}");
}
Placed::Clip { rect, spin, items } => format!("{rect:?}{spin:?}{items:?}").hash(&mut h),
Placed::Cell { .. } | Placed::Object { .. } => {}
}
}
+14 -1
View File
@@ -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);
}
+14 -2
View File
@@ -13,7 +13,7 @@ use wordcraft_doc::{Document, Pos};
use wordcraft_layout::DocLayout;
use super::WordApp;
use super::pages::{PageKeys, page_doc, page_render_options, page_shows, view_key};
use super::pages::{PageKeys, page_render_options, page_shows, view_key};
/// A page dimension (points) safe to lay out: finite, at least 1 pt, at most `cap`.
fn dim(v: f32, cap: f32) -> f64 {
@@ -38,7 +38,19 @@ impl WordPages {
pub(super) fn new(app: &mut WordApp, layout: &Arc<DocLayout>, dim_body: bool, hidden: Option<(usize, Pos)>) -> Self {
let view = view_key(app, dim_body, hidden.as_ref().map(|(_, p)| p));
let options = page_render_options(app, dim_body);
let doc = Arc::new(page_doc(app).clone());
let doc = if let Some((_, preview, _, _)) = &app.canvas.table_preview_layout {
Arc::new(preview.clone())
} else {
let key = (app.session.document_id(), app.session.rev());
match &app.canvas.doc_snapshot {
Some((k, snap)) if *k == key => Arc::clone(snap),
_ => {
let snap = Arc::new(app.session.doc.clone());
app.canvas.doc_snapshot = Some((key, Arc::clone(&snap)));
snap
}
}
};
WordPages { doc, layout: layout.clone(), keys: RefCell::new(std::mem::take(&mut app.canvas.page_keys)), view, options, hidden }
}
+192
View File
@@ -17,6 +17,47 @@ fn rest_for_tip(h: &mut H) {
mod markup;
mod overlays;
/// A double-click in the body while editing a header closes the header and ends the gesture.
#[test]
fn double_clicking_body_while_editing_header_clears_drag_state() {
use egui::{Event, PointerButton};
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("Body text")), Default::default());
app.run("insert.header", json!({"text": "Header text"})).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| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
app,
);
for _ in 0..6 {
h.app_frame();
}
let caret = h.state_mut().session.layout().caret(&Pos::body(0, 0)).expect("body text caret");
let at = page_to_screen(h.state_mut(), caret.page, caret.x as f32, caret.top + caret.height * 0.5).expect("body text is on screen");
let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() };
h.event(Event::PointerMoved(at));
for click in 0..2 {
h.event(button(true));
h.app_frame();
if click == 1 {
assert!(h.state().canvas.dragging, "the second press starts the gesture");
assert!(h.state().canvas.unit_drag.is_none(), "the header switch disables word dragging");
}
h.event(button(false));
h.app_frame();
if click == 0 {
h.app_frame();
}
}
assert_eq!(h.state().session.sel.focus.story, StoryRef::Body, "the double-click closes the header");
assert!(!h.state().canvas.dragging, "the press/release gesture has ended");
assert!(h.state().canvas.column_drag.is_none(), "column drag state has ended");
assert!(h.state().canvas.unit_drag.is_none(), "unit drag state has ended");
}
/// #3931: while Insert › Table's grid asks for a preview the page is laid out with that
/// table; the document, its revision and undo history stay as they were, and without a
/// request the page is the document's own again.
@@ -36,6 +77,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 +2663,137 @@ fn the_caret_blinks_only_while_the_window_is_active() {
h.app_frame();
assert!(next_frame(&h) <= blink, "active again, the caret blinks again");
}
#[test]
fn word_pages_reuses_doc_snapshot_across_unchanged_frames_and_invalidates_on_edit() {
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("hello")), Default::default());
let layout = app.session.layout();
let first = super::source::WordPages::new(&mut app, &layout, false, None);
let doc1 = first.doc();
app.canvas.page_keys = first.into_keys();
let second = super::source::WordPages::new(&mut app, &layout, false, None);
let doc2 = second.doc();
app.canvas.page_keys = second.into_keys();
assert!(std::sync::Arc::ptr_eq(&doc1, &doc2), "unchanged frame reuses cached Arc<Document> snapshot");
app.run("text.insert", json!({"text": " world"})).unwrap();
let layout2 = app.session.layout();
let third = super::source::WordPages::new(&mut app, &layout2, false, None);
let doc3 = third.doc();
app.canvas.page_keys = third.into_keys();
assert!(!std::sync::Arc::ptr_eq(&doc1, &doc3), "editing document invalidates cached snapshot");
assert_eq!(doc3.plain_text(wordcraft_doc::StoryRef::Body), " worldhello");
}
/// #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");
}
+80 -5
View File
@@ -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");
}
}
+1 -1
View File
@@ -10,7 +10,7 @@
//! - `ui.clickText {page, x, y}`: click at a page position (points from the page's top-left)
//! - `ui.dialog.set`, `ui.dialog.confirm`, `ui.dialog.cancel`: the open dialogs' fields and answers
//! - `ui.screenshot {path?, region?}`: PNG of the window (or of `region` `[x0, y0, x1, y1]` in points); `ui.render {path?, page?, scale?}`: page PNG
//! (without `path`, both reply with the PNG as base64 `png`)
//! (without `path`, the reply carries the PNG as base64: `base64` for a screenshot, `png` for a render)
//! - `ui.resize`, `ui.focus`, `ui.closeWindow`, `ui.clipboard`, `ui.replayAt`, `ui.accessTree`
//! - `ui.parity`: feature catalog parity
//!

Some files were not shown because too many files have changed in this diff Show More